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

How to use explain to query SQL execution plan in MySql

The explain command is the primary way to see how...

Nginx builds rtmp live server implementation code

1. Create a new rtmp directory in the nginx sourc...

The difference and choice between datetime and timestamp in MySQL

Table of contents 1 Difference 1.1 Space Occupanc...

Use CSS to draw a file upload pattern

As shown below, if it were you, how would you ach...

CSS3 transition to achieve underline example code

This article introduces the sample code of CSS3 t...

Detailed explanation of execution context and call stack in JavaScript

Table of contents 1. What is the execution contex...

Example of how to install kong gateway in docker

1. Create a Docker network docker network create ...

About nginx to implement jira reverse proxy

Summary: Configure nginx reverse proxy jira and i...

Detailed explanation of the mechanism and implementation of accept lock in Nginx

Preface nginx uses a multi-process model. When a ...

VUE Getting Started Learning Event Handling

Table of contents 1. Function Binding 2. With par...

MYSQL A question about using character functions to filter data

Problem description: structure: test has two fiel...

Implementation of Docker cross-host network (manual)

1. Introduction to Macvlan Before the emergence o...

Install CentOS 7 on VMware14 Graphic Tutorial

Introduction to CentOS CentOS is an enterprise-cl...

Analysis of HTTP interface testing process based on postman

I accidentally discovered a great artificial inte...