Home  >  Article  >  WeChat Applet  >  Nodejs develops WeChat payment function

Nodejs develops WeChat payment function

Y2J
Y2JOriginal
2017-05-13 15:43:583419browse

This article mainly introduces the development of nodejs WeChat public account payment in detail, which has certain reference value. Interested friends can refer to

odeJs WeChat public account function development, mobile H5 The 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 relative to the current public account Unique identifier) ​​and access_token, requested API: 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 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 address of the redirect_uri 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 much to say about this, just fixed response_type=code. For detailed instructions, you can check the instructions on the WeChat official website
4. scope=snsapi_userinfo, just write it like this , for detailed instructions, you can check the instructions on the WeChat official website
5. State=STATE is fixed like this, and for detailed instructions, you can check the instructions on the WeChat official website
6. wechat_redirect is fixed like this, and for detailed instructions, you can check the WeChat official website Note
ps: Official website link:

2. Obtain access_token, openid through code

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

1. appid WeChat public account id, obtained from the WeChat public account background
2. secret WeChat public account key, obtained from the WeChat public account background
3. code, the first step is to obtain the used code
4. Just fix grant_type=authorization_code

3. Call theinterface through access_token

access_token can be used for subsequent functions. You can refer to the official example:
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

Seeing this, do 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();
}

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" //微信签名 
}

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 a string timestamp format, which means it must be "" quotation marks
3. nonceStr //Random string 32 bits, a method will be provided later
4. signType //WeChat signature method: MD5
5. paySign //WeChat signature, then say
6. **package** //This is the most important, where did you get it? Next.
ps: Official website interface description
pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6

##5 .Get the package, Obtain the prepay_id from WeChat’s unified order interface

Official api:


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

请求参数一堆, 但是有一些不是必须的,下面是必须参数

{
 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',
}

微信的统一下单接口要求传递的是 xml 的数据, 而且数据还需要签名, 那么首先吧数据签名。
签名规则可以参考微信给出的签名规则(签名方法一会给出)
微信官方签名规则:
pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3

生成签名后需要吧数据组装为xml 的格式:

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

接下来就是请求 api 获取prepay_id的值了, 将上面得到的 xml 数据请求下面的 api 发送给微信, 微信验证数据没问题后会放回你想要的值。
api : api.mch.weixin.qq.com/pay/unifiedorder

六. 获取到了prepay_id是不是就可以在 h5 段直接调用微信的支付了么? 答案是还不可以。

获取到了prepay_id那么现在h5 呼起微信的支付功能的参数是这样的:

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

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

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

如果你的各个环节都没有问题, 那么得到了这样参数后你就可以正常的调用起微信的支付功能, 跟原生的功能是没有任何的差别的,(估计你现在的心里也特高兴吧, 没有 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>

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

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

小坑: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
 }
}));

这样你就可以正常的获取到微信的 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
 });
 });

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

【相关推荐】

1. 特别推荐:“php程序员工具箱”V0.1版本下载

2. 微信小程序完整源码

3. 微信小程序demo:果库更新版

The above is the detailed content of Nodejs develops WeChat payment function. For more information, please follow other related articles on the PHP Chinese website!

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