Asp.Net MVC development for WeChat scan code payment
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. 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 .
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 codeWith 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.
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; }
controller responsible for payment. Used to display QR codes:
ActionResult Payment(( ArgumentException( order = _orderService.GetOrderByGuid( user == url2 == +=
<img src="@ViewBag.QRCode" class="qrcode" />
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"); }
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(); } }
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); } }
Development of refund function for WeChat payment
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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, 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?" 》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

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 "Meituan Takeout" shortcut icon on the mobile phone desktop. 2. Log in to the Meituan takeout app on your mobile phone and click "My" in the lower right corner. 3. In the My interface, click "Enter Wallet". 4. On the Meituan Wallet interface, click the "Settings" icon in the upper right corner

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.
