const at = require('auto-bind')
const { KJUR, hextob64 } = require('jsrsasign')
const axios = require('axios')
class Post {
constructor() {
at(this)
}
// 上传发票文件到微信
async uploadInvoice(req, res, next) {
try {
const method = 'POST'
const pathname = '/v3/pay/transactions/native'
const timestamp = Math.round(new Date().getTime() / 1000); // 十位的时间戳
const onece_str = await this.randomString() // 随机字符串
const bodyParamsStr = {
'mchid': '商户号',
'out_trade_no': '证书序列号',
'appid': '应用id',
'description': 'Image形象店-深圳腾大-QQ公仔',
'notify_url': '支付成功的回调地址',
'support_fapiao': true, // 是否开发票
'amount': {
'total': 1, // 总金额,单位分
'currency': 'CNY' // 币种
}
}
const mchid = 'xxxxxx' // 商户号
const serial_no = 'xxxxxxxxxx' // 商户API证书序列号
const private_key = `-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
` // appiclient_key.pem里的内容全部复制过来
const signature = await this.rsaSign(`${method}\n${pathname}\n${timestamp}\n${onece_str}\n${JSON.stringify(bodyParamsStr)}\n`, private_key, 'SHA256withRSA')
//获取到signature后就可以获取到Authorization了
let Authorization = `WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",nonce_str="${onece_str}",timestamp="${timestamp}",signature="${signature}",serial_no="${serial_no}"`
const data = await axios.post('https://api.mch.weixin.qq.com/v3/pay/transactions/native', bodyParamsStr, {
headers: {
Authorization
}
})
console.log(data);
res.json(data.data)
} catch (error) {
console.log(error.response.data);
return next(error)
}
}
// 加密
async rsaSign(content, privateKey, hash = 'SHA256withRSA') {
// 创建 Signature 对象
const signature = new KJUR.crypto.Signature({
alg: hash,
//!这里指定 私钥 pem!
prvkeypem: privateKey
})
signature.updateString(content)
const signData = signature.sign()
// 将内容转成base64
return hextob64(signData)
}
// 生成随机数
async randomString(e = 32) {
const t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
const a = t.length
let n = ''
for (let index = 0; index < e; index++) {
n += t.charAt(Math.floor(Math.random() * a))
}
return n
}
}
module.exports = new Post()
node 微信支付 V3版本签名生成
于 2022-12-19 11:47:52 首次发布