Nodejs WeChat public account payment development, nodejs mail public payment

Source: Internet
Author: User
Tags openid

Nodejs public account payment development, nodejs mail public payment

OdeJs public account function development, mobile terminal H5 page call 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. Get package,Obtain 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 = '<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>' + '<policy_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_timeout>' + obj. total_detail + '</total_detail>' + '<trade_type>' + obj. trade_type + '</trade_type>' + '<sign>' + obj. sign + '</sign>' + // the signature is required here. Otherwise, the signature is not passed '</xml> ';

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:

<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 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.

<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>

Trap:Node, 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.

Attach my own code: https://git.oschina.net/anziguoer/wechatPay

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.