Asp.Net MVC development for WeChat scan code payment
Mar 16, 2018 pm 01:47 PMThis 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",?"北京分店");//附加數(shù)據(jù) ????????????data.SetValue("out_trade_no",?order.TradeNumber);//隨機(jī)字符串???????????//?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"));//交易結(jié)束時間 ????????????data.SetValue("goods_tag",?"智能嬰兒床");//商品標(biāo)記 ????????????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);//調(diào)用統(tǒng)一下單接口????????????Logger.Info(result.ToJson());????????????string?url?=?result.GetValue("code_url").ToString();//獲得統(tǒng)一下單接口返回的二維碼鏈接 ????????????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到內(nèi)存流?? ????????????MemoryStream?ms?=?new?MemoryStream(); ????????????image.Save(ms,?ImageFormat.Jpeg);????????????return?File(ms.ToArray(),?"image/jpeg"); ????????}After success, you will get the payment page:
??public?ActionResult?ResultNotify() ????????{????????????//接收從微信后臺POST過來的數(shù)據(jù) ????????????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);????????????//轉(zhuǎn)換數(shù)據(jù)格式并驗(yàn)證簽名 ????????????WxPayData?data?=?new?WxPayData();????????????try ????????????{ ????????????????data.FromXml(builder.ToString()); ????????????}????????????catch?(WxPayException?ex) ????????????{????????????????//若簽名錯誤,則立即返回結(jié)果給微信支付后臺 ????????????????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;????????????//檢查支付結(jié)果中transaction_id是否存在 ????????????if?(!notifyData.IsSet("transaction_id")) ????????????{????????????????//若transaction_id不存在,則立即返回結(jié)果給微信支付后臺 ????????????????WxPayData?res?=?new?WxPayData(); ????????????????res.SetValue("return_code",?"FAIL"); ????????????????res.SetValue("return_msg",?"支付結(jié)果中微信訂單號不存在"); ????????????????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();????????????//查詢訂單,判斷訂單真實(shí)性 ????????????if?(!QueryOrder(transaction_id)) ????????????{????????????????//若訂單查詢失敗,則立即返回結(jié)果給微信支付后臺 ????????????????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+"成功更新狀態(tài)為"+status); ????????????} ????????}Then check the status of the order on the page. After confirming success, jump to the page.
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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

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.

VSCode is a powerful, flexible, and easy-to-extend open source code editor that is widely favored by developers. It supports many programming languages ??and frameworks to meet different project needs. However, the advantages of VSCode may be different for different frameworks. This article will discuss the applicability of VSCode in the development of different frameworks and provide specific code examples. 1.ReactReact is a popular JavaScript library used for building user interfaces. When developing projects using React,

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.
