This article mainly introduces the development of nodejs public account payment, which has some reference value. if you are interested, you can refer to the development of the odeJs public account function, the mobile terminal H5 page calls the payment function. In the past few days, we have used the payment function called by node and h5 pages to meet the company's needs. Now we repeat the development process to help more developers smoothly complete the development of the payment function. (Node payment function is not yet provided)
1. request CODE
The purpose of the request code is to get the user's openid (the user's unique identifier relative to the current public number) 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
Note the following parameters for this api:
1. appid of The appid public account, which can be viewed in the public account
2. the custom callback address of redirect_uri will jump to the address of your redirect_uri after you have requested the address above, with code. the redirect_url here requires ** url_encode ** php *, if your program is node, you need to use ** encodeURLComponent (url) ** encoding.
3. response_type = code. the fixed response_type = code is nothing to say. for details, refer to the instructions on the official website.
4. scope = snsapi_userinfo
5. the state = STATE is fixed. for details, refer to the instructions on the official website.
6. wechat_redirect is fixed. for details, refer to the instructions on the official website.
Ps: official website link:
2. get access_token and openid through code
The value of the code has been obtained in the first step. then, you need to use the code to obtain the value of access_token, openid, and the requested api.
API https://api.weixin.qq.com/sns/oauth2/access_token? Appid = APPID & secret = SECRET & code = CODE & grant_type = authorization_code
Here, the api parameters are described as follows:
1. appid public id, which is obtained in the background
2. secret: secret of the public account, which is obtained from the background of the public account
3. code. The first step is to obtain the code used.
4. grant_type = authorization_code is fixed.
3. call the interface through access_token
Access_token can be used for subsequent functions. refer to the official example:
Https://open.weixin.qq.com/cgi-bin/showdocument? Action = dir_list & t = resource/res_list & verify = 1 & id = open1419425518 & lang = zh_CN
4. call the payment API on the webpage
Does it feel like it's almost over? as long as the webpage calls the payment function, it's over? No, almost
Open the H5 webpage in the browser and execute JS to initiate the payment. The format of input and output data is JSON.
Note: WeixinJSBridge built-in objects are invalid in other browsers.
The sample code is as follows:
Function onBridgeReady () {WeixinJSBridge. invoke ('getbrandwcpayrequest', {"appId": "wx2421b1c4370ec43b", // name of the public account, which is input by the merchant "timeStamp": "1395712654", // timeStamp, the number of seconds since January 1, 1970 "nonceStr": "success", // random string "package": "prepay_id = u802345jgfjsdfgsdg888", "signType": "MD5", // signature method: "paySign": "70EA570631E4BB79628FBCA90534C63FF7FADD89" // signature}, function (res) {if (res. err_msg = "get_bran D_wcpay_request: OK ") {}// determine the front-end return using the above method. The team solemnly prompts that res. err_msg will return OK after the user successfully pays, but it is not guaranteed to be absolutely reliable. });} 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 ();}
If you see the code above, you need to pass parameters for the payment function to be called,
{"AppId": "wx2421b1c4370ec43b", // name of the public account, "timeStamp": "1395712654", // timeStamp, number of seconds since January 1, 1970 ": "signature", // random string "package": "prepay_id = u802345jgfjsdfgsdg888", "signType": "MD5", // signature method: "paySign ": "70EA570631E4BB79628FBCA90534C63FF7FADD89" // signature}
Parameter description:
1. appId // public account name, which is input by the merchant
2. timeStamp // timeStamp, the number of seconds since January 1, 1970. Note that the timeStamp format of the string must be "" quotation marks
3. nonceStr // 32-bit random string, followed by a method
4. signType // signature method: MD5
5. paySign // signature.
6. ** package ** // This is the most important. Where can I obtain the package? Next, let's talk about it.
Ps: Official website interface description
Https://pay.weixin.qq.com/wiki/doc/api/jsapi.php? Chapter = 7_7 & index = 6
5. obtain the package and obtain the prepay_id from the unified order interface.
Official api:
Https://api.mch.weixin.qq.com/pay/unifiedorder
There are a bunch of request parameters, but some are not required. below are required parameters
{Appid: APPID, attach: ATTACH, body: BODY, mch_id: MCH_ID, nonce_str: NONCE_STR, yy_url: yy_url, // callback address after payment openid: OPENID, out_trade_no: OUT_TRADE_NO, // new Date (). getTime (), // Order No. spbill_create_ip: SPBILL_CREATE_IP, // The ip address total_cost of the client: total_price, // The price of the product. Note that the price is calculated by minute, generally, it is RMB. you need to convert it to RMB trade_type of RMB: 'japi ',}
The unified order interface requires that the xml data be transmitted, and the data still needs to be signed. First, the data signature.
For signature rules, refer to the given signature rules (the signature method will be provided later)
Official signature rules:
Https://pay.weixin.qq.com/wiki/doc/api/jsapi.php? Chapter = 4_3
After the signature is generated, you need to assemble the data in xml format:
Var body ='
'+ ''+ Config. wxappid +''+ ''+ Obj. attach +''+''+ Obj. body +''+'
'+ Config. mch_id +'
'+'
'+ Obj. nonce_str +'
'+'
'+ Obj. policy_url +'
'+'
'+ Obj. openid +'
'+'
'+ Obj. out_trade_no +'
'+'
'+ Obj. spbill_create_ip +'
'+'
'+ Obj. total_fee +'
'+'
'+ Obj. trade_type +'
'+'
'+ Obj. sign +'
'+ // Signature is required here. Otherwise, the signature fails during data verification'
';
The next step is to request the api to get the value of prepay_id. send the following api of the preceding xml data request to the api. after verifying that the data is correct, the api will return the value you want.
Api: https://api.mch.weixin.qq.com/pay/unifiedorder
6. can I directly call the payment in the h5 segment after obtaining the prepay_id? The answer is No.
After obtaining the prepay_id, the parameters of the currently h5 call-up payment function are as follows:
{"AppId": "wx2421b1c4370ec43b", // name of the public account, "timeStamp": "1395712654", // timeStamp, number of seconds since January 1, 1970 ": "e61463f8efa94090b1fda-cccfbbb444", // random string "package": "prepay_id = u802345jgfjsdfgsdg888", "signType": "MD5", // signature method :}
With such a parameter, you still need to sign all the involved parameters. The signature rules are the same as above. after a signature is generated, the paySign parameter of the signature must be assigned to the payment function parameter initiated by h5 (that is, the signature does not participate in signature generation)
The final parameter is like this:
{"AppId": "wx2421b1c4370ec43b", // name of the public account, "timeStamp": "1395712654", // timeStamp, number of seconds since January 1, 1970 ": "signature", // random string "package": "prepay_id = u802345jgfjsdfgsdg888", "signType": "MD5", // signature method: "paySign ": "70EA570631E4BB79628FBCA90534C63FF7FADD89" // signature}
If you have no problems in all aspects, you can call the payment function normally after such a parameter is obtained, which is no different from the native function, (I guess you are very happy now. it's amazing that no app can actually use the app function ).
7. callback of payment completion
After the payment is completed, the value will be put back in the callback function of the h5 page,
Res. err_msg = "get_brand_wcpay_request: OK". This is a success, but isn't it all done? No. why? Did you really receive the money? Did you pass the money you received? What else do you need to write the payment result to the database? these are unknown. Note that a required parameter in the unified order interface is yy_url: yy_url, // The callback address after payment. This address is transmitted by the user, after receiving the payment from the user, the user will request this interface in the form of post, and the user's payment information will be transmitted, but in xml format.
Class:
wx2421b1c4370ec43b 支付测试
CFT
CNY
Y
10000100
5d2b6c2a8db53831f7eda20af46e531c
oUpF8uMEb4qRXf22hE3X68TekukE
1409811653
SUCCESS
SUCCESS
B552ED6B279343CB493C5DD0D78AB241
10000100
20140903131540
1
JSAPI
1004400740201409030005092168
Parse the data in xml format based on your business logic.
Note: You need to get your response after obtaining the data. if you do not respond, you will be requested several times. in this case, your logic may be faulty, therefore, you need to return a response in xml format.
SUCCESS
OK
Trap: node and express framework development. if you have not obtained any xml value in the callback after the payment is successful, you need to install a component: body-parser-xml, you can use npm install body-parser-xml -- save to install the tool. require ('body-parser-XML') (bodyParser) in js, using middleware
// Solve the callback data of the payment notification 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 if> 1 }}));
In this way, you can get the xml data normally.
Usage:
Pay. getAccessToken ({policy_url: 'http: // demo.com/', // callback out_trade_no: new Date () after payment is complete (). getTime (), // order number attach: 'name', body: 'Purchase information', total_detail: '1', // The quota here is spbill_create_ip: req. connection. remoteAddress,}, function (error, responseData) {res. render ('payment', {title: 'pay', wxPayParams: JSON. stringify (responseData), // userInfo: userInfo });});
That's it. it's almost the same. If anything is wrong, please correct it.
For more articles about nodejs public account payment and development, refer to PHP Chinese website!