Implementation method of using .NET to parse WeChat payment
Due 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
//判断是否网页授权,获取授权code,没有代表没有授权,构造网页授权获取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); /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。 * 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。这里的code用于换取access_token(和通用接口的access_token不通用) * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数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/
//创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); //初始化 packageReqHandler.Init(); //时间戳 string timeStamp = TenPayUtil.GetTimestamp(); //随机字符串 string nonceStr = TenPayUtil.GetNoncestr(); //设置package订单参数 生成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); //用户的公网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("调用统一下单接口,下单结果:--"+result+"请求参数:"+data); var res = XDocument.Parse(result); prepayId = res.Element("xml").Element("prepay_id").Value; AppLog.Write("调用统一下单接口获取预支付prepayId成功", AppLog.LogMessageType.Debug); } catch (Exception ex) { AppLog.Write("获取到openid和access_tokenu异常", AppLog.LogMessageType.Debug, ex); MailHelp.SendMail("调用统一下单接口获取预支付prepayid异常:", ex); return null; }
4. Set up jsapi WeChat Payment request parameters, initiate payment
我这里是首先组装好微信支付所需要的参数,然后再创建调用js脚本
//生成JsAPI支付参数 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" };
创建调用脚本
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("生成可执行脚本成功", AppLog.LogMessageType.Debug); return js; }
5、接收微信支付回调进行后续操作
回调的时候首先需要验证签名是否正确,保证安全性,签名验证通过之后再进行后续的操作,订单状态、通知啥的。
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();
这里有一点需要注意,就是微信支付回调的时候微信会通知八次,好像是这个数吧,所以你需要在第一次收到通知之后,把收到请求这个状态以xml的格式响应给微信支付接口。当然你不进行这个操作也是可以的,再回调的时候 每次去判断该订单是否已经回调成功,回调成功则不进行处理就可以了。
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

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

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



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.

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

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.

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 Pay does not need to be bound to a bank card. WeChat payment can be used without binding a bank card, provided that real-name authentication is carried out. As long as the real-name authentication is passed, you can use WeChat change to send red envelopes, transfer, collect money, WeChat payment and other operations. It should be noted that WeChat cannot withdraw cash if it is not bound to a bank card, and there are limits on receipts, payments, transfers, etc., with a maximum of 200 yuan for a single transaction and daily, and a maximum of 500 yuan per month.

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.

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.
