ASP.NET MVC 微信扫码支付
1、首先到官网下载微信API。
2、解压后将cert、lib两个文件夹复制到项目更目录下。
3、微信扫码支付
3.1、控制器代码
1 private string GetPayUrl(OrderDto order,string ip) 2 { 3 if (order == null) 4 { 5 throw new ArgumentNullException("order"); 6 } 7 var product = ....; //商品信息 8 WxPayData data = new WxPayData(); 9 data.SetValue("appid",PublicConst.Wx_appid); 10 data.SetValue("mch_id",PublicConst.Wx_wchid); 11 // data.SetValue("device_info", "iphone4s"); 12 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); 13 data.SetValue("body",product.ProductName);//商品描述 14 data.SetValue("out_trade_no", order.OrderNo);//随机字符串 15 // data.SetValue("total_fee", Convert.ToInt32(order.OrderTotal * 100));//总金额 16 data.SetValue("total_fee",Convert.ToInt32(order.OrderAmount*100));//总金额 17 data.SetValue("spbill_create_ip", ip);//总金额 18 data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间 19 data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间 20 data.SetValue("notify_url", url);//这里输入通知地址 21 data.SetValue("trade_type", "NATIVE");//交易类型 22 data.SetValue("product_id", product.ProductCode.ToString());//商品ID 23 data.SetValue("sign", data.MakeSign());//签名 24 //Logger.Info("获得签名" + data.GetValue("sign")); 25 26 WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口 27 //Logger.Info(result.ToJson()); 28 string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接 29 //Logger.Info("pay url:" + url); 30 return url; 31 } 32 // 二维码的显示页面 33 public ActionResult Payment(string orderno,string ip) 34 { 35 if (string.IsNullOrEmpty(orderno)) 36 throw new ArgumentException("guide"); 37 38 var order = _order.QueryFirstOrDefault(c => c.OrderNo == orderno); 39 NativePay nativePay = new NativePay(); 40 string url2 = this.GetPayUrl(order,ip); 41 ViewBag.QRCode = "/Common/MakeQRCode?data=" + HttpUtility.UrlEncode(url2); 42 ViewBag.Order = order; 43 44 return View(order); 45 } 46 // 生成二维码图片 47 public FileResult MakeQRCode(string data) 48 { 49 //初始化二维码生成工具 50 QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); 51 qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; 52 qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; 53 qrCodeEncoder.QRCodeVersion = 0; 54 qrCodeEncoder.QRCodeScale = 4; 55 56 //将字符串生成二维码图片 57 Bitmap image = qrCodeEncoder.Encode(data, Encoding.Default); 58 59 //保存为PNG到内存流 60 MemoryStream ms = new MemoryStream(); 61 image.Save(ms, ImageFormat.Jpeg); 62 63 return File(ms.ToArray(), "image/jpeg"); 64 } 65 // 回调处理函数 66 public ActionResult WxNotify() 67 { 68 69 //接收从微信后台POST过来的数据 70 Stream s = Request.InputStream; 71 int count = 0; 72 byte[] buffer = new byte[1024]; 73 StringBuilder builder = new StringBuilder(); 74 while ((count = s.Read(buffer, 0, 1024)) > 0) 75 { 76 builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); 77 } 78 s.Flush(); 79 s.Close(); 80 s.Dispose(); 81 //转换数据格式并验证签名 82 WxPayData data = new WxPayData(); 83 try 84 { 85 Log.Info(this.GetType().ToString(), builder.ToString()); 86 data.FromXml(builder.ToString()); 87 if (data.GetValue("result_code").ToString() == "SUCCESS") 88 { 89 var tno = data.GetValue("out_trade_no").ToString(); //订单号 90 var order = _order.QueryFirstOrDefault(c => c.OrderNo == tno); //根据订单号获取系统订单信息 91 if (order != null && order.Status == (int)OrderStatus.WaitPay) 92 { 93 //这里加入自己的处理逻辑 94 } 95 } 96 Log.Info("返回结果:",data.ToJsonString()); 97 } 98 catch (WxPayException ex) 99 { 100 //若签名错误,则立即返回结果给微信支付后台 101 WxPayData res = new WxPayData(); 102 res.SetValue("return_code", "FAIL"); 103 res.SetValue("return_msg", ex.Message); 104 Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml()); 105 Response.Write(res.ToXml()); 106 Response.End(); 107 } 108 ProcessNotify(data); 109 110 return View(); 111 } 112 public void ProcessNotify(WxPayData data) 113 { 114 WxPayData notifyData = data; 115 116 //检查支付结果中transaction_id是否存在 117 if (!notifyData.IsSet("transaction_id")) 118 { 119 //若transaction_id不存在,则立即返回结果给微信支付后台 120 WxPayData res = new WxPayData(); 121 res.SetValue("return_code", "FAIL"); 122 res.SetValue("return_msg", "支付结果中微信订单号不存在"); 123 Response.Write(res.ToXml()); 124 Response.End(); 125 } 126 127 string transaction_id = no 128 }
3.2、页面代码
支付结果通知页面 WxNotify.cshtml
1 @{ 2 ViewBag.Title = "微信扫码支付结果"; 3 } 4 5 <div> 6 <div> 7 <h1>订单支付成功!</h1> 8 </div> 9 </div>
支付页面 Payment.cshtml
1 @model OrdersDto 2 @{ 3 ViewBag.Title = "微信扫码支付"; 4 Layout = "~/Views/Shared/_OrderLayout.cshtml"; 5 } 6 <div class=""> 7 <div class=""> 8 <img src="@ViewBag.QRCode" style="width:200px;height:200px" /> 9 <h1>请微信扫描二维码进行支付!</h1> 10 </div> 11 <div class=""> 12 <h1>订单号:@Model.OrderNo</h1> 13 <h2>应付金额<span>@Model.OrderAmount</span>元</h2> 14 <a href="" class="dtjcg_zf">付款完成</a> 15 </div> 16 17 </div>