Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example analysis of NET Wechat code scanning payment access

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces. NET Wechat scan payment access example analysis, the article introduces in great detail, has a certain reference value, interested friends must read it!

Step1: it must generate the merchant order number, and then pass it to the Wechat backstage. Wechat will form the QR code string, and then return it to you, and then turn the string into a picture.

/ public string GetCodeUrl (string orderNumber) {var result = string.Empty; if (! string.IsNullOrEmpty (orderNumber)) {var matchedItem = db.OrderInfoForProducts.FirstOrDefault (x = > x.OrderNumber = = orderNumber); if (matchedItem! = null & & matchedItem.IsPaid = = false) {WxPayData data = new WxPayData (); data.SetValue ("body", "productBody") / / Product description data.SetValue ("attach", "attach data"); / / additional data data.SetValue ("out_trade_no", WxPayApi.GenerateOutTradeNo ()); / / Random string data.SetValue ("total_fee", price); / / Total amount data.SetValue ("time_start", DateTime.Now.ToString ("yyyyMMddHHmmss")) / / transaction start time data.SetValue ("time_expire", DateTime.Now.AddMinutes (10). ToString ("yyyyMMddHHmmss")); / / transaction end time data.SetValue ("goods_tag", "tag"); / / Commodity tag data.SetValue ("trade_type", "NATIVE"); / / transaction type data.SetValue ("product_id", WxPayApi.GenerateOutTradeNo ()) / / Product ID result = WxPayApi.UnifiedOrder (data) .GetValue ("code_url") .GetValue (); / / call the API for unified ordering} return result;}

Here, I put the company's merchant order number on the attach field, because the company's merchant order number is longer, more than 32 digits. Out_trade_no and product_id fields up to 32 bits, please be careful!

The price in Wechat cannot be decimal, so 0.01RMB should be written as 100RMB.

Step2: after successfully returning the QR code string, you can generate the image. I use ThoughtWorks.QRCode.dll to generate the image:

/ public static Image CreateQRCodeImage (string qrInfo, string productName, string version) {try {if (! string.IsNullOrEmpty (qrInfo)) {QRCodeEncoder encoder = new QRCodeEncoder {QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeScale = 4, QRCodeVersion = 0, QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M} according to the string / / Encoding method (Note: BYTE can support Chinese, ALPHA_NUMERIC scans all numbers) / / size (the higher the value, the higher the pixel of the QR code image) / / version (Note: set to 0 is mainly to prevent errors when the encoded string is too long) / / error effectiveness, error correction (there are 4 levels) Image image = encoder.Encode (qrInfo, Encoding.GetEncoding ("utf-8")) String filename = $"{productName} _ {version} .png"; var userLocalPath = Environment.GetFolderPath (Environment.SpecialFolder.LocalApplicationData); var docPath = Path.Combine (userLocalPath, @ "Your Product\ QRCode"); if (! Directory.Exists (docPath)) {Directory.CreateDirectory (docPath);} string filepath = Path.Combine (docPath, filename); using (FileStream fs = new FileStream (filepath, FileMode.OpenOrCreate, FileAccess.Write)) {image.Save (fs, System.Drawing.Imaging.ImageFormat.Png) Fs.Close (); image.Dispose ();} return image;}} catch (Exception) {return null;} return null;}

Step3: after the user has scanned the QR code, Wechat will initiate a callback, then we can deal with our own business logic. Here my UpdatePayStatus returns an empty page

/ callback function / public ActionResult UpdatePayStatus () {/ / receive data from Wechat backend POST System.IO.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 (); / / convert the data format and verify the signature WxPayData data = new WxPayData (); try {data.FromXml (builder.ToString ());} catch (WxPayException ex) {/ / if the signature is incorrect, immediately return the result to WeChat Pay backend WxPayData res = new WxPayData (); res.SetValue ("return_code", "FAIL"); res.SetValue ("return_msg", ex.Message) LogEntity signErrorLog = new LogEntity (); signErrorLog.errorMessage = ex.Message; LogHelper.WriteLog (signErrorLog, null); Response.Write (res.ToXml ()); Response.End ();} ProcessNotify (data); return View ();} / process callback data / public void ProcessNotify (WxPayData data) {WxPayData notifyData = data / / check whether transaction_id exists in the payment result if (! notifyData.IsSet ("transaction_id")) {/ / if transaction _ id does not exist, immediately return the result to WeChat Pay backend WxPayData res = new WxPayData (); res.SetValue ("return_code", "FAIL"); res.SetValue ("return_msg", "Wechat order number does not exist"); LogEntity orderLog = new LogEntity () OrderLog.errorMessage = "Wechat order number does not exist in payment result"; LogHelper.WriteLog (orderLog, null); Response.Write (res.ToXml ()); Response.End ();} string transaction_id = notifyData.GetValue ("transaction_id") .ToString () / / query the order to determine the authenticity of the order if (! QueryOrder (transaction_id)) {/ / if the order query fails, immediately return the result to WeChat Pay backend WxPayData res = new WxPayData (); res.SetValue ("return_code", "FAIL"); res.SetValue ("return_msg", "order query failure"); LogEntity orderqueryLog = new LogEntity (); orderqueryLog.errorMessage = "order query failed" LogHelper.WriteLog (orderqueryLog, null); Response.Write (res.ToXml ()); Response.End ();} / query order success else {WxPayData res = new WxPayData (); res.SetValue ("return_code", "SUCCESS"); res.SetValue ("return_msg", "OK"); SetPaymentResult (data); / / the parameter here is data!! Not res! Response.Write (res.ToXml ()); Response.End ();}} / private void SetPaymentResult (WxPayData res) {var isSucessFlagOne = res.GetValue ("return_code"). ToString (); var isSuccessFlagTwo = res.GetValue ("result_code"). ToString (); if (isSucessFlagOne = = "SUCCESS" & & isSuccessFlagTwo = = "SUCCESS") {/ / your own business logic! } / / query order private bool QueryOrder (string transaction_id) {WxPayData req = new WxPayData (); req.SetValue ("transaction_id", transaction_id); WxPayData res = WxPayApi.OrderQuery (req); if (res.GetValue ("return_code"). ToString () = = "SUCCESS" & & res.GetValue ("result_code"). ToString () = = "SUCCESS") {return true;} else {return false }} the above is all the contents of the article "sample Analysis of .NET Wechat Code scan payment access". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report