Home  >  Article  >  WeChat Applet  >  Asp.Net MVC development for WeChat scan code payment

Asp.Net MVC development for WeChat scan code payment

php中世界最好的语言
php中世界最好的语言Original
2018-03-16 13:47:472110browse

This time I will bring you the development of MVC using WeChat scan code to pay. Asp.Net MVC development and the development of Asp.Net MVC using WeChat scan code to pay. What are the precautions? The following is the actual combat. Let’s take a look at the case.

The scan code payment here refers to the use of WeChat payment on the PC website, which is the official mode two. The website is Asp.net MVC, which is organized as follows. (Demo is at the bottom)

1.

Preparation work

The unified order method in the WeChat API used, the key parameter is'

public account ID (appid)', 'merchant number (mch_id)' and 'merchant payment key (KEY)', so you must first have an approved public account, and Activate the payment function, then apply for a merchant. After passing the review, you will get the merchant number, which is the login name of the merchant platform. The merchant payment key is used for signing to ensure that the URL is not tampered with. After entering the merchant platform, set it in API security. It is a 32-bit string .

After having these three parameters, there is another thing to note:

Transaction starting time and Transaction ending time The interval should be more than five minutes and less than 2 hours. Otherwise, an error will be reported when obtaining the payment URL.

2. Generate payment QR code

With the above parameters, the next step is to download the SDK: .net SDK and examples.

Unfortunately, this official example did not run correctly at first. Reference the relevant dll to the MVC directory. And create a WxPayAPI folder and copy the relevant classes over.

Then set the relevant parameters in

WxPayConfig to your own parameters, and then modify the GetPayUrl method,

 public string GetPayUrl(Order order,string ip)
        {            if (order == null)
            {                throw new ArgumentNullException("order");
            }           
            var product = order.OrderItems.First();
            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.APPID);
            data.SetValue("mch_id", WxPayConfig.MCHID);            // data.SetValue("device_info", "iphone4s");
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
            data.SetValue("body", product.AttributeDescription);//商品描述
            data.SetValue("detail", product.AttributeDescription);//商品描述
            data.SetValue("attach", "北京分店");//附加数据
            data.SetValue("out_trade_no", order.TradeNumber);//随机字符串           // data.SetValue("total_fee", Convert.ToInt32(order.OrderTotal * 100));//总金额
            data.SetValue("total_fee", 1);//总金额
            data.SetValue("spbill_create_ip",ip);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("goods_tag", "智能婴儿床");//商品标记
            data.SetValue("notify_url", "http://www.xxxx.com/Checkout/ResultNotify");//通知地址
            data.SetValue("trade_type", "NATIVE");//交易类型
            data.SetValue("product_id", product.ProductId);//商品ID  
            data.SetValue("sign", data.MakeSign());//签名
            Logger.Info("获得签名" + data.GetValue("sign"));
            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口            Logger.Info(result.ToJson());            string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
            Logger.Info("pay url:" + url);            return url;
        }
TradeNumber It is generated by calling the WxPayApi.GenerateOutTradeNo() method. notify_url is the address of WeChat notification after the user pays. The unit of the amount is cents, which can only be passed in int type or string type. Decimal needs to be converted. After successfully obtaining the url, create a payment method in the

controller responsible for payment. Used to display QR codes:

  ActionResult Payment((  ArgumentException( order = _orderService.GetOrderByGuid( user ==  url2 ==  +=
Here just returns a url, on the page:

<img src="@ViewBag.QRCode" class="qrcode"  />
The qrCodeEncoder used in the background generates QR codes.

  public FileResult MakeQRCode(string data)
        {            if (string.IsNullOrEmpty(data)) 
                throw new ArgumentException("data");            //初始化二维码生成工具
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            qrCodeEncoder.QRCodeVersion = 0;
            qrCodeEncoder.QRCodeScale = 4;            //将字符串生成二维码图片
            Bitmap image = qrCodeEncoder.Encode(data, Encoding.Default);            //保存为PNG到内存流  
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Jpeg);            return File(ms.ToArray(), "image/jpeg");
        }
After success, you will get the payment page:

After scanning the QR code, the payment page will pop up:

3. Callback

After the user pays, WeChat will send a message to the previously reserved interface (the interface cannot take parameters). The website will verify and confirm after receiving the message, and then send a message to WeChat after confirmation. For detailed parameters and documents, please see the official API

Here we have slightly modified the method in the demo and put it into the controller:

  public ActionResult ResultNotify()
        {            //接收从微信后台POST过来的数据
            Stream s = 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();
            Logger.Info(this.GetType()+ "Receive data from WeChat : " + builder);            //转换数据格式并验证签名
            WxPayData data = new WxPayData();            try
            {
                data.FromXml(builder.ToString());
            }            catch (WxPayException ex)
            {                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                Response.Write(res.ToXml());
                Response.End();
            }
            Logger.Info(this.GetType()+ "Check sign success");
            ProcessNotify(data);            return View();
        }        public void ProcessNotify(WxPayData data)
        {
            WxPayData notifyData = data;            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {                //若transaction_id不存在,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                Logger.Error(this.GetType()+"The Pay result is error : " + res.ToXml());
                Response.Write(res.ToXml());
                Response.End();
            }            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", "订单查询失败");
                Logger.Error(this.GetType()+"Order query failure : " + res.ToXml());
                Response.Write(res.ToXml());
                Response.End();
            }            //查询订单成功
            else
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Logger.Info(this.GetType()+"order query success : " + res.ToXml());                SetPaymentResult(data.GetValue("out_trade_no").ToString(), PaymentStatus.Paid);
                Response.Write(res.ToXml());
                Response.End();
            }
        }
After receiving the confirmation, we need to update the status of the order:

  public void SetPaymentResult(string tradeno, PaymentStatus status)
        {
            Logger.Info("订单号:"+tradeno);            var order = _orderService.GetOrderByTradeNumber(tradeno);            if (order != null)
            {
                order.PaymentStatus = status;                if (status == PaymentStatus.Paid)
                {
                    order.PaidDate = DateTime.Now;
                }
                _orderService.UpdateOrder(order);
                Logger.Info("订单:"+tradeno+"成功更新状态为"+status);
            }
        }
Then check the status of the order on the page. After confirming success, jump to the page.

In the background of the merchant platform, we can query:

I believe you have mastered it after reading the case in this article Method, for more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Development of refund function for WeChat payment

##Detailed explanation of H5’s video playback library video.js

WeChat Hardware H5 Development Controlling Lights

Easy-to-use lightweight date plug-in in JS

The above is the detailed content of Asp.Net MVC development for WeChat scan code payment. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn