Home > WeChat Applet > WeChat Development > Nodejs WeChat public account payment development

Nodejs WeChat public account payment development

高洛峰
Release: 2017-01-04 16:52:00
Original
2008 people have browsed it

odeJs WeChat public account function development, mobile H5 page calls WeChat’s payment function. In the past few days, node and h5 pages have been used to call WeChat's payment function according to the company's needs to complete payment requirements. Now let’s go through the development process again to help more developers successfully complete the development of WeChat payment functions. (WeChat does not yet provide node payment function)

1. Request CODE

The purpose of requesting code is to obtain the user's openid (the user's unique identification relative to the current official account) and access_token. 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 requires attention to several parameters:

1. appid The appid of the official account can be seen in the official account
2. redirect_uri Customized WeChat callback address. WeChat will jump to the redirect_uri address you defined after you request the above address. 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, there is nothing to say about this. Fixed response_type=code, for detailed instructions, please refer to the instructions on the WeChat official website
4. scope=snsapi_userinfo, just write it like this, for detailed instructions, please check the instructions on the WeChat official website
5. state=STATE, just write it like this , for detailed instructions, you can view the instructions on the WeChat official website
6. wechat_redirect is fixed like this. For detailed instructions, you can view the instructions on the WeChat official website
ps: Official website link:

2. Get access_token through code, openid

The value of code has been obtained in the first step, then you need to obtain the value of access_token and openid through code. The requested api
API https://api.weixin.qq .com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
Parameter description of api here:

1. appid WeChat official account id, obtained from WeChat official account background
2. Secret is the key of the WeChat official account. Get the code from the WeChat official account background. The first step is to get the code used.
4. Just fix grant_type=authorization_code.

3. Call the interface

access_token through access_token to perform subsequent functions. You 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

4. Call up the payment API on the web page

When you see this, you feel that it is almost over. As long as the web page calls the WeChat payment function, it will be over. ? No, not even close

Open the H5 webpage in the WeChat browser and execute JS to activate the payment. The input and output data format of the interface 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", //公众号名称,由商户传入 
  "timeStamp":" 1395712654",  //时间戳,自1970年以来的秒数 
  "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 
  "package" : "prepay_id=u802345jgfjsdfgsdg888", 
  "signType" : "MD5",  //微信签名方式: 
  "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
 },
 function(res){ 
  if(res.err_msg == "get_brand_wcpay_request:ok" ) {} // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。 
 }
 ); 
}
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();
}
Copy after login

See the above code, then if you want to call the payment function of WeChat, you need to pass parameters,

{
 "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 
 "timeStamp":" 1395712654",  //时间戳,自1970年以来的秒数 
 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 
 "package" : "prepay_id=u802345jgfjsdfgsdg888", 
 "signType" : "MD5",  //微信签名方式: 
 "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
}
Copy after login

Parameter description:

1. appId //Official account name, passed in by the merchant

2. timeStamp //Timestamp, the number of seconds since 1970 Special attention needs to be paid here, it needs to be in the timestamp format of a string, which means it must be " ” Quotation marks
3. nonceStr // Random string 32 bits, method will be provided later
4. signType // WeChat signature method: MD5
5. paySign // WeChat signature, then
6 . **package** //This is the most important. Where did you get it? Next.
ps: Official website interface description
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6

5. Get the package from WeChat’s unified ordering interface obtains prepay_id

Official api:

https://api.mch.weixin.qq.com/pay/unifiedorder

There are a lot of request parameters, but Some of them are not necessary. The following are the required parameters.

{
 appid : APPID,
 attach : ATTACH,
 body : BODY,
 mch_id : MCH_ID,
 nonce_str: NONCE_STR,
 notify_url : NOTIFY_URL,// 微信付款后的回调地址
 openid : OPENID,
 out_trade_no : OUT_TRADE_NO ,//new Date().getTime(), //订单号
 spbill_create_ip : SPBILL_CREATE_IP , //客户端的 ip
 total_fee : TOTAL_FEE, //商品的价格, 此处需要注意的是这个价格是以分算的, 那么一般是元, 你需要转换为 RMB 的元
 trade_type : 'JSAPI',
}
Copy after login

WeChat’s unified ordering interface requires the transmission of xml data, and the data also needs to be signed, so first sign the data.

For signature rules, please refer to the signature rules given by WeChat (the signature method will be given later)
WeChat official 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 xml format:

var body = &#39;<xml> &#39; +
 &#39;<appid>&#39;+config.wxappid+&#39;</appid> &#39; +
 &#39;<attach>&#39;+obj.attach+&#39;</attach> &#39; +
 &#39;<body>&#39;+obj.body+&#39;</body> &#39; +
 &#39;<mch_id>&#39;+config.mch_id+&#39;</mch_id> &#39; +
 &#39;<nonce_str>&#39;+obj.nonce_str+&#39;</nonce_str> &#39; +
 &#39;<notify_url>&#39;+obj.notify_url+&#39;</notify_url>&#39; +
 &#39;<openid>&#39;+obj.openid+&#39;</openid> &#39; +
 &#39;<out_trade_no>&#39;+obj.out_trade_no+&#39;</out_trade_no>&#39;+
 &#39;<spbill_create_ip>&#39;+obj.spbill_create_ip+&#39;</spbill_create_ip> &#39; +
 &#39;<total_fee>&#39;+obj.total_fee+&#39;</total_fee> &#39; +
 &#39;<trade_type>&#39;+obj.trade_type+&#39;</trade_type> &#39; +
 &#39;<sign>&#39;+obj.sign+&#39;</sign> &#39; + // 此处必带签名, 否者微信在验证数据的时候是不通过的
 &#39;</xml>&#39;;
Copy after login

The next step is to request the api to get the value of prepay_id, and request the xml data obtained above The following api is sent to WeChat. WeChat will return the value you want after verifying that the data is OK.

api: https://api.mch.weixin.qq.com/pay/unifiedorder

6. After obtaining the prepay_id, can I directly call WeChat payment in the h5 section? The answer is not yet.

After obtaining the prepay_id, the parameters for h5 to call WeChat’s payment function are as follows:

{
 "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 
 "timeStamp":" 1395712654",  //时间戳,自1970年以来的秒数 
 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 
 "package" : "prepay_id=u802345jgfjsdfgsdg888", 
 "signType" : "MD5",  //微信签名方式:
}
Copy after login

有了这样的参数, 那么你还需要吧所有参与的参数做签名。签名规跟上面的一样,生成了签名后需要吧签名的参数 paySign 赋给h5 呼起微信的支付功能的参数(也就是微信的签名不参与签名的生成)
最后的参数是这样子的:

{
 "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 
 "timeStamp":" 1395712654",  //时间戳,自1970年以来的秒数 
 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 
 "package" : "prepay_id=u802345jgfjsdfgsdg888", 
 "signType" : "MD5",  //微信签名方式:
 "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
}
Copy after login

如果你的各个环节都没有问题, 那么得到了这样参数后你就可以正常的调用起微信的支付功能, 跟原生的功能是没有任何的差别的,(估计你现在的心里也特高兴吧, 没有 app 竟然可以使用 app 的功能,就是这么的神奇)。

七.支付完成的回调

微信支付完了后会在 h5 页面的微信支付的回调函数里面放回值,
res.err_msg == "get_brand_wcpay_request:ok" ,这样就是成功了, 但是不是就完事儿了呢 ? 也不是,为什么呢? 微信真的收到钱了么? 收到的钱是不是你传递给微信的值呢 ?你还需要将支付的结果写数据库什么的,这些都是未知。还记的在统一下单接口中有个必须参数就是 notify_url : NOTIFY_URL,// 微信付款后的回调地址 这个地址是用户传递给微信的, 微信在收到用户的付款后会以 post 的方式请求这个接口,微信会传递用户付款的信息过来, 不过是 xml 格式的。
类系这样的 xml 格式:

<xml>
 <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
 <attach><![CDATA[支付测试]]></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>
Copy after login

根据自己的业务逻辑解析这个 xml 格式的数据就好了。
注意:这里你在获取到数据后微信需要得到你的回应, 如果你一直不回应微信, 微信会请求你好几次, 这样估计你的逻辑会有问题吧,所以你需要给微信返回 xml 的格式的 回应。

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

小坑:node ,express 框架开发, 如果你在微信的支付成功后的回调中没有获取到任何 xml 的值, 那么你需要安装一组件:body-parser-xml, 你可以使用 npm install body-parser-xml --save 安装, 在 app.js 里面require('body-parser-xml')(bodyParser);,使用中间件的方式

// 解决微信支付通知回调数据
app.use(bodyParser.xml({
 limit: &#39;2MB&#39;, // 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
 }
}));
Copy after login

这样你就可以正常的获取到微信的 xml 数据了。

使用方法:

pay.getAccessToken({
 notify_url : &#39;http://demo.com/&#39;, //微信支付完成后的回调
 out_trade_no : new Date().getTime(), //订单号
 attach : &#39;名称&#39;,
 body : &#39;购买信息&#39;,
 total_fee : &#39;1&#39;, // 此处的额度为分
 spbill_create_ip : req.connection.remoteAddress,
 }, function (error, responseData) {
 res.render(&#39;payment&#39;, {
  title : &#39;微信支付&#39;,
  wxPayParams : JSON.stringify(responseData),
  //userInfo : userInfo
 });
 });
Copy after login

就到这里吧, 感觉也差不多了。如有不对的地方还请指正。

更多nodejs微信公众号支付开发相关文章请关注PHP中文网!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template