Example code for implementing WeChat account splitting with Nodejs

Example code for implementing WeChat account splitting with Nodejs

The company's business scenario requires the use of the WeChat account splitting function. I debugged it according to the official website documentation for an afternoon before it was finally working, and recorded the process of using Nodejs WeChat account splitting.

Prerequisites

  • In WeChat Merchant Platform Product Center->My Products, enable the split account function in the payment extension tool.
  • Add a billing recipient. If this step is not set, a * split account receiver relationship does not exist will be reported. Please check the relationship of each receiver in the parameters. *mistake
  • Get the merchant ID and secret on the merchant platform
  • You need to transfer apiclient_cert.pem and apiclient_key to a directory on the server.

Specific implementation

// @router post -> share -> /common/payment/share
async share() {
 const { ctx } = this
 const nonce_str = ctx.service.wx.randomStr()
 //Merchant id
 const mch_id = '123456'
 // x applet appid
 const appid = 'wx123456'
 // Order number const out_order_no = '1609745196755nFvdMaYub2'
 // WeChat payment order number const transaction_id = '4200000801202101044301662433'
 //Merchant secrect
 const key = '9813490da1ffb80afaa36f6f1265e490'

 // The parameters of this block are described in detail in the official documentation 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,
 }

 // The signature method must be 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",
  {
   // Need to use the certificate apiclient_cert
   cert: fs.readFileSync(path.join(__dirname,'../../../cert/apiclient_cert.pem')),
   // Need to use the certificate 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
// Generate a random string 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;
}

// Signature // mchKey is the merchant's secrect, otherwise the signature will not pass sign(data, mchKey, signType = 'MD5') {
 const keys = [];
 for (const key in data) {
  if (data[key] !== undefined) {
   keys.push(key);
  }
 }
 // Dictionary sort => key=value
 const stringA = keys
  .sort()
  .map(key => `${key}=${decodeURIComponent(data[key])}`)
  .join('&');
 // Concatenate merchant key
 const stringSignTemp = stringA + '&key=' + mchKey;
 // encrypt 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;
}

If you encounter the problem of signature failure. You can put the formData you generated into the interface signature verification tool for step-by-step verification.

Other common problems with the account splitting interface

This is the end of this article about the sample code for implementing WeChat account splitting with Nodejs. For more relevant content about WeChat account splitting with Nodejs, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Nodejs error handling process record
  • Detailed explanation of how to quickly operate MySQL database in nodejs environment
  • A complete example of implementing a timed crawler with Nodejs
  • Differences between this keyword in NodeJS and browsers
  • The core process of nodejs processing tcp connection
  • Detailed explanation of Nodejs array queue and forEach application
  • Learn asynchronous programming in nodejs in one article
  • How to create a child process in nodejs
  • How to use worker_threads to create new threads in nodejs
  • Implementation of WeChat applet message push in Nodejs
  • Detailed explanation of asynchronous programming knowledge points in nodejs
  • The simplest way to connect to the database with nodejs+express
  • How to downgrade the installed nodejs high version to a lower version in windows (graphic tutorial)
  • Detailed explanation of the implementation process of NodeJS CORS configuration
  • How to use nodejs to automatically send email reminders at regular intervals (super practical)
  • Simple deployment of nodeJs project in Alibaba Cloud
  • How to use nodejs to implement command line games
  • Understanding what Node.js is is so easy

<<:  MySQL 5.7.17 winx64 free installation version configuration method graphic tutorial

>>:  A method of hiding processes under Linux and the pitfalls encountered

Recommend

Practical record of optimizing MySQL tables with tens of millions of data

Preface Let me explain here first. Many people on...

18 common commands in MySQL command line

In daily website maintenance and management, a lo...

How to use Flex layout to achieve scrolling of fixed content area in the head

The fixed layout of the page header was previousl...

A brief discussion on several ways to pass parameters in react routing

The first parameter passing method is dynamic rou...

Vue axios interceptor commonly used repeated request cancellation

introduction The previous article introduced the ...

XHTML Getting Started Tutorial: What is XHTML?

What is HTML? To put it simply: HTML is used to m...

Example of how rem is adapted for mobile devices

Preface Review and summary of mobile terminal rem...

The concept and characteristics of MySQL custom variables

A MySQL custom value is a temporary container for...

Node.js implements breakpoint resume

Table of contents Solution Analysis slice Resume ...

Vue calls the PC camera to realize the photo function

This article example shares the specific code of ...

JavaScript data visualization: ECharts map making

Table of contents Overview Precautions 1. Usage 2...

JavaScript+html to implement front-end page sliding verification

This article shares the specific code of JavaScri...