English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
odeJs to develop WeChat public account functions, mobile end H5The page calls WeChat's payment function. In these days, according to the company's needs, I used node and h5The page calls WeChat's payment function to complete the payment requirement. Now let's go through the development process again to help more developers smoothly complete the development of WeChat payment function. (WeChat has not provided node payment function temporarily)
I. Request CODE
The purpose of requesting code is to obtain the user's openid (the unique identifier of the user relative to the current official account) and access_token, the requested API: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
This API needs to pay attention to several parameters:
1. appid is the appid of the official account, which can be seen in the official account
2. redirect_uri is the custom WeChat callback address, WeChat will jump to the address defined by redirect_uri after you request the above address, carrying the code, the redirect_url here needs **url_encode** *php*, If your program is node, you need to use **encodeURLComponent(url)**Encoding
3. response_type=code, there is nothing much to say, it is fixed as response_type=code, for detailed explanation, please refer to WeChat official website
4. scope=snsapi_userinfo, it is written in this fixed way, for detailed explanation, please refer to WeChat official website
5. state=STATE is written in this fixed way, for detailed explanation, please refer to WeChat official website
6. wechat_redirect is written in this fixed way, for detailed explanation, please refer to WeChat official website
ps: Official website link:
II. Obtain access_token and openid through code
The first step has already obtained the value of code, so the next step is to obtain the values of access_token and openid through code, and make the API request
API https://api.weixin.qq.com/sns/oauth2/access_token#63;appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
Here is the description of the parameters of this api:
1. appid The WeChat official account ID, obtained from the WeChat official account background
2. secret The secret key of the WeChat official account, obtained from the WeChat official account background
3. code, the first step to obtain the used code
4. grant_type=authorization_code is fixed
3. Call the interface through access_token
The access_token can be used for subsequent functions, you can refer to the official examples:
https://open.weixin.qq.com/cgi-bin/showdocument#63;action=dir_list&t=resource/res_list&verify=1&id=open1419316518&lang=zh_CN
4. Web page call payment API
Don't you feel like it's almost done? As long as the WeChat payment function is called on the web page, it's done? No, it's still a bit short
Open H in the WeChat browser5JS call payment is executed in the web page. The input and output data format of the interface is JSON.
Note: The built-in WeixinJSBridge object is invalid in other browsers.
The following is an example of the code:
function onBridgeReady(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId": "wx2421b1c4370ec43b", //Public account name, passed in by the merchant "timeStamp": " 1395712654", //Timestamp, since197seconds since the year 0 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //Random String "package" : "prepay_id=u802345jgfjsdfgsdg888", "signType" : "MD5", //WeChat Signature Method: "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //WeChat Signature }, function(res){ if(res.err_msg == "get_brand_wcpay_request:ok" ) {} // Please be advised by the WeChat team solemnly: res.err_msg will return 'ok' after the user's payment is successful, but it does not guarantee its absolute reliability. } ); } if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } }else{ onBridgeReady(); }
Looking at the above code, if you want to call WeChat's payment function, you need to pass parameters,
{ "appId": "wx2421b1c4370ec43b", //Public account name, passed in by the merchant "timeStamp": " 1395712654", //Timestamp, since197seconds since the year 0 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //Random String "package" : "prepay_id=u802345jgfjsdfgsdg888", "signType" : "MD5", //WeChat Signature Method: "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //WeChat Signature }
Parameter description:
1. appId //Public account name, passed in by the merchant
2. timeStamp //Timestamp, since197Seconds since 0 years ago, it should be noted that it needs to be a string timestamp format, meaning it must be enclosed in double quotes ""
3. nonceStr //Random String 32bits, a method will be provided later
4. signType // WeChat signature method: MD5
5. paySign //WeChat signature, to be discussed later
6. **package** //This is the most important, where can it be obtained? Let's talk about it next.
ps: Official API description
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
5. Get package, Get prepay_id from WeChat's unified order interface
Official API:
https://api.mch.weixin.qq.com/pay/unifiedorder
There are a lot of request parameters, but some are not required, and the following are required parameters
{ appid : APPID, attach : ATTACH, body : BODY, mch_id : MCH_ID, nonce_str: NONCE_STR, notify_url : NOTIFY_URL,// The callback address after WeChat payment openid : OPENID, out_trade_no : OUT_TRADE_NO ,//new Date().getTime(), //Order Number spbill_create_ip : SPBILL_CREATE_IP , //The client's IP total_fee : TOTAL_FEE, //The price of the product, it should be noted that this price is calculated in fen, so it is usually in yuan, and you need to convert it to RMB yuan. trade_type : 'JSAPI', }
The unified order interface of WeChat requires passing xml data, and the data also needs to be signed, so the data should be signed first.
The signature rules can be referred to in the signature rules provided by WeChat (the signature method will be given later).
The official WeChat signature rules:
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
After generating the signature, you need to assemble the data into the xml format:
var body = '<xml> ' + <appid>'+config.wxappid+</appid> ' + <attach>'+obj.attach+</attach> ' + <body>'+obj.body+</body> ' + <mch_id>'+config.mch_id+</mch_id> ' + <nonce_str>'+obj.nonce_str+</nonce_str> ' + <notify_url>'+obj.notify_url+</notify_url>' + <openid>'+obj.openid+</openid> ' + <out_trade_no>'+obj.out_trade_no+</out_trade_no>'+ <spbill_create_ip>'+obj.spbill_create_ip+</spbill_create_ip> ' + <total_fee>'+obj.total_fee+</total_fee> ' + <trade_type>'+obj.trade_type+</trade_type> ' + <sign>'+obj.sign+</sign> ' + // This must include the signature, otherwise WeChat will not pass the verification of the data. </xml>';
Next is to request the api to get the value of prepay_id, send the above obtained xml data to the following api, and WeChat will return the value you want after verifying the data correctly.
api: https://api.mch.weixin.qq.com/pay/unifiedorder
Six. After obtaining the prepay_id, can we directly use h5 Can we directly call WeChat payment? The answer is not yet.
After obtaining the prepay_id, now h5 Parameters for invoking WeChat payment function are as follows:
{ "appId": "wx2421b1c4370ec43b", //Public account name, passed in by the merchant "timeStamp": " 1395712654", //Timestamp, since197seconds since the year 0 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //Random String "package" : "prepay_id=u802345jgfjsdfgsdg888", "signType" : "MD5", //WeChat Signature Method: }
With such parameters, you still need to sign all the participating parameters. The signature rules are the same as above, and after generating the signature, you need to assign the signed parameter paySign to h5 Parameters for invoking WeChat payment function (that is, WeChat signature does not participate in the generation of the signature)
The final parameters are as follows:
{ "appId": "wx2421b1c4370ec43b", //Public account name, passed in by the merchant "timeStamp": " 1395712654", //Timestamp, since197seconds since the year 0 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //Random String "package" : "prepay_id=u802345jgfjsdfgsdg888", "signType" : "MD5", //WeChat Signature Method: "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //WeChat Signature }
If all your links are fine, then with these parameters you can normally call the WeChat payment function, which is completely different from the native function (I guess you are very happy in your heart now, without an app you can use the app's function, it is just so magical).
Chapter 7. Callback after payment is completed
After WeChat payment is completed, it will be in h5 The callback function of WeChat payment on the page returns the value,
res.err_msg == "get_brand_wcpay_request:ok", this means it is successful, but is that all? No, why? Did WeChat really receive the money? Is the money received the value you passed to WeChat? You still need to write the payment result to the database, etc., which are all unknown. Remember that there is a required parameter in the unified order interface, namely notify_url: NOTIFY_URL,// The callback address after WeChat payment, this address is passed to WeChat by the user. After WeChat receives the user's payment, it will request this interface in the form of POST. WeChat will pass the user's payment information, but it is in XML format.
This is an XML format such as:
<xml> <appid><![CDATA[wx2421b1c4370ec43b]]></appid> <attach><![CDATA[Payment Test]]></attach> <bank_type><![CDATA[CFT]]></bank_type> <fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe> <mch_id><![CDATA[10000100]]></mch_id> <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str> <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid> <out_trade_no><![CDATA[1409811653]]></out_trade_no> <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code> <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign> <sub_mch_id><![CDATA[10000100]]></sub_mch_id> <time_end><![CDATA[20140903131540]]></time_end> <total_fee>1</total_fee> <trade_type><![CDATA[JSAPI]]></trade_type> <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id> </xml>
Parse the xml format data according to your business logic.
Note: After you get the data, WeChat needs to receive your response. If you do not respond to WeChat continuously, WeChat will request you several times. This may indicate that there is a problem with your logic, so you need to return a response in xml format to WeChat.
<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>
Little pit:node, express framework development, if you did not get any xml value in the callback after the payment success in WeChat, then you need to install a component: body-parser-xml, you can use npm install body-parser-xml --save Installation, in app.js require('body-parser-xml)(bodyParser);, using middleware
// Resolve WeChat payment notification callback data app.use(bodyParser.xml({ limit: '2MB', // Reject payload bigger than 1 MB xmlParseOptions: { normalize: true, // Trim whitespace inside text nodes normalizeTags: true, // Transform tags to lowercase explicitArray: false // Only put nodes in array if1 } });
This way, you can normally get WeChat's xml data.
Usage:
pay.getAccessToken({ notify_url : 'http://demo.com/', //Callback after WeChat payment is completed out_trade_no : new Date().getTime(), //Order Number attach : 'Name', total_fee : '1', // The amount here is in cents spbill_create_ip : req.connection.remoteAddress, }, function (error, responseData) { res.render('payment', { title : 'WeChat Payment', wxPayParams : JSON.stringify(responseData), //userInfo : userInfo }); });
That's all for now, I feel it's about right. If there are any mistakes, please correct them.
Attach my own code:https://git.oschina.net/anziguoer/wechatPay
This article has been sorted into 'Summary of JavaScript WeChat Development Techniques', welcome to study and read.
Here is a tutorial on WeChat Mini Program that is currently highly concerned: 'WeChat Mini Program Development Tutorial'. The editor has carefully organized it, and I hope you like it.
That's all for the content of this article. I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yell Tutorial.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, has not been edited by humans, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)