這篇文章主要介紹了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 微信分賬內容請關注站長圖庫。






