/** * * 转换短链接 * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX), * 减小二维码数据量,提升扫描速度和精确度。 * @param WxPayData inputObj 提交给转换短连接API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData ShortUrl(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/tools/shorturl"; //检测必填参数 if (!inputObj.IsSet("long_url")) { throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now; //请求开始时间 WxLog.Debug("WxPayApi", "ShortUrl request : " + xml); string response = WxHttpService.Post(xml, url, false, timeOut); WxLog.Debug("WxPayApi", "ShortUrl response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result); //测速上报 return(result); }
/** * * 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下: * { * "access_token":"ACCESS_TOKEN", * "expires_in":7200, * "refresh_token":"REFRESH_TOKEN", * "openid":"OPENID", * "scope":"SCOPE", * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" * } * 其中access_token可用于获取共享收货地址 * openid是微信支付jsapi支付接口统一下单时必须的参数 * 更详细的说明请参考网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html * @失败时抛异常WxPayException */ public void GetOpenidAndAccessTokenFromCode(string code) { try { //构造获取openid及access_token的url WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("secret", WxPayConfig.APPSECRET); data.SetValue("code", code); data.SetValue("grant_type", "authorization_code"); string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl(); //请求url以获取数据 string result = WxHttpService.Get(url); WxLog.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result); //保存access_token,用于收货地址获取 JsonData jd = JsonMapper.ToObject(result); access_token = (string)jd["access_token"]; //获取用户openid openid = (string)jd["openid"]; WxLog.Debug(this.GetType().ToString(), "Get openid : " + openid); WxLog.Debug(this.GetType().ToString(), "Get access_token : " + access_token); } catch (Exception ex) { WxLog.Error(this.GetType().ToString(), ex.ToString()); throw new WxPayException(ex.ToString()); } }
/** * * 检测签名是否正确 * 正确返回true,错误抛异常 */ public bool CheckSign() { //如果没有设置签名,则跳过检测 if (!IsSet("sign")) { WxLog.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!"); throw new WxPayException("WxPayData签名存在但不合法!"); } //如果设置了签名但是签名为空,则抛异常 else if (GetValue("sign") == null || GetValue("sign").ToString() == "") { WxLog.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!"); throw new WxPayException("WxPayData签名存在但不合法!"); } //获取接收到的签名 string return_sign = GetValue("sign").ToString(); //在本地计算新的签名 string cal_sign = MakeSign(); if (cal_sign == return_sign) { return(true); } WxLog.Error(this.GetType().ToString(), "WxPayData签名验证错误!"); throw new WxPayException("WxPayData签名验证错误!"); }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查支付结果中transaction_id是否存在 if (!notifyData.IsSet("transaction_id")) { //若transaction_id不存在,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "支付结果中微信订单号不存在"); WxLog.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml()); } string transaction_id = notifyData.GetValue("transaction_id").ToString(); //查询订单,判断订单真实性 if (!QueryOrder(transaction_id)) { //若订单查询失败,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "订单查询失败"); WxLog.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml()); } //查询订单成功 else { WxPayData res = new WxPayData(); res.SetValue("return_code", "SUCCESS"); res.SetValue("return_msg", "OK"); WxLog.Info(this.GetType().ToString(), "order query success : " + res.ToXml()); } }
/** * * 撤销订单API接口 * @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回API调用结果,其他抛异常 */ public static WxPayData Reverse(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 WxLog.Debug("WxPayApi", "Reverse request : " + xml); string response = WxHttpService.Post(xml, url, true, timeOut); WxLog.Debug("WxPayApi", "Reverse response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
/** * 调用统一下单,获得下单结果 * @return 统一下单结果 * @失败时抛异常WxPayException */ public WxPayData GetUnifiedOrderResult(VWPayOrderEntity _order) { //统一下单 WxPayData data = new WxPayData(); data.SetValue("body", "易店心,订单号:" + _order.SysOrderCode); data.SetValue("attach", ""); data.SetValue("out_trade_no", _order.PayOrderCode);/*WxPayApi.GenerateOutTradeNo()*/ data.SetValue("total_fee", (_order.NeedPayPrice * 100).ToString()); data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); data.SetValue("goods_tag", ""); data.SetValue("trade_type", "JSAPI"); data.SetValue("openid", openid); WxPayData result = WxPayApi.UnifiedOrder(data); if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "") { WxLog.Error(this.GetType().ToString(), "UnifiedOrder response error!"); throw new WxPayException("UnifiedOrder response error!"); } unifiedOrderResult = result; return(result); }
/*** * 退款查询完整业务流程逻辑 * @param refund_id 微信退款单号(优先使用) * @param out_refund_no 商户退款单号 * @param transaction_id 微信订单号 * @param out_trade_no 商户订单号 * @return 退款查询结果(xml格式) */ public static string Run(string refund_id, string out_refund_no, string transaction_id, string out_trade_no) { WxLog.Info("RefundQuery", "RefundQuery is processing..."); WxPayData data = new WxPayData(); if (!string.IsNullOrEmpty(refund_id)) { data.SetValue("refund_id", refund_id);//微信退款单号,优先级最高 } else if (!string.IsNullOrEmpty(out_refund_no)) { data.SetValue("out_refund_no", out_refund_no);//商户退款单号,优先级第二 } else if (!string.IsNullOrEmpty(transaction_id)) { data.SetValue("transaction_id", transaction_id);//微信订单号,优先级第三 } else { data.SetValue("out_trade_no", out_trade_no);//商户订单号,优先级最低 } WxPayData result = WxPayApi.RefundQuery(data);//提交退款查询给API,接收返回数据 WxLog.Info("RefundQuery", "RefundQuery process complete, result : " + result.ToXml()); return(result.ToPrintStr()); }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查openid和product_id是否返回 if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "回调数据异常"); WxLog.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml()); return; } //调统一下单接口,获得下单结果 string openid = notifyData.GetValue("openid").ToString(); string product_id = notifyData.GetValue("product_id").ToString(); WxPayData unifiedOrderResult = new WxPayData(); try { unifiedOrderResult = UnifiedOrder(openid, product_id); } catch (Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台 { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); WxLog.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); return; } //若下单失败,则立即返回结果给微信支付后台 if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); WxLog.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); return; } //统一下单成功,则返回成功结果给微信支付后台 WxPayData data = new WxPayData(); data.SetValue("return_code", "SUCCESS"); data.SetValue("return_msg", "OK"); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("mch_id", WxPayConfig.MCHID); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id")); data.SetValue("result_code", "SUCCESS"); data.SetValue("err_code_des", "OK"); data.SetValue("sign", data.MakeSign()); WxLog.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml()); return; }
/*** * 下载对账单完整业务流程逻辑 * @param bill_date 下载对账单的日期(格式:20140603,一次只能下载一天的对账单) * @param bill_type 账单类型 * ALL,返回当日所有订单信息,默认值 * SUCCESS,返回当日成功支付的订单 * REFUND,返回当日退款订单 * REVOKED,已撤销的订单 * @return 对账单结果(xml格式) */ public static string Run(string bill_date, string bill_type) { WxLog.Info("DownloadBill", "DownloadBill is processing..."); WxPayData data = new WxPayData(); data.SetValue("bill_date", bill_date); //账单日期 data.SetValue("bill_type", bill_type); //账单类型 WxPayData result = WxPayApi.DownloadBill(data); //提交下载对账单请求给API,接收返回结果 WxLog.Info("DownloadBill", "DownloadBill process complete, result : " + result.ToXml()); return(result.ToPrintStr()); }
/** * * 申请退款 * @param WxPayData inputObj 提交给申请退款API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回接口调用结果,其他抛异常 */ public static WxPayData Refund(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!"); } else if (!inputObj.IsSet("out_refund_no")) { throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("退款申请接口中,缺少必填参数total_fee!"); } else if (!inputObj.IsSet("refund_fee")) { throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!"); } else if (!inputObj.IsSet("op_user_id")) { throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now; WxLog.Debug("WxPayApi", "Refund request : " + xml); string response = WxHttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API WxLog.Debug("WxPayApi", "Refund response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
/** * 提交被扫支付API * 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台, * 由商户收银台或者商户后台调用该接口发起支付。 * @param WxPayData inputObj 提交给被扫支付API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回调用结果,其他抛异常 */ public static WxPayData Micropay(WxPayData inputObj, int timeOut = 10) { string url = "https://api.mch.weixin.qq.com/pay/micropay"; //检测必填参数 if (!inputObj.IsSet("body")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数body!"); } else if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数out_trade_no!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数total_fee!"); } else if (!inputObj.IsSet("auth_code")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数auth_code!"); } inputObj.SetValue("spbill_create_ip", WxPayConfig.IP); //终端ip inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 WxLog.Debug("WxPayApi", "MicroPay request : " + xml); string response = WxHttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API WxLog.Debug("WxPayApi", "MicroPay response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
/** * @values格式化成能在Web页面上显示的结果(因为web页面上不能直接输出xml格式的字符串) */ public string ToPrintStr() { string str = ""; foreach (KeyValuePair <string, object> pair in m_values) { if (pair.Value == null) { WxLog.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!"); throw new WxPayException("WxPayData内部含有值为null的字段!"); } str += string.Format("{0}={1}<br>", pair.Key, pair.Value.ToString()); } return(str); }
/** * * 测速上报接口实现 * @param WxPayData inputObj 提交给测速上报接口的参数 * @param int timeOut 测速上报接口超时时间 * @throws WxPayException * @return 成功时返回测速上报接口返回的结果,其他抛异常 */ public static WxPayData Report(WxPayData inputObj, int timeOut = 1) { string url = "https://api.mch.weixin.qq.com/payitil/report"; //检测必填参数 if (!inputObj.IsSet("interface_url")) { throw new WxPayException("接口URL,缺少必填参数interface_url!"); } if (!inputObj.IsSet("return_code")) { throw new WxPayException("返回状态码,缺少必填参数return_code!"); } if (!inputObj.IsSet("result_code")) { throw new WxPayException("业务结果,缺少必填参数result_code!"); } if (!inputObj.IsSet("user_ip")) { throw new WxPayException("访问接口IP,缺少必填参数user_ip!"); } if (!inputObj.IsSet("execute_time_")) { throw new WxPayException("接口耗时,缺少必填参数execute_time_!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("user_ip", WxPayConfig.IP); //终端ip inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss")); //商户上报时间 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); WxLog.Info("WxPayApi", "Report request : " + xml); string response = WxHttpService.Post(xml, url, false, timeOut); WxLog.Info("WxPayApi", "Report response : " + response); WxPayData result = new WxPayData(); result.FromXml(response); return(result); }
/** * * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数, * 微信浏览器调起JSAPI时的输入参数格式如下: * { * "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 * "timeStamp":" 1395712654", //时间戳,自1970年以来的秒数 * "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 * "package" : "prepay_id=u802345jgfjsdfgsdg888", * "signType" : "MD5", //微信签名方式: * "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 * } * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用 * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7 * */ public string GetJsApiParameters() { WxLog.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing..."); WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", WxPayConfig.APPID); jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string parameters = jsApiParam.ToJson(); WxLog.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters); return(parameters); }
/** * 生成扫描支付模式一URL * @param productId 商品ID * @return 模式一URL */ public string GetPrePayUrl(string productId) { WxLog.Info(this.GetType().ToString(), "Native pay mode 1 url is producing..."); WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); //公众帐号id data.SetValue("mch_id", WxPayConfig.MCHID); //商户号 data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp()); //时间戳 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 data.SetValue("product_id", productId); //商品ID data.SetValue("sign", data.MakeSign()); //签名 string str = ToUrlParams(data.GetValues()); //转换为URL串 string url = "weixin://wxpay/bizpayurl?" + str; WxLog.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url); return(url); }
/*** * 订单查询完整业务流程逻辑 * @param transaction_id 微信订单号(优先使用) * @param out_trade_no 商户订单号 * @return 订单查询结果(xml格式) */ public static string Run(string transaction_id, string out_trade_no) { WxLog.Info("OrderQuery", "OrderQuery is processing..."); WxPayData data = new WxPayData(); if (!string.IsNullOrEmpty(transaction_id))//如果微信订单号存在,则以微信订单号为准 { data.SetValue("transaction_id", transaction_id); } else//微信订单号不存在,才根据商户订单号去查单 { data.SetValue("out_trade_no", out_trade_no); } WxPayData result = WxPayApi.OrderQuery(data);//提交订单查询请求给API,接收返回数据 WxLog.Info("OrderQuery", "OrderQuery process complete, result : " + result.ToXml()); return(result.ToPrintStr()); }
/** * @Dictionary格式转化成url参数格式 * @ return url格式串, 该串不包含sign字段值 */ public string ToUrl() { string buff = ""; foreach (KeyValuePair <string, object> pair in m_values) { if (pair.Value == null) { WxLog.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!"); throw new WxPayException("WxPayData内部含有值为null的字段!"); } if (pair.Key != "sign" && pair.Value.ToString() != "") { buff += pair.Key + "=" + pair.Value + "&"; } } buff = buff.Trim('&'); return(buff); }
/// <summary> /// 接收从微信支付后台发送过来的数据并验证签名 /// </summary> /// <returns>微信支付后台返回的数据</returns> public WxPayData GetNotifyData() { //接收从微信后台POST过来的数据 System.IO.Stream s = HttpContext.Current.Request.InputStream; int count = 0; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); WxLog.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString()); //转换数据格式并验证签名 WxPayData data = new WxPayData(); try { data.FromXml(builder.ToString()); } catch (WxPayException ex) { ////若签名错误,则立即返回结果给微信支付后台 //WxPayData res = new WxPayData(); data.SetValue("return_code", "FAIL"); data.SetValue("return_msg", ex.Message); WxLog.Error(this.GetType().ToString(), "Sign check error : " + data.ToXml()); } WxLog.Info(this.GetType().ToString(), "Check sign success"); return(data); }
/** * * 查询退款 * 提交退款申请后,通过该接口查询退款状态。退款有一定延时, * 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 * out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个 * @param WxPayData inputObj 提交给查询退款API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData RefundQuery(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/refundquery"; //检测必填参数 if (!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id")) { throw new WxPayException("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now; //请求开始时间 WxLog.Debug("WxPayApi", "RefundQuery request : " + xml); string response = WxHttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API WxLog.Debug("WxPayApi", "RefundQuery response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result); //测速上报 return(result); }
/** * 下载对账单 * @param WxPayData inputObj 提交给下载对账单API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData DownloadBill(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/downloadbill"; //检测必填参数 if (!inputObj.IsSet("bill_date")) { throw new WxPayException("对账单接口中,缺少必填参数bill_date!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); WxLog.Debug("WxPayApi", "DownloadBill request : " + xml); string response = WxHttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API WxLog.Debug("WxPayApi", "DownloadBill result : " + response); WxPayData result = new WxPayData(); //若接口调用失败会返回xml格式的结果 if (response.Substring(0, 5) == "<xml>") { result.FromXml(response); } //接口调用成功则返回非xml格式的数据 else { result.SetValue("result", response); } return(result); }
/** * @将Dictionary转成xml * @return 经转换得到的xml串 * @throws WxPayException **/ public string ToXml() { //数据为空时不能转化为xml格式 if (0 == m_values.Count) { WxLog.Error(this.GetType().ToString(), "WxPayData数据为空!"); throw new WxPayException("WxPayData数据为空!"); } string xml = "<xml>"; foreach (KeyValuePair <string, object> pair in m_values) { //字段值不能为null,会影响后续流程 if (pair.Value == null) { WxLog.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!"); throw new WxPayException("WxPayData内部含有值为null的字段!"); } if (pair.Value.GetType() == typeof(int)) { xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">"; } else if (pair.Value.GetType() == typeof(string)) { xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">"; } else//除了string和int类型不能含有其他数据类型 { WxLog.Error(this.GetType().ToString(), "WxPayData字段数据类型错误!"); throw new WxPayException("WxPayData字段数据类型错误!"); } } xml += "</xml>"; return(xml); }
/*** * 申请退款完整业务流程逻辑 * @param transaction_id 微信订单号(优先使用) * @param out_trade_no 商户订单号 * @param total_fee 订单总金额 * @param refund_fee 退款金额 * @return 退款结果(xml格式) */ public static string Run(PayOrderRebackEntity reback) { WxLog.Info("Refund", "Refund is processing..."); WxPayData data = new WxPayData(); if (!string.IsNullOrEmpty(reback.ExternalCode))//微信订单号存在的条件下,则已微信订单号为准 { data.SetValue("transaction_id", reback.ExternalCode); } else//微信订单号不存在,才根据商户订单号去退款 { data.SetValue("out_trade_no", reback.PayOrderCode); } data.SetValue("total_fee", int.Parse((reback.TotalPrice * 100).ToString())); //订单总金额 data.SetValue("refund_fee", int.Parse((reback.RebackPrice * 100).ToString())); //退款金额 data.SetValue("out_refund_no", reback.PayRebackCode); //随机生成商户退款单号 data.SetValue("op_user_id", WxPayConfig.MCHID); //操作员,默认为商户号 WxPayData result = WxPayApi.Refund(data); //提交退款申请给API,接收返回数据 WxLog.Info("Refund", "Refund process complete, result : " + result.ToXml()); return(result.ToPrintStr()); }
/** * @将xml转为WxPayData对象并返回对象内部的数据 * @param string 待转换的xml串 * @return 经转换得到的Dictionary * @throws WxPayException */ public SortedDictionary <string, object> FromXml(string xml) { if (string.IsNullOrEmpty(xml)) { WxLog.Error(this.GetType().ToString(), "将空的xml串转换为WxPayData不合法!"); throw new WxPayException("将空的xml串转换为WxPayData不合法!"); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml> XmlNodeList nodes = xmlNode.ChildNodes; foreach (XmlNode xn in nodes) { XmlElement xe = (XmlElement)xn; m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中 } try { //2015-06-29 错误是没有签名 if (m_values["return_code"] != "SUCCESS") { return(m_values); } CheckSign();//验证签名,不通过会抛异常 } catch (WxPayException ex) { throw new WxPayException(ex.Message); } return(m_values); }
/** * * 统一下单 * @param WxPaydata inputObj 提交给统一下单API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("缺少统一支付接口必填参数out_trade_no!"); } else if (!inputObj.IsSet("body")) { throw new WxPayException("缺少统一支付接口必填参数body!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("缺少统一支付接口必填参数total_fee!"); } else if (!inputObj.IsSet("trade_type")) { throw new WxPayException("缺少统一支付接口必填参数trade_type!"); } //关联参数 if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) { throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); } if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) { throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); } //异步通知url未设置,则使用配置文件中的url if (!inputObj.IsSet("notify_url")) { inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("spbill_create_ip", SuperMarket.Core.Sys.Misc.IPAddress); //终端ip inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); var start = DateTime.Now; WxLog.Debug("WxPayApi", "UnfiedOrder request : " + xml); string response = WxHttpService.Post(xml, url, false, timeOut); WxLog.Debug("WxPayApi", "UnfiedOrder response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
public static string Post(string xml, string url, bool isUseCert, int timeout) { System.GC.Collect(); //垃圾回收,回收没有正常关闭的http连接 string result = ""; //返回结果 HttpWebRequest request = null; HttpWebResponse response = null; Stream reqStream = null; try { //设置最大连接数 ServicePointManager.DefaultConnectionLimit = 200; //设置https验证方式 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } /*************************************************************** * 下面设置HttpWebRequest的相关属性 * ************************************************************/ request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = timeout * 1000; //设置代理服务器 //WebProxy proxy = new WebProxy(); //定义一个网关对象 //proxy.Address = new Uri(WxPayConfig.PROXY_URL); //网关服务器端口:端口 //request.Proxy = proxy; //设置POST的数据类型和长度 request.ContentType = "text/xml"; byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); request.ContentLength = data.Length; //是否使用证书 if (isUseCert) { string path = HttpContext.Current.Request.PhysicalApplicationPath; X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD); request.ClientCertificates.Add(cert); WxLog.Debug("WxPayApi", "PostXml used cert"); } //往服务器写入数据 reqStream = request.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); //获取服务端返回 response = (HttpWebResponse)request.GetResponse(); //获取服务端返回数据 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = sr.ReadToEnd().Trim(); sr.Close(); } catch (System.Threading.ThreadAbortException e) { WxLog.Error("HttpService", "Thread - caught ThreadAbortException - resetting."); WxLog.Error("Exception message: {0}", e.Message); System.Threading.Thread.ResetAbort(); } catch (WebException e) { WxLog.Error("HttpService", e.ToString()); if (e.Status == WebExceptionStatus.ProtocolError) { WxLog.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode); WxLog.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription); } throw new WxPayException(e.ToString()); } catch (Exception e) { WxLog.Error("HttpService", e.ToString()); throw new WxPayException(e.ToString()); } finally { //关闭连接和流 if (response != null) { response.Close(); } if (request != null) { request.Abort(); } } return(result); }
/** * 刷卡支付完整业务流程逻辑 * @param body 商品描述 * @param total_fee 总金额 * @param auth_code 支付授权码 * @throws WxPayException * @return 刷卡支付结果 */ public static string Run(string body, string total_fee, string auth_code) { WxLog.Info("MicroPay", "Micropay is processing..."); WxPayData data = new WxPayData(); data.SetValue("auth_code", auth_code); //授权码 data.SetValue("body", body); //商品描述 data.SetValue("total_fee", int.Parse(total_fee)); //总金额 data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo()); //产生随机的商户订单号 WxPayData result = WxPayApi.Micropay(data, 10); //提交被扫支付,接收返回结果 //如果提交被扫支付接口调用失败,则抛异常 if (!result.IsSet("return_code") || result.GetValue("return_code").ToString() == "FAIL") { string returnMsg = result.IsSet("return_msg") ? result.GetValue("return_msg").ToString() : ""; WxLog.Error("MicroPay", "Micropay API interface call failure, result : " + result.ToXml()); throw new WxPayException("Micropay API interface call failure, return_msg : " + returnMsg); } //签名验证 result.CheckSign(); WxLog.Debug("MicroPay", "Micropay response check sign success"); //刷卡支付直接成功 if (result.GetValue("return_code").ToString() == "SUCCESS" && result.GetValue("result_code").ToString() == "SUCCESS") { WxLog.Debug("MicroPay", "Micropay business success, result : " + result.ToXml()); return(result.ToPrintStr()); } /****************************************************************** * 剩下的都是接口调用成功,业务失败的情况 * ****************************************************************/ //1)业务结果明确失败 if (result.GetValue("err_code").ToString() != "USERPAYING" && result.GetValue("err_code").ToString() != "SYSTEMERROR") { WxLog.Error("MicroPay", "micropay API interface call success, business failure, result : " + result.ToXml()); return(result.ToPrintStr()); } //2)不能确定是否失败,需查单 //用商户订单号去查单 string out_trade_no = data.GetValue("out_trade_no").ToString(); //确认支付是否成功,每隔一段时间查询一次订单,共查询10次 int queryTimes = 10; //查询次数计数器 while (queryTimes-- > 0) { int succResult = 0; //查询结果 WxPayData queryResult = Query(out_trade_no, out succResult); //如果需要继续查询,则等待2s后继续 if (succResult == 2) { Thread.Sleep(2000); continue; } //查询成功,返回订单查询接口返回的数据 else if (succResult == 1) { WxLog.Debug("MicroPay", "Mircopay success, return order query result : " + queryResult.ToXml()); return(queryResult.ToPrintStr()); } //订单交易失败,直接返回刷卡支付接口返回的结果,失败原因会在err_code中描述 else { WxLog.Error("MicroPay", "Micropay failure, return micropay result : " + result.ToXml()); return(result.ToPrintStr()); } } //确认失败,则撤销订单 WxLog.Error("MicroPay", "Micropay failure, Reverse order is processing..."); if (!Cancel(out_trade_no)) { WxLog.Error("MicroPay", "Reverse order failure"); throw new WxPayException("Reverse order failure!"); } return(result.ToPrintStr()); }
/// <summary> /// 处理http GET请求,返回数据 /// </summary> /// <param name="url">请求的url地址</param> /// <returns>http GET成功后返回的数据,失败抛WebException异常</returns> public static string Get(string url) { System.GC.Collect(); string result = ""; HttpWebRequest request = null; HttpWebResponse response = null; //请求url以获取数据 try { //设置最大连接数 ServicePointManager.DefaultConnectionLimit = 200; //设置https验证方式 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } /*************************************************************** * 下面设置HttpWebRequest的相关属性 * ************************************************************/ request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //设置代理 //WebProxy proxy = new WebProxy(); //proxy.Address = new Uri(WxPayConfig.PROXY_URL); //request.Proxy = proxy; //获取服务器返回 response = (HttpWebResponse)request.GetResponse(); //获取HTTP返回数据 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = sr.ReadToEnd().Trim(); sr.Close(); } catch (System.Threading.ThreadAbortException e) { WxLog.Error("HttpService", "Thread - caught ThreadAbortException - resetting."); WxLog.Error("Exception message: {0}", e.Message); System.Threading.Thread.ResetAbort(); } catch (WebException e) { WxLog.Error("HttpService", e.ToString()); if (e.Status == WebExceptionStatus.ProtocolError) { WxLog.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode); WxLog.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription); } throw new WxPayException(e.ToString()); } catch (Exception e) { WxLog.Error("HttpService", e.ToString()); throw new WxPayException(e.ToString()); } finally { //关闭连接和流 if (response != null) { response.Close(); } if (request != null) { request.Abort(); } } return(result); }