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'
const private_key = `-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
`
const signature = await this.rsaSign(`${method}\n${pathname}\n${timestamp}\n${onece_str}\n${JSON.stringify(bodyParamsStr)}\n`, private_key, 'SHA256withRSA')
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') {
const signature = new KJUR.crypto.Signature({
alg: hash,
prvkeypem: privateKey
})
signature.updateString(content)
const signData = signature.sign()
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()