当前位置: 首页 > 工具软件 > weixinSDK.net > 使用案例 >

.NET微信支付集成实例

宁飞宇
2023-12-01

微信端HTML页面下单事件:

[javascript] view plain copy
print ?
  1. document.getElementById('btn-wxpay')addEventListener('tap'function (e) {  
  2.   //创建订单  
  3.   $.post('/Orders/Create', orderdata, function(result){  
  4.     //创建订单成功  
  5.     if (result.status == 'success') {  
  6.       //开始调用微信JS API支付接口  
  7.       WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(result.data), function (res) {  
  8.         //支付成功,重定向只支付页面  
  9.         if (res.err_msg == 'get_brand_wcpay_request:ok') {  
  10.           window.location.href = '/Orders/CreateSuccess/' + result.orderId;  
  11.         } else {  
  12.           //支付失败,提示错误原因,重定向至订单详情页面  
  13.           if (res.err_msg == 'get_brand_wcpay_request:cancel') {  
  14.             alert('支付过程中用户取消');  
  15.           } else if (res.err_msg == 'get_brand_wcpay_request:fail') {  
  16.             alert('支付失败');  
  17.           } else {  
  18.             alert(res.err_msg);  
  19.           }  
  20.           window.location.href = '/Orders/Details/' + result.orderId;  
  21.         }  
  22.       });  
  23.     }else{  
  24.       //创建订单失败,提示错误  
  25.       alert(result.error);  
  26.     }  
  27.   });  
  28. }  
document.getElementById('btn-wxpay')addEventListener('tap', function (e) {
  //创建订单
  $.post('/Orders/Create', orderdata, function(result){
    //创建订单成功
    if (result.status == 'success') {
      //开始调用微信JS API支付接口
      WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(result.data), function (res) {
        //支付成功,重定向只支付页面
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
          window.location.href = '/Orders/CreateSuccess/' + result.orderId;
        } else {
          //支付失败,提示错误原因,重定向至订单详情页面
          if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            alert('支付过程中用户取消');
          } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
            alert('支付失败');
          } else {
            alert(res.err_msg);
          }
          window.location.href = '/Orders/Details/' + result.orderId;
        }
      });
    }else{
      //创建订单失败,提示错误
      alert(result.error);
    }
  });
}

服务端对应处理模块:

[csharp] view plain copy
print ?
  1. //创建订单,同时对订单进行预支付  
  2. public ActionResult Create(OrderCreateViewModel model){  
  3.   try{  
  4.     using(var db = new MyDbEntities()){  
  5.       db.Orders.Add(new Order(){ Name = model.Name, Weight = model.Weight, OrderTotal = model.OrderTotal, OrderStatus = WaitBuyerPay, Gateway = 'wxpay' });  
  6.       db.SaveChanges();  
  7.       return Json(new { status = "success", orderId = order.OrderId, data = GetJsBrandWCPayRequestApiParameters(order.Name, order.Name, (int)(order.OrderTotal * 100), 'openId')});  
  8.     }  
  9.   }catch (Exception ex){  
  10.     return Json(new { status = "error", error = ex.Message });  
  11.   }  
  12. }  
  13. //生成微信JS API支付接口参数  
  14. public string GetJsBrandWCPayRequestApiParameters(string body, string out_trade_no, int total_fee, string openid){  
  15.   var parameters = new Dictionary<string string="">();  
  16.   parameters.Add("appId"'wx0000000000000000');  
  17.   parameters.Add("timeStamp"'timeStamp');  
  18.   parameters.Add("nonceStr"'nonceStr');  
  19.   //获取预支付订单号  
  20.   parameters.Add("package"string.Format("prepay_id={0}", GetPrepayId('wx0000000000000000''0000000000''000000000000000''nonceStr', body, out_trade_no, total_fee, openid)));  
  21.   parameters.Add("signType""MD5");  
  22.   parameters.Add("paySign", GetPaySign(parameters, '000000000000000'));  
  23.   return JsonConvert.SerializeObject(parameters);  
  24. }  
  25. //获取预支付订单号  
  26. public static string GetPrepayId(string appId, string mchId, string mchKey, string nonceStr, string body, string out_trade_no, int total_fee, string openid){  
  27.   HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api.mch.weixin.qq.com/pay/unifiedorder");  
  28.   myRequest.Method = "POST";  
  29.   myRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";  
  30.   myRequest.Accept = "application/json";  
  31.   var formQuery = GetUnifiedOrderApiParameters(appId, mchId, mchKey, nonceStr, body, out_trade_no, total_fee, openid);  
  32.   using (var sw = new StreamWriter(myRequest.GetRequestStream())){  
  33.     sw.Write(formQuery);  
  34.   }  
  35.   string responseText = string.Empty;  
  36.   using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse()){  
  37.     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){  
  38.       responseText = reader.ReadToEnd().ToString();  
  39.     }  
  40.   }  
  41.   var doc = XDocument.Parse(responseText);  
  42.   if (doc.Root.Element("return_code").Value == "FAIL" || doc.Root.Element("result_code").Value == "FAIL"){  
  43.     if (doc.Root.Element("err_code") != null)  
  44.       throw new WeixinPayException(doc.Root.Element("err_code").Value, doc.Root.Element("err_code_des").Value);  
  45.     else  
  46.       throw new Exception(doc.Root.Element("return_msg").Value);  
  47.   }else{  
  48.     return doc.Root.Element("prepay_id").Value;  
  49.   }  
  50. }  
  51. </string>  
//创建订单,同时对订单进行预支付
public ActionResult Create(OrderCreateViewModel model){
  try{
    using(var db = new MyDbEntities()){
      db.Orders.Add(new Order(){ Name = model.Name, Weight = model.Weight, OrderTotal = model.OrderTotal, OrderStatus = WaitBuyerPay, Gateway = 'wxpay' });
      db.SaveChanges();
      return Json(new { status = "success", orderId = order.OrderId, data = GetJsBrandWCPayRequestApiParameters(order.Name, order.Name, (int)(order.OrderTotal * 100), 'openId')});
    }
  }catch (Exception ex){
    return Json(new { status = "error", error = ex.Message });
  }
}
//生成微信JS API支付接口参数
public string GetJsBrandWCPayRequestApiParameters(string body, string out_trade_no, int total_fee, string openid){
  var parameters = new Dictionary<string string="">();
  parameters.Add("appId", 'wx0000000000000000');
  parameters.Add("timeStamp", 'timeStamp');
  parameters.Add("nonceStr", 'nonceStr');
  //获取预支付订单号
  parameters.Add("package", string.Format("prepay_id={0}", GetPrepayId('wx0000000000000000', '0000000000', '000000000000000', 'nonceStr', body, out_trade_no, total_fee, openid)));
  parameters.Add("signType", "MD5");
  parameters.Add("paySign", GetPaySign(parameters, '000000000000000'));
  return JsonConvert.SerializeObject(parameters);
}
//获取预支付订单号
public static string GetPrepayId(string appId, string mchId, string mchKey, string nonceStr, string body, string out_trade_no, int total_fee, string openid){
  HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api.mch.weixin.qq.com/pay/unifiedorder");
  myRequest.Method = "POST";
  myRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
  myRequest.Accept = "application/json";
  var formQuery = GetUnifiedOrderApiParameters(appId, mchId, mchKey, nonceStr, body, out_trade_no, total_fee, openid);
  using (var sw = new StreamWriter(myRequest.GetRequestStream())){
    sw.Write(formQuery);
  }
  string responseText = string.Empty;
  using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse()){
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){
      responseText = reader.ReadToEnd().ToString();
    }
  }
  var doc = XDocument.Parse(responseText);
  if (doc.Root.Element("return_code").Value == "FAIL" || doc.Root.Element("result_code").Value == "FAIL"){
    if (doc.Root.Element("err_code") != null)
      throw new WeixinPayException(doc.Root.Element("err_code").Value, doc.Root.Element("err_code_des").Value);
    else
      throw new Exception(doc.Root.Element("return_msg").Value);
  }else{
    return doc.Root.Element("prepay_id").Value;
  }
}
</string>

通用通知接口处理模块:

[csharp] view plain copy
print ?
  1. public ActionResult Notify()  
  2.         {  
  3.             //读取从客户端发出的原始数据并解码  
  4.             var xml = System.Text.Encoding.UTF8.GetString(Request.BinaryRead(Request.TotalBytes));  
  5.             if (!string.IsNullOrEmpty(xml))  
  6.             {  
  7.                 //解析为XML文档实例  
  8.                 var doc = XDocument.Parse(xml);  
  9.                 var originalSign = doc.Root.Element("sign").Value;  
  10.                 var parameters = doc.Root.Elements().Where(m => m.Name != "sign").ToDictionary(m => m.Name.LocalName, m => m.Value);  
  11.                 //签名验证  
  12.                 var sign = GetPaySign(parameters, "MchKey");  
  13.                 var returnDic = new Dictionary<stringstring>();  
  14.                 if (sign != originalSign)  
  15.                 {  
  16.                     Log.Error("签名失败:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value).ToArray()));  
  17.                     returnDic.Add("return_code""FAIL");  
  18.                     returnDic.Add("return_msg""签名失败");  
  19.                 }  
  20.                 else  
  21.                 {  
  22.                     returnDic.Add("return_code""SUCCESS");  
  23.                 }  
  24.                 //返回处理结果给微信  
  25.                 Response.Write(WeixinSDK.DictionaryToXML(returnDic));  
  26.                 //业务处理  
  27.                 if (sign == originalSign)  
  28.                 {  
  29.                     if (parameters["return_code"] == "FAIL")  
  30.                     {  
  31.                         Log.Error("通信出错:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value)));  
  32.                     }  
  33.                     else if (parameters["result_code"] == "FAIL")  
  34.                     {  
  35.                         Log.Error("业务出错:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value)));  
  36.                     }  
  37.                     else  
  38.                     {  
  39.                         Log.Info("支付成功:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value)));  
  40.                         var request = new WeixinPayNotifyRequest()  
  41.                         {  
  42.                             transaction_id = parameters["transaction_id"],  
  43.                             out_trade_no = parameters["out_trade_no"]  
  44.                         };  
  45.                         //最终对该笔交易进行确认  
  46.                         ConfirmPay(request.out_trade_no, request.transaction_id);  
  47.                     }  
  48.                 }  
  49.             }  
  50.             return Content(string.Empty);  
  51.         }  
 类似资料: