支付的大致流程如下:
- 小程序端用 wx.request 向服務(wù)器請(qǐng)求支付參數(shù)(相當(dāng)于ajax)
- 服務(wù)器根據(jù)客戶(hù)端的 sessionId , 找到 它的 openId, 將它和商家自己的 應(yīng)用id, 商戶(hù)號(hào), 支付密鑰等 和商品的一系列(包括價(jià)格/商品描述)這些信息用規(guī)定的方式拼接起來(lái), 然后加密, 去請(qǐng)求微信的服務(wù)器
- 微信的服務(wù)器向商家服務(wù)器返回這次交易需要的數(shù)據(jù)(prepay_id等)
- 商家服務(wù)器處理上述數(shù)據(jù), 并且和其他需要用到的信息一起返回給用戶(hù)端(小程序前端)使用
- 用戶(hù)端(小程序前端)接收到數(shù)據(jù), 使用這些信息調(diào)用 wx.requestPayment 接口
- 微信服務(wù)器主動(dòng)向商家的服務(wù)器發(fā)送本次支付的信息(是否成功等), 商戶(hù)服務(wù)器根據(jù)微信發(fā)來(lái)的數(shù)據(jù)判斷用戶(hù)是否完成支付
官方的文檔在這里
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1
話(huà)不多說(shuō), 代碼如下
1. 準(zhǔn)備好一些需要用的常量
const axios = require('axios')
const md5 = require('blueimp-md5')
const xml2js = require('xml2js')
const xmlParser = new xml2js.Parser()
const appId = 'your wx appId'
const appSecret = 'your wx app secret'
// 商戶(hù)號(hào)
const mchId = 'mch id'
// 支付api 的 key
const PAY_API_KEY = 'pay api key'
// 一個(gè)方便的 log 方法
const log = console.log.bind(console)
2. 準(zhǔn)備一些工具方法(函數(shù))
由于獲取支付簽名的代碼比較多, 這里先一股腦把他們封裝到函數(shù)里面
后面只需要調(diào)用這些函數(shù)就可以的
// 預(yù)定義的一些工具函數(shù)
function getNonceStr() {
var text = ""
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for (var i = 0; i < 16; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
function getPaySign(appId, timeStamp, nonceStr, package) {
var stringA = 'appId=' + appId +
'&nonceStr=' + nonceStr +
'&package=' + package +
'&signType=MD5' +
'&timeStamp=' + timeStamp
var stringSignTemp = stringA + '&key=' + PAY_API_KEY
var sign = md5(stringSignTemp).toUpperCase()
return sign
}
function getTradeId(attach) {
var date = new Date().getTime().toString()
var text = ""
var possible = "0123456789"
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
var tradeId = 'ty_' + attach + '_' + date + text
return tradeId
}
function getPrePaySign(appId, attach, productIntro, mchId, nonceStr, notifyUrl, openId, tradeId, ip, price) {
var stringA = 'appid=' + appId +
'&attach=' + attach +
'&body=' + productIntro +
'&mch_id=' + mchId +
'&nonce_str=' + nonceStr +
'¬ify_url=' + notifyUrl +
'&openid=' + openId +
'&out_trade_no=' + tradeId +
'&spbill_create_ip=' + ip +
'&total_fee=' + price +
'&trade_type=JSAPI'
var stringSignTemp = stringA + '&key=' + PAY_API_KEY
var sign = md5(stringSignTemp).toUpperCase()
return sign
}
function wxSendData(appId, attach, productIntro, mchId, nonceStr, notifyUrl, openId, tradeId, ip, price, sign) {
const sendData = '<xml>' +
'<appid>' + appId + '</appid>' +
'<attach>' + attach + '</attach>' +
'<body>' + productIntro + '</body>' +
'<mch_id>' + mchId + '</mch_id>' +
'<nonce_str>' + nonceStr + '</nonce_str>' +
'<notify_url>' + notifyUrl + '</notify_url>' +
'<openid>' + openId + '</openid>' +
'<out_trade_no>' + tradeId + '</out_trade_no>' +
'<spbill_create_ip>' + ip + '</spbill_create_ip>' +
'<total_fee>' + price + '</total_fee>' +
'<trade_type>JSAPI</trade_type>' +
'<sign>' + sign + '</sign>' +
'</xml>'
return sendData
}
function getPayParams(prepayId, tradeId) {
const nonceStr = getNonceStr()
const timeStamp = new Date().getTime().toString()
const package = 'prepay_id=' + prepayId
const paySign = getPaySign(appId, timeStamp, nonceStr, package)
// 前端需要的所有數(shù)據(jù), 都從這里返回過(guò)去
const payParamsObj = {
nonceStr: nonceStr,
timeStamp: timeStamp,
package: package,
paySign: paySign,
signType: 'MD5',
tradeId: tradeId,
}
return payParamsObj
}
3. 這時(shí), 前端發(fā)請(qǐng)求過(guò)來(lái)了, 需要給他返回支付簽名
如果是在 express 下, 下面的代碼應(yīng)該是在一個(gè)長(zhǎng)成這樣的方法里面:
app.get('/paysign', (req, res) => {
// 代碼應(yīng)該在這里
})
// attach 是一個(gè)任意的字符串, 會(huì)原樣返回, 可以用作一個(gè)標(biāo)記
const attach = 'GJS-ORG'
// 一個(gè)隨機(jī)字符串
const nonceStr = getNonceStr()
// 用戶(hù)的 openId
const openId = 'user openId'
// 生成商家內(nèi)部自定義的訂單號(hào), 商家內(nèi)部的系統(tǒng)用的, 理論上只要不和其他訂單重復(fù), 使用任意的字符串都是可以的
const tradeId = getTradeId(attach)
// 生成簽名
const sign = getPrePaySign(appId, attach, productIntro, mchId, nonceStr, notifyUrl, openId, tradeId, ip, price)
// 這里是在 express 獲取用戶(hù)的 ip, 因?yàn)槭褂昧?nginx 的反向代理, 所以這樣獲取
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
ip = ip.match(/\d+\.\d+\.\d+\.\d+/)[0]
將微信需要的數(shù)據(jù)拼成 xml 發(fā)送出去
const sendData = wxSendData(appId, attach, productIntro, mchId, nonceStr, notifyUrl, openId, tradeId, ip, price, sign)
// 使用 axios 發(fā)送數(shù)據(jù)帶微信支付服務(wù)器, 沒(méi)錯(cuò), 后端也可以使用 axios
axios.post('https://api.mch.weixin.qq.com/pay/unifiedorder', sendData).then(wxResponse => {
// 微信返回的數(shù)據(jù)也是 xml, 使用 xmlParser 將它轉(zhuǎn)換成 js 的對(duì)象
xmlParser.parseString(wxResponse.data, (err, success) => {
if (err) {
log('parser xml error ', err)
} else {
if (success.xml.return_code[0] === 'SUCCESS') {
const prepayId = success.xml.prepay_id[0]
const payParamsObj = getPayParams(prepayId, tradeId)
// 返回給前端, 這里是 express 的寫(xiě)法
res.json(payParamsObj)
} else {
// 錯(cuò)誤處理
if (err) {
log('axios post error', err)
res.sendStatus(502)
} else if (success.xml.return_code[0] !== 'SUCCESS') {
res.sendStatus(403)
}
}
}
})
}).catch(err => {
log('post wx err', err)
})