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

Asp.Net MVC development for WeChat scan code payment

Mar 16, 2018 pm 01:47 PM
asp.net develop pay

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;
        }
Copy after login
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 ==  +=
Copy after login
Here just returns a url, on the page:

<img src="@ViewBag.QRCode" class="qrcode"  />
Copy after login
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");
        }
Copy after login
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();
            }
        }
Copy after login
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);
            }
        }
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to pay for a taxi ride on Baidu Maps. Introduction to the payment steps for a taxi ride. How to pay for a taxi ride on Baidu Maps. Introduction to the payment steps for a taxi ride. Mar 13, 2024 am 10:04 AM

Baidu Map APP has now become the preferred travel navigation software for many users, so some of the functions here are comprehensive and can be selected and operated for free to solve some of the problems that you may encounter in daily travel. You can all check some of your own travel routes and plan some of your own travel plans. After checking the corresponding routes, you can choose appropriate travel methods according to your own needs. So whether you choose some public transportation, Cycling, walking or taking a taxi can all satisfy your needs. There are corresponding navigation routes that can successfully lead you to a certain place. Then everyone will feel more convenient if they choose to take a taxi. There are many drivers They are all able to take orders online, and taxi-hailing has become super

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Summary of the five most popular Go language libraries: essential tools for development Summary of the five most popular Go language libraries: essential tools for development Feb 22, 2024 pm 02:33 PM

Summary of the five most popular Go language libraries: essential tools for development, requiring specific code examples. Since its birth, the Go language has received widespread attention and application. As an emerging efficient and concise programming language, Go's rapid development is inseparable from the support of rich open source libraries. This article will introduce the five most popular Go language libraries. These libraries play a vital role in Go development and provide developers with powerful functions and a convenient development experience. At the same time, in order to better understand the uses and functions of these libraries, we will explain them with specific code examples.

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

How to close Meituan Takeout Express Payment How to close Meituan Takeout Express Payment Mar 27, 2024 am 10:41 AM

In the fast-paced modern life, Meituan Takeaway is deeply loved by consumers for its convenient services and rich choices. Among them, the ultra-fast payment function brings great convenience to users. Payment can be completed with one click, eliminating tedious input steps. However, many users don't like paying directly without confirmation, so they want to turn off this feature. So how to turn off the fast payment of Meituan Waimai? In the following, the editor of this website will bring you a detailed step-by-step setup tutorial, I hope it can help you! 1. Click the &quot;Meituan Takeout&quot; shortcut icon on the mobile phone desktop. 2. Log in to the Meituan takeout app on your mobile phone and click &quot;My&quot; in the lower right corner. 3. In the My interface, click &quot;Enter Wallet&quot;. 4. On the Meituan Wallet interface, click the &quot;Settings&quot; icon in the upper right corner

Where can Meituan instant discount be deducted by default when payment is enabled_ Tutorial on Meituan instant discount being deducted by default when payment is enabled Where can Meituan instant discount be deducted by default when payment is enabled_ Tutorial on Meituan instant discount being deducted by default when payment is enabled Mar 28, 2024 am 11:00 AM

1. First open the [Meituan] APP, click the [My] button in the bottom navigation bar. 2. Then click the [My Wallet] function button and click the [Cash Voucher] button. 3. Then in the top function bar, click the [Instant Deduction] button, and click the switch button to turn on [Default Deduction during Payment] to successfully turn it on.

See all articles