Implementation method of using .NET to parse WeChat payment
Mar 17, 2017 pm 03:21 PMDue to the widespread use of WeChat, a series of products developed based on WeChat have also emerged. This article mainly introduces the implementation method of parsing WeChat payment (.NET version). Those who are interested can learn about it.
I made a web version of WeChat payment some time ago and encountered many problems, but they were finally solved. Now I will record the development process and instructions here to give others some reference.
1. Preparation work
First of all, you must first activate the WeChat payment function. In the past, activating WeChat payment required a deposit of 30,000, but now it is no longer required, so... Made this feature.
To develop WeChat payment, you need to make relevant settings in the official account backend and WeChat merchant backend.
1. Development directory configuration
WeChat payment needs to configure the payment authorization directory in the official account background (WeChat payment = "development configuration"). The authorized directory here needs to be an online address, that is, an address that can be accessed through the Internet. The WeChat payment system needs to be able to access your address through the Internet.
The WeChat authorization directory needs to be accurate to the second or third level directory. Example: If the link to initiate payment is http://www.hxfspace.net/weixin/WeXinPay/WeXinPayChoose then the configured directory should be http: //www.hxfspace.net/weixin/WeXinPay/ where http://www. hxfspace.net is the domain name and weixin is the virtual directory WeXinPay, which is the Controller. The related payment requests are all in action in WeXinPay.
This 2, OAUTH2.0 Webpage Authorized Domaining Domaining
WeChat Payment will Make a callback to the payment request to obtain the authorization code (code), so you need to set the authorization domain name here. Of course, the domain name here must be the same as the domain name in the payment authorization directory. Don’t forget to set this up. I just forgot to set it up and spent a long time looking for the reason, crying to death.
3. Relevant parameter preparation
#To call WeChat payment, you need to initiate a payment request to the WeChat payment system through a script. For parameter description, seeWeChat official website payment platform
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
2. Development process
Without further ado, let’s talk about the process after sorting out:
1. Obtain the authorization code through WeChat authorization callback
2. Obtain the authorization code through the authorization code Exchange web page authorization access_token and openid
3. Call the unified ordering interface to obtain the prepayId
4. Set up jsapi WeChat payment request parameters and initiate payment
5. Receive WeChat payment callback for subsequent operations
3. Specific development (code above)
WeChat payment can only It is very inconvenient to debug in an online environment, so it is best to record logs at every key location when you first start developing.
1. Obtain the authorization code through WeChat authorization callback
First pass the initiating payment address and related parameters to the WeChat payment interface. After the WeChat payment is successfully received and verified, it will Request your payment address and bring the authorization code.
For example, here
//判斷是否網(wǎng)頁授權,獲取授權code,沒有代表沒有授權,構造網(wǎng)頁授權獲取code,并重新請求 if (string.IsNullOrEmpty(Request.QueryString["code"])) { string redirectUrl = _weChatPaySerivce.GetAuthorizeUrl(account.AppId, account.RedquestUrl, "STATE" + "#wechat_redirect", "snsapi_base"); return Redirect(redirectUrl); }
Stitching WeChat webpage authorization Url method
public string GetAuthorizeUrl(string appId, string redirectUrl, string state, string scope) { string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}", appId, HttpUtility.UrlEncode(redirectUrl), scope, state); /* 這一步發(fā)送之后,客戶會得到授權頁面,無論同意或拒絕,都會返回redirectUrl頁面。 * 如果用戶同意授權,頁面將跳轉至 redirect_uri/?code=CODE&state=STATE。這里的code用于換取access_token(和通用接口的access_token不通用) * 若用戶禁止授權,則重定向后不會帶上code參數(shù),僅會帶上state參數(shù)redirect_uri?state=STATE */ AppLog.Write("獲取到授權url:", AppLog.LogMessageType.Debug); return url; }
2. Exchange the authorization code for web page authorization access_token and openid
After obtaining the authorization code from the first step, combine the web page authorization Request url to obtain access_token and openid
public Tuple<string, string> GetOpenidAndAccessTokenFromCode(string appId, string code, string appSecret) { Tuple<string, string> tuple = null; try { string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, appSecret, code); string result = WeChatPayHelper.Get(url); AppLog.Write("微信支付-獲取openid和access_token 請求Url:" + url + "result:" + result, AppLog.LogMessageType.Debug); if (!string.IsNullOrEmpty(result)) { var jd=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(result); tuple = new Tuple<string, string>(jd["openid"],jd["access_token"]); AppLog.Write("微信支付-獲取openid和access_token成功", AppLog.LogMessageType.Debug); } } catch (Exception ex) { AppLog.Write("微信支付:獲取openid和access_tokenu異常", AppLog.LogMessageType.Debug,ex); } return tuple; }
3. Call the unified ordering interface to obtain prepaymentId
The RequestHandler here is a dll packaged by others online, which helps you encapsulate the generation of signatures and some verification requests. The dll can be downloaded from their official website http://weixin.senparc.com/
//創(chuàng)建支付應答對象 RequestHandler packageReqHandler = new RequestHandler(null); //初始化 packageReqHandler.Init(); //時間戳 string timeStamp = TenPayUtil.GetTimestamp(); //隨機字符串 string nonceStr = TenPayUtil.GetNoncestr(); //設置package訂單參數(shù) 生成prepayId預支付Id packageReqHandler.SetParameter("appid", account.AppId); //公眾賬號ID packageReqHandler.SetParameter("mch_id", account.PartnertId); //商戶號 packageReqHandler.SetParameter("nonce_str", nonceStr); //隨機字符串 packageReqHandler.SetParameter("body", account.Body); packageReqHandler.SetParameter("out_trade_no", account.OrderSerialId); //商家訂單號 packageReqHandler.SetParameter("total_fee", account.TotalAmount); //商品金額,以分為單位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", account.RequestIp); //用戶的公網(wǎng)ip,不是商戶服務器IP packageReqHandler.SetParameter("notify_url", account.NotifyUrl); //接收財付通通知的URL packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易類型 packageReqHandler.SetParameter("openid", account.OpenId); //用戶的openId string sign = packageReqHandler.CreateMd5Sign("key", account.PaySignKey); packageReqHandler.SetParameter("sign", sign); //簽名 string prepayId = string.Empty; try { string data = packageReqHandler.ParseXML(); var result = TenPayV3.Unifiedorder(data); MailHelp.SendMail("調(diào)用統(tǒng)一下單接口,下單結果:--"+result+"請求參數(shù):"+data); var res = XDocument.Parse(result); prepayId = res.Element("xml").Element("prepay_id").Value; AppLog.Write("調(diào)用統(tǒng)一下單接口獲取預支付prepayId成功", AppLog.LogMessageType.Debug); } catch (Exception ex) { AppLog.Write("獲取到openid和access_tokenu異常", AppLog.LogMessageType.Debug, ex); MailHelp.SendMail("調(diào)用統(tǒng)一下單接口獲取預支付prepayid異常:", ex); return null; }
4. Set up jsapi WeChat Payment request parameters, initiate payment
我這里是首先組裝好微信支付所需要的參數(shù),然后再創(chuàng)建調(diào)用js腳本
//生成JsAPI支付參數(shù) RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appId", account.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); string paySign = paySignReqHandler.CreateMd5Sign("key", account.PaySignKey); WeChatJsPayRequestModel resultModel = new WeChatJsPayRequestModel { AppId = account.AppId, NonceStr = nonceStr, TimeStamp = timeStamp, Package = string.Format("prepay_id={0}", prepayId), PaySign = paySign, SignType = "MD5" };
創(chuàng)建調(diào)用腳本
private string CreateWeixinJs(WeChatJsPayRequestModel model) { string js = @"<script type='text/javascript'> callpay(); function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest', { requestParam }, function (res) { if(res.err_msg == 'get_brand_wcpay_request:ok' ){ window.location.href = 'successUrl'; }else{ window.location.href = 'failUrl'; } } ); } function callpay() { if (typeof WeixinJSBridge == 'undefined'){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script>"; string requestParam = string.Format(@"'appId': '{0}','timeStamp': '{1}','nonceStr': '{2}','package': '{3}','signType': '{4}','paySign': '{5}'", model.AppId, model.TimeStamp, model.NonceStr, model.Package, model.SignType, model.PaySign); js = js.Replace("requestParam", requestParam) .Replace("successUrl", model.JumpUrl + "&result=1") .Replace("failUrl", model.JumpUrl + "&result=0"); AppLog.Write("生成可執(zhí)行腳本成功", AppLog.LogMessageType.Debug); return js; }
5、接收微信支付回調(diào)進行后續(xù)操作
回調(diào)的時候首先需要驗證簽名是否正確,保證安全性,簽名驗證通過之后再進行后續(xù)的操作,訂單狀態(tài)、通知啥的。
ResponseHandler resHandler = new ResponseHandler(System.Web.HttpContext.Current); bool isSuccess = _weChatPaySerivce.ProcessNotify(resHandler); if (isSuccess) { string result = @"<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[支付成功]]></return_msg> </xml>"; HttpContext.Response.Write(result); HttpContext.Response.End(); } return new EmptyResult();
這里有一點需要注意,就是微信支付回調(diào)的時候微信會通知八次,好像是這個數(shù)吧,所以你需要在第一次收到通知之后,把收到請求這個狀態(tài)以xml的格式響應給微信支付接口。當然你不進行這個操作也是可以的,再回調(diào)的時候 每次去判斷該訂單是否已經(jīng)回調(diào)成功,回調(diào)成功則不進行處理就可以了。
The above is the detailed content of Implementation method of using .NET to parse WeChat 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)

In WeChat, users can enter their payment password to make purchases, but how do they retrieve their payment password if they forget it? Users need to go to My-Services-Wallet-Payment Settings-to recover their payment password if they forget it. This introduction to how to retrieve your payment password if you forget it will tell you the specific operation method. The following is a detailed introduction, so take a look! WeChat usage tutorial. How to find the WeChat payment password if you forget it? Answer: My-Service-Wallet-Payment Settings-Forgot payment password. Specific method: 1. First, click My. 2. Click on the service inside. 3. Click on the wallet inside. 4. Find the payment settings. 5. Click Forgot payment password. 6. Enter your own information for verification. 7. Then enter the new payment password to change it.

Solution for forgetting WeChat payment password: 1. Open WeChat APP, click "I" in the lower right corner to enter the personal center page; 2. In the personal center page, click "Pay" to enter the payment page; 3. On the payment page , click "..." in the upper right corner to enter the payment management page; 4. In the payment management page, find and click "Forgot payment password"; 5. Follow the page prompts and enter personal information for identity verification. After successful verification, you can Choose the method of "retrieve by swiping your face" or "retrieve by verifying bank card information" to retrieve your password, etc.

Steps to set the order of deductions for WeChat payment: 1. Open the WeChat APP, click on the "Me" interface, click on "Services", and then click on "Collect and Payment"; 2. Click on "Prioritize Use This Payment Method" under the payment code on the collection and payment interface; 3. Select the preferred payment method you need.

There are many food and snack shops provided in the Meituan takeout app, and all mobile phone users log in through their accounts. Add your personal delivery address and contact number to enjoy the most convenient takeout service. Open the homepage of the software, enter product keywords, and search online to find the corresponding product results. Just swipe up or down to purchase and place an order. The platform will also recommend dozens of nearby restaurants with high reviews based on the delivery address provided by the user. The store can also set up different payment methods. You can place an order with one click to complete the order. The rider can arrange the delivery immediately and the delivery speed is very fast. There are also takeout red envelopes of different amounts for use. Now the editor is online in detail for Meituan takeout users. We show you how to set up WeChat payment. 1. After selecting the product, submit the order and click Now

When everyone has nothing to do, they will choose to browse the Xianyu platform. Everyone can find that there are a large number of products on this platform, which can allow everyone to see various second-hand products. Although these products are second-hand products, there is absolutely no problem with the quality of these products, so everyone can buy them with confidence. The prices are very affordable, and they still allow everyone to face-to-face with these products. It is entirely possible for sellers to communicate and conduct some price bargaining operations. As long as everyone negotiates properly, then you can choose to conduct transactions, and when everyone pays here, they want to make WeChat payment, but it seems that the platform It's not allowed. Please follow the editor to find out what the specific situation is. Xianyu

WeChat payment cannot be canceled immediately after successful payment. Refunds usually need to meet the following conditions: 1. The merchant's refund policy. The merchant will formulate its own refund policy, including the refund time window, refund amount and refund method; 2. Payment time, refunds usually require Apply within a certain time frame, and refunds may not be possible beyond this time frame; 3. Goods or service status. If the user has received the goods or enjoyed the service, the merchant may require the user to return the goods or provide corresponding proof; 4. Refund process, etc.

The Didi Chuxing app provides more convenience for everyone's daily travel. You can go wherever you want, and all Didi vehicles are on call. You no longer need to wait anxiously. Dozens of taxi red envelopes are available for free. Travel faster. Open the homepage of the software, enter the starting point and destination according to your personal itinerary, and freely choose from vehicles of different prices below. Place an order with one click and publish the itinerary. Didi drivers will receive the order in seconds and arrive at the designated location as quickly as possible. For the location, just check your mobile phone number before getting on the bus. Of course, there are many ways to pay for the fare, including WeChat and Alipay, but everyone usually uses WeChat. It is easy to set up payment with one click. Now the editor is online carefully paying for Didi one by one. Travel users bring how to set up WeChat payment. 1. We are on the mobile phone

1. First, we need to open the WeChat APP on the mobile phone, and then click to log in to the WeChat account, so that we enter the WeChat homepage. 2. Click the [Me] button in the lower right corner of the WeChat homepage, then select the [Payment] option. We click to enter the payment page. 3. After entering the [Payment] page, click the [Wallet] option to enter, and click [Bill] in the upper right corner of the [Wallet] page.
