Micro-channel pay nodejs

https://www.jianshu.com/p/40142493a620

 

 

nodejs - scratch docking micro letter payment (nothing, only began practicing license)

Xie Xiuyue concern

32019.01.27 14:01:40 number of words read 1,075 2,874

No business license, in fact, can also be achieved, that is too much trouble, taking the black line technology, reference payjs, that as long as you can pay three hundred dollars, do not need to go toss, please pass ash production.

nodejs pure native example, copy can be used directly, without frame burden.
nodejs微信支付最佳实践
nodejs微信支付源码
nodejs微信支付代码、例子
Because I Alipay also used black technology, so I can not disclose, we talk about how nodejs how micro-channel payment, starting from the application (no public number, etc.).

1: micro-channel payment application

This step is free.

https://pay.weixin.qq.com  Click to go to the following page

Click to become a business
to enter the following link
https://pay.weixin.qq.com/index.php/apply/applyment_home/guide_normal
then scan code to apply it.
Note 1, if it is self-employed and run an online store is no corresponding section, pick a .6 column can be. (Why not choose a lower, because they are found in a lot of trouble Oh, the other to say?)
Note 2: Do not encountered a problem with micro-channel customer service, you wait forever because they are the party again. (I hung up for two days, access is still, oh, when there has been prompt ten people queuing)

After the application is successful micro-channel without guidance how do you how I see the need butt documents say the public needs above number id, so we need a public number.

2: public registration number

https://mp.weixin.qq.com  into the public registration number, service number and subscription number can, I recommend using a service number, and more authority, and will not be stowed (user difficult to find the entrance).
Then follow the prompts to see how long luck audit completed

3: Copy appid with application appSecret

Developer Center -> Configuration Items

4: micro-channel business application platform API key platform certificate

Portal  https://pay.weixin.qq.com/index.php/core/cert/api_cert
platform certificate is p12

5, using the ready-wheel docking pay

tip: copy the way businesses under No.

npm install weixin-pay

New pay to obtain public documents to export these objects

var wxpayInfo = {
    appid: 'wx**打码**8',
    mch_id: '1**打码**1',
}
var wxMp = {
    appid: 'wx**打码**8',
    appSecret: '4567**打码**8',
}
var wxpay = WXPay({
    ...wxpayInfo,
    partner_key: 'uiiwx**打码**8', //微信商户平台API密钥
    pfx: fs.readFileSync('./wx/**打码**.p12'), //微信商户平台证书
})

Assuming that the configuration was called Config.

No public pay

Config.wxpay.getBrandWCPayRequestParams({
        openid,
        body,
        detail,
        out_trade_no,
        // 微信金额是以分做单位
        total_fee: amount * 100,
        spbill_create_ip,
        notify_url: 'http://**打码**'
    },  async (err, result) => {
        // CODE  
                // **打码**
    })

However, we found that there are no parameters for that openid, the public does not support the number is sweeping yards, including two-dimensional code Photo Gallery can not, you can not press scan code (in order to increase the authenticity, I did a pro-test, micro-letter web page was blocked micro-channel protocol, that is, you can not use the native pay [pay with native scan code can be skipped openid])
scan code to pay

wxpay.createUnifiedOrder({
    body: '扫码支付测试',
    out_trade_no: '20140703'+Math.random().toString().substr(2, 10),
    total_fee: 1,
    spbill_create_ip: '192.168.2.210',
    notify_url: 'http://wxpay_notify_url',
    trade_type: 'NATIVE',
    product_id: '1234567890'
}, function(err, result){
    console.log(result);
})

But we certainly do micro-channel payment page, so the public is required to pay number.

6: Get CODE

First attach the official micro-channel link, a good ability to understand the need to see the following
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
1: public platform in the official website of "development first come - Interface permissions - web services - web account - web authorization to obtain information about users' configuration options, modify the callback authorization domain. (No need to write http, https protocol)
注意: OAuth2.0 authentication domain to specific needs precise path. # Can be considered, I do not think everything will be fine hash mode.
2: Get the code
carried Jump in page.
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base &state=STATE#wechat_redirect

The next redirect_uri with appid can change. If you need to xxxxx, user information (a user-determined window will pop up), the scope changedsnsapi_userinfo

Under reference to my code

// 微信环境,未授权的进入静默授权,并记录openid到数据库 (支付必须使用openid, 微信里面的网页被微信封了二维码和原生支付)
;(async () => {
  // 用户是否授权了微信
  let wxOpenidInfo = await Config.wxOpenidGet()
  // 分隔符,判断回调
  ,state = 'gou_weixin_return_code__' + Config.wxBase.appid
  // 获取code url
  ,getCodeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${Config.wxBase.appid}&redirect_uri=${Config.wxBase.redirect_uri |> encodeURI}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`
  // 获取到的code
  ,codeParams = 'code' |> Config.getUrlParams
  // 获取openid结果
  ,openidResult

  // --------------return 已授权的用户
  if(wxOpenidInfo)
    return
  //------------- 未授权, 未收到code
  if(location.href.indexOf(state) < 0){
    // 去获取code
    location.href = getCodeUrl
    return
  }
  // -----------未授权, 已收到code
  openidResult = await Http.user['wxGetOpenid']({code: codeParams})()
  // 换取openid失败
  if(openidResult.code !== 0){
    openidResult.code === 1 && xxy.toast(openidResult.msg)
    return
  }
  // 换取成功, 储存到openid本地一份, 此时完成后就是已授权了
  openidResult.msg |> Config.wxSaveOpenid
}) |> Config.isWx

There are above xxy(here used a pop, you change your),  HTTP, into your request, Config, a few basic configuration into your own.
Attach two function codes, the communication terminal determines whether the micro with whether to authorize

  isWx(cb, err){
        // 微信环境
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            cb && cb() 
        }else{
            err && err()
        }
    }
    // 用户是否授权了微信
    wxOpenidGet(){
        return new Promise((resolve) => {
            if(localStorage.openid && localStorage.openid.length > 5){
                resolve(true)
                return
            }
            resolve(false)
        })
    }

7: exchange openid

废话少说, 直接上代码, 全是原生实现, 直接copy就可以使用
var https = require('https')
exports.wxGetOpenid = (params) => new Promise(async (resolve, reject) => {
    let {code} = params
    var url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${Config.wxMp.appid}&secret=${Config.wxMp.appSecret}&code=${code}&grant_type=authorization_code`
    https.get(url, (res) => {
        var datas = ''
        res.on('data', (d) => {
            datas += d
        })
        res.on('end', (d) => {
            var result = JSON.parse(datas)
            if(result.errcode){
                resolve({code: 1, msg: result.errmsg})
                return
            }
            if(result.openid){
                resolve({code: 0, msg: result.openid})
                return
            }
        })
    })
    .on('error', (e) => {
      resolve({code: 0, msg: '服务器异常'})
          // ** 打码 **
    })
})

8: Docking callback processing, refund processing

After completion of the payment function to get openid, completed in step 5

Callback

var util = require('weixin-pay/lib/util.js')
    var xml = Object.keys(body)[0]
    util.parseXML(xml, async (err, msg) => {
        var pkg = JSON.parse(JSON.stringify(msg))
        let sign = msg.sign
        delete pkg.sign
        if (sign !== Config.wxpay.sign(pkg)) {
            // 签名失败,请求不是来自于微信服务器。
                        // **打码**
            return
        }
                // CODE
})

Refund

var params = {
    ...Config.wxpayInfo,
    op_user_id: Config.wxpayInfo.mch_id,
    out_refund_no: '20140703'+Math.random().toString().substr(2, 10),
    total_fee: '1', //原支付金额  (以分为单位)
    refund_fee: '1', //退款金额
    transaction_id: '微信订单号'
};

wxpay.refund(params, function(err, result){
    console.log('refund', arguments);
});

OK

Reference links:
https://github.com/tvrcgo/weixin-pay
http://mysy.vip
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

Published 444 original articles · won praise 25 · views 180 000 +

Guess you like

Origin blog.csdn.net/ozhy111/article/details/103527273