Implementation of WeChat applet message push in Nodejs

Implementation of WeChat applet message push in Nodejs

Select or create a subscription message template

Log in to the WeChat applet and find Function->Subscribe to Messages. You can select the template you need in the public template library. If you don’t find what you need, you can create it yourself and wait for review.

After selecting a template and viewing its details, you will get the template ID and the fields required for sending push notifications.

The applet sends a subscription request

The template ID obtained in the previous step is required

// Mini Program<Text className='rights-buy' onClick={this.messageSubmit}>
 Application for admission</Text>

// Subscribe to the settlement application message messageSubmit = () => {
 Taro.requestSubscribeMessage({
  tmplIds: ['SuGMwqyYY9cocuP-LxfElcM3a7ITaF34lKNux6EaE9'],
  success: (res) => {
   //Call the server interface and write a subscription record in the database // this.subscribeDeal()
  }
 })
}

The server initiates the push

There are generally two types of push

  • Manual trigger,
  • Another thing is that after subscribing to a message, a certain condition is met and the push is automatically triggered.

For the first case, just call WeChat's push interface directly. The second situation is a little more troublesome. You can add a timed task, or use a related queue library to trigger when the conditions are met.

Things to note

  • When sending push, the user's openid and template id are required. The specific push content fields can be viewed in the first step template details.
  • When calling the WeChat push interface, you need access_token. It is best to cache it. Frequent calls may cause invalidation.

Get access_token and cache it

async getAccessToken () {
 const { appId, appSecert, host } = this.app.config.idolWxAConfig;

 return new Promise(async (resolve) => {
  const currentTime = new Date().getTime()

  const redisToken = await this.app.redis.get('wxtoken').get('token') || '{access_token: "", expries_time: 0}'
  const accessTokenJson = JSON.parse(redisToken)

  if (accessTokenJson.access_token === '' || accessTokenJson.expries_time < currentTime) {
   const res = await this.ctx.curl(`${host}/cgi-bin/token?appid=${appId}&secret=${appSecert}&grant_type=client_credential`, { dataType: 'json' })

   if (res.data) {

    accessTokenJson.access_token = res.data.access_token
    accessTokenJson.expries_time = new Date().getTime() + (parseInt(res.data.expires_in) - 200) * 1000

    await this.app.redis.get('wxtoken').set('token', JSON.stringify(accessTokenJson))
    resolve(accessTokenJson)
   }
  } else {
   resolve(accessTokenJson)
  }
 })
}

Send a push request to WeChat

async sendSubscribeMsg(openid) {

 let requestData = {
  "touser": `${openid}`,
  "template_id": "SuGMwqyYY9cocuP-LxfElcM3a7ITaF34lKNux6EaE9",
  "page": `/pages/certification/index`,
  "data": {
    "phrase2": {
     "value": `Approved`
    },
    "thing3": {
     "value": `Your application has been reviewed and approved`
    }
  }
 }

 const { host } = this.app.config.idolWxAConfig;
 // Get access_toekn
 const tokenJson = await this.ctx.service.wx.getAccessToken()
 const res = await this.ctx.curl(`${host}/cgi-bin/message/subscribe/send?access_token=${tokenJson.access_token}
 `, {
  method: 'POST',
  contentType: 'json',
  data: requestData,
  dataType: 'json'
 });

 if (res.data.errmsg === 'ok') {
  console.log('========Push successfully========')
  //TODO
 } else {
  console.log('========Push failed========')
  //TODO
 }
}

This is the end of this article about the implementation of Nodejs WeChat applet message push. For more relevant Nodejs applet message push content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Node event loop and process module example analysis
  • Understanding and application examples of Event Loop in node.js
  • Summary of knowledge points about non-blocking I/O and event loop in Node
  • Detailed explanation of Nodejs monitoring event loop exception example
  • A brief discussion on Node asynchronous IO and event loop
  • Nodejs implementation code for pushing messages through DingTalk group robots
  • Implementation of WeChat applet configuration message push in node.js
  • Broadcast message of socket.io in node.js
  • Analyzing the node event loop and message queue

<<:  How to install nginx in centos7

>>:  MySQL 5.7.17 free installation version configuration method graphic tutorial (windows10)

Recommend

Detailed explanation of Nginx current limiting configuration

This article uses examples to explain the Nginx c...

Implementation example of nginx access control

About Nginx, a high-performance, lightweight web ...

CSS to achieve the image hovering mouse folding effect

CSS to achieve the image hovering mouse folding e...

MySQL insert json problem

MySQL 5.7.8 and later began to support a native J...

Explanation of building graph database neo4j in Linux environment

Neo4j (one of the Nosql) is a high-performance gr...

CSS to achieve Skeleton Screen effect

When loading network data, in order to improve th...

MySql Group By implements grouping of multiple fields

In daily development tasks, we often use MYSQL...

js to achieve simple magnifying glass effects

This article example shares the specific code of ...

Detailed explanation of Vue project packaging

Table of contents 1. Related configuration Case 1...

How to monitor array changes in Vue

Table of contents Preface Source code Where do I ...

Alpine Docker image font problem solving operations

1. Run fonts, open the font folder, and find the ...

Detailed explanation of how to use Teleport, a built-in component of Vue3

Table of contents 1. Teleport usage 2. Complete t...

MySQL configuration master-slave server (one master and multiple slaves)

Table of contents Ideas Host Configuration Modify...