node 微信支付 V3版本签名生成

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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值