Nodejs Public number Payment development _node.js

Source: Internet
Author: User
Tags cdata md5 openid

Odejs Micro-letter public number function development, mobile end H5 page Call micro-letter payment function. These days, depending on the needs of the company, use node and H5 pages to invoke the payment function of the micro-letter to fulfill the payment requirements. Now go through the development process again to help more developers successfully complete the development of the micro-credit payment function. (Micro-letter has not yet provided node's payment function)

A. Request code

The purpose of the request code is to obtain the user's OpenID (the user's unique identity 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
This API needs to be aware of several parameters:

1. The AppID of the AppID public number can be seen in the public number
2. Redirect_uri customized micro-letter callback address, the micro-letter will be after you request the above address to jump to your definition of the Redirect_uri address, with code, where the Redirect_url need **url_encode** *php*, if your Program is node you need to use **encodeurlcomponent (URL) * * encoding
3. Response_type=code, this is nothing to say is fixed response_type=code, detailed instructions can see the micro-letter official website description
4. Scope=snsapi_userinfo, fixed this write is good, detailed instructions can view the micro-letter official website description
5. State=state fixed This write is good, detailed instructions can view the micro-letter official website description
6. Wechat_redirect fixed This write is good, detailed instructions can view the micro-letter official website description
PS: Website Link:

Two. Get Access_token,openid by code

The first step is to get the value of the code, then you need to use code to get the value of Access_token,openid, the requested API
API Https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant _type=authorization_code
the parameters of the API here are described:

1. AppID Public number ID, micro-credit public number backstage access
2. Secret public number key, micro-credit public number backstage access
3. Code, the first step to get the code used
4. Grant_type=authorization_code fixing is good.

Three. Invoke interface via Access_token

Access_token can do the following functions, can refer to the official example:
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1& ID=OPEN1419316518&LANG=ZH_CN

Four. Web page to adjust the payment API

See this is not feeling fast, as long as the web end of the call micro-credit payment function is done? No, I almost
In the micro-letter browser Open H5 Web page in the implementation of JS adjustment to pay. interface input Output data format is JSON.
Note: Weixinjsbridge built-in objects are not valid in other browsers.
The sample code is as follows:

function Onbridgeready () {
 weixinjsbridge.invoke (
 ' getbrandwcpayrequest ', {
  "appId": " wx2421b1c4370ec43b ",//public number name, by merchant incoming 
  " TimeStamp ":" 1395712654 ",  //timestamp, seconds since 1970 
  " Noncestr ":" e61463f8efa94090b1f366cccfbbb444 ",//Random string 
  " package ":" prepay_id=u802345jgfjsdfgsdg888 ", 
  " Signtype ":" MD5 ",  //micro-letter Signature mode: 
  "paysign": "70ea570631e4bb79628fbca90534c63ff7fadd89"//micro-letter Signature 
 },
 function (res) { 
  if (res.err_msg = = "Get_brand_wcpay_request:ok") {}//Use the above method to judge the front end return, the micro-letter team solemnly prompts: Res.err_msg will return OK after the user pays success, 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 ();
}

See the above code, then want to invoke the micro-letter payment function needs to pass parameters,

{
 "appId": "wx2421b1c4370ec43b",//public number name, incoming by merchant 
 "TimeStamp": "1395712654",  //timestamp, seconds since 1970 
 Noncestr ":" e61463f8efa94090b1f366cccfbbb444 ",//Random string 
 " package ":" prepay_id=u802345jgfjsdfgsdg888 ", 
 " Signtype ":" MD5 ",  //micro-letter Signature way: 
 " paysign ":" 70ea570631e4bb79628fbca90534c63ff7fadd89 "//micro-letter Signature 
}

Parameter description:

1. AppId//Public number name, introduced by merchant
2. TimeStamp//timestamp, the number of seconds since 1970 here needs special attention, need to be the timestamp format of the string, meaning that you must quote
3. Noncestr//Random string 32-bit, then provide method
4. Signtype//micro-letter signature method: MD5
5. Paysign//micro-letter signature, then said
6. **package**//This is the most important, where to get it? Then say.
PS: Official Website Interface description
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6

Five. Obtain the package, obtain the prepay_id from the unified single interface of the micro-letter

Official API:
Https://api.mch.weixin.qq.com/pay/unifiedorder

Request parameters a bunch, but some are not required, the following is the required parameter

{
 appid:appid,
 Attach:attach,
 body:body,
 mch_id:mch_id,
 nonce_str:nonce_str,
 notify_ url:notify_url,//the callback address after the micro-letter payment
 Openid:openid,
 out_trade_no:out_trade_no,//new Date (). GetTime (),//order number
 SPBILL_CREATE_IP:SPBILL_CREATE_IP,//client IP
 total_fee:total_fee,//The price of the commodity, here is to note that the price is divided, then the general is the yuan, you need to convert to RMB The meta
 trade_type: ' Jsapi ',
}

The unification of micro-letters the single interface requires that the XML data be passed, and the data needs to be signed, so first the data signature.
The signature rule can refer to the signature rule given by the micro-letter (the signature method is given)
Micro-Credit official signature rules:
Https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3

When you generate the signature, you need it. Data is assembled into 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> ' +//here will be signed, no person micro-letter in the validation of data is not through the
 ' </xml > ';

The next step is to request the API to get the value of the prepay_id, to send the following API from the XML data request above to the micro-letter, which will return the value you want after the data is no problem.
API: Https://api.mch.weixin.qq.com/pay/unifiedorder

Six. Get to the prepay_id is it possible to call the micro-letter payment in the H5 section? The answer is still not available.

Get to prepay_id so now h5 the parameters of the payment function of the micro-letter is this:

{
 "appId": "wx2421b1c4370ec43b",//public number name, incoming by merchant 
 "TimeStamp": "1395712654",  //timestamp, seconds since 1970 
 Noncestr ":" e61463f8efa94090b1f366cccfbbb444 ",//Random string 
 " package ":" prepay_id=u802345jgfjsdfgsdg888 ", 
 " Signtype ":" MD5 ",  //micro-letter Signature mode:
}

With such parameters, you need to sign all the participating parameters. The signature is the same as the above, the signature must be generated after the signing of the parameters Paysign assigned to H5 to call the micro-letter payment function parameters (i.e., micro-letter signature does not participate in the generation of signatures)
The final argument is this:

{
 "appId": "wx2421b1c4370ec43b",//public number name, incoming by merchant 
 "TimeStamp": "1395712654",  //timestamp, seconds since 1970 
 Noncestr ":" e61463f8efa94090b1f366cccfbbb444 ",//Random string 
 " package ":" prepay_id=u802345jgfjsdfgsdg888 ", 
 " Signtype ":" MD5 ",  //micro-letter Signature way:
 " paysign ":" 70ea570631e4bb79628fbca90534c63ff7fadd89 "//micro-letter Signature
}

If all of your links are fine, so when you get this parameter you can normally call the micro-letter payment function, with the original function is no difference, (it is estimated that your heart is also very happy now, no app unexpectedly can use the function of the app, is so magical).

Seven. Payment-Completed callback

When the micro-mail is paid, it will put the value back in the H5 of the micro-mail payment on the page.
Res.err_msg = = "Get_brand_wcpay_request:ok", so that is successful, but is not the finished son? No, why not? Did the micro-mail really get the money? Did you receive the money you passed to the micro-letter? You also need to write the results of the payment to the database or whatever, these are unknown. Also recorded in the unified next single interface has a must parameter is the notify_url:notify_url,//micro-letter payment callback address this address is the user passed to the micro-letter, micro-letter in the receipt of payment will be sent by post to request this interface, micro-letter will pass the user payment information over, It's just XML format.
Class is an XML format like this:

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

It's good to parse this XML-formatted data according to your business logic.
Note: Here you get the data after the micro-letter need to get your response, if you have not responded to the micro-letter, the micro-letter will ask you several times, so that your logic will be a problem, so you need to give the micro-letter return to the format of XML response.

<xml>
 <return_code><![ Cdata[success]]></return_code>
 <return_msg><![ Cdata[ok]]></return_msg>
</xml>

Pits:node, express Framework development, if you do not get any XML value in the callback after the successful payment of the micro-letter, you need to install a component: Body-parser-xml, you can use NPM install Body-parser-xml--save installed, inside the app.js require (' Body-parser-xml ') (Bodyparser), using middleware

Resolves the micro-credit 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 if >1
 }
}));

So you can get the micro-letter XML data normally.

How to use:

Pay.getaccesstoken ({
 notify_url: ' http://demo.com/',//micro-letter payment completed after callback
 out_trade_no:new Date (). GetTime (),//order number
 attach: ' name ', body
 : ' Buy information ',
 total_fee: ' 1 ',//Here is the amount of
 spbill_create_ip: Req.connection.remoteAddress,
 }, function (Error, responsedata) {
 res.render (' payment ', {
  title: ' Micro-letter payment ',
  wxPayParams:JSON.stringify (responsedata),
  //userinfo:userinfo
 });
 

Here it is, and it feels pretty much the same. Please correct me if there is any wrong place.

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

This article has been organized into the "JavaScript micro-Credit Development Skills Summary", welcome to learn to read.

For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.