1. 程式人生 > 程式設計 >Nodejs實現微信分賬的示例程式碼

Nodejs實現微信分賬的示例程式碼

公司的業務的場景需要用到微信分賬的功能、對著官網文件除錯了一下午才調通、記錄下使用Nodejs微信分賬的流程。

前提條件

  • 在微信商戶平臺 產品中心->我的產品,支付擴充套件工具中 開通分賬的功能
  • 新增分賬接收方。 這一步不設定的話回報一個*分賬接收方關係不存在,請檢查引數中每個接收方的關係。*錯誤
  • 在商戶平臺獲取商戶id和secrect
  • 需要將apiclient_cert.pem、 apiclient_key傳到伺服器某個目錄下面

具體實現

// @router post -> share -> /common/payment/share
async share() {
 const { ctx } = this
 const nonce_str = ctx.service.wx.randomStr()
 // 商戶id
 const mch_id = '123456'
 // x小程式appid
 const appid = 'wx123456'
 // 訂單號
 const out_order_no = '1609745196755nFvdMaYub2'
 // 微信支付訂單號
 const transaction_id = '4200000801202101044301662433'
 // 商戶secrect
 const key = '9813490da1ffb80afaa36f6f1265e490'

 // 這一塊的引數官網文件上有詳細的說明
 const params = {
  appid,mch_id,nonce_str,out_order_no,receivers: `[{"account": "123qwe","amount": 1,"description": "description","type": "PERSONAL_OPENID"}]`,sign_type: 'HMAC-SHA256',transaction_id,}

 // 簽名方式必須是HMAC-SHA256
 const sign = ctx.service.wx.sign(params,key,'HMAC-SHA256')

 // xmlString
 const formData = `<xml>
  <appid>${appid}</appid>
  <mch_id>${mch_id}</mch_id>
  <nonce_str>${nonce_str}</nonce_str> 
  <out_order_no>${out_order_no}</out_order_no>
  <transaction_id>${transaction_id}</transaction_id>
  <sign>${sign}</sign>
  <sign_type>HMAC-SHA256</sign_type>
  <receivers>${params.receivers}</receivers>
 </xml>`

 const res = await ctx.curl(
  "https://api.mch.weixin.qq.com/secapi/pay/profitsharing",{
   // 需要使用證書apiclient_cert
   cert: fs.readFileSync(path.join(__dirname,'../../../cert/apiclient_cert.pem')),// 需要使用證書apiclient_key
   key: fs.readFileSync(path.join(__dirname,'../../../cert/apiclient_key.pem')),method: "post",data: formData,}
 )

 const datastring = res.data.toString()
 xml2js.parseString(datastring,(err,result) => {
  if (err) {
   ctx.throw(422,err)
  }

  console.log(result)
 })
}


// randomStr
// 生成隨機字串
randomStr(len = 24) {
 const str =
  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
 let result = '';
 for (let i = 0; i < len; i++) {
  result += str[Math.floor(Math.random() * str.length)];
 }
 return result;
}

// 簽名
// mchKey是商戶secrect,否則簽名不通過
sign(data,mchKey,signType = 'MD5') {
 const keys = [];
 for (const key in data) {
  if (data[key] !== undefined) {
   keys.push(key);
  }
 }
 // 字典排序=>key=value
 const stringA = keys
  .sort()
  .map(key => `${key}=${decodeURIComponent(data[key])}`)
  .join('&');
 // 拼接商戶key
 const stringSignTemp = stringA + '&key=' + mchKey;
 // 加密
 let hash;
 if (signType === 'MD5') {
  hash = crypto.createHash('md5').update(stringSignTemp);
 } else {
  hash = crypto.createHmac('sha256',mchKey).update(stringSignTemp,'utf8');
 }
 
 const paySign = hash.digest('hex').toUpperCase();
 return paySign;
}

如果遇到簽名不通過的問題。可以將你生成的formData放到介面簽名校驗工具進行逐步驗證、

Nodejs實現微信分賬的示例程式碼

分賬介面其他常見問題

到此這篇關於Nodejs實現微信分賬的示例程式碼的文章就介紹到這了,更多相關Nodejs 微信分賬內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!