在开发微信小程序的时候,要实现微信支付,要做好以下准备:
1、注册微信公众平台
2、创建一个微信小程序
3、注册申请微信支付商户
4、获取 API 证书和私钥,用于调用微信支付 API 和验证回调消息的签名
5、配置你的 Node.js 服务以使用 HTTPS,因为微信支付 API 需要通过 HTTPS 调用。
在node.js后端中,下载fs
const fs = require('fs')
let cert = fs.readFileSync('key/apiclient_cert.pem')
let PRIMARY_PEM = fs.readFileSync('key/apiclient_key.pem')
function joinMessage(...args) {
return args.join('\n') + '\n'
}
function calcSign(msg) {
return Rsa.sign(msg, PRIMARY_PEM)
}
function joinAuthMessage(timestamp, nonce_str, signature) {
return utils.parseObj2QsVsQuote({
mchid: config.MCHID,
serial_no: config.SERIAL_NO,
nonce_str,
timestamp,
signature
})
}
utils.js
function parseObj2QsVsQuote(obj) {
return Object.keys(obj).map(k => `${k}="${obj[k]}"`).join()
}
编写接口实现微信支付
app.post('/pay', async (req, res) => {
let { money, openid } = req.body
try {
let timeStamp = utils.timeStamp()
let nonceStr = utils.getGuid()
let body = {
appid: config.APPID,
mchid: config.MCHID,
description: '描述',
out_trade_no: nonceStr,
notify_url: '接收支付情况url',
amount: { total: parseFloat(money) },
payer: { openid: openid }
}
let message = joinMessage('POST', '/v3/pay/transactions/jsapi', timeStamp, nonceStr, JSON.stringify(body))
let signature = calcSign(message)
let authMessage = joinAuthMessage(timeStamp, nonceStr, signature)
const API_PAY = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi'
let { data: { prepay_id } } = await axios.post(API_PAY, body, {
headers: {
Authorization: 'WECHATPAY2-SHA256-RSA2048' + ' ' + authMessage
}
})
let package = 'prepay_id=' + prepay_id
let paySign = calcSign(joinMessage(config.APPID, timeStamp, nonceStr, package))
res.json({
nonceStr,
package,
paySign,
timeStamp,
signType: 'RSA'
})
} catch (error) {
if (error.response)
console.log(error.response.data);
else console.log(error);
}
})
微信小程序前端发起请求获得返回参数后,调用微信官方API发起支付
wx.requestPayment
(
{
timeStamp: res.data.timeStamp,
nonceStr: nonceStr,
package: res.data.package,
signType: res.data.signType,
paySign: res.data.paySign,
success: async (res) => {
console.log(res)
console.log('支付成功');
},
fail: function (res) { console.log(res) },
complete: function (res) { console.log(res) }
}
)