Notifications can be an essential part of your mini program if you need to inform users with the latest news. To implement notifications on the server side using Node.js, you will typically use WeChat’s subscription message service. This is a brief guide to achieve this.
Request subscription permission
First of all, we need to request the user’s permission to receive subscription messages on the client side:
1 | wx.requestSubscribeMessage({ |
In the code above, you have to put your own template ID in the tmplIds array. To get this Id, you need to find the one which is most suitable for your app in the official template list.
The user’s preference will be saved on WeChat servers, and it will be used to determine the notifications should be sent to this user or not.
Obtain User’s openid
This openid uniquely identifies a user within your mini program.
- Use the
wx.loginAPI on the client-side to get acode. - Send this
codeto your Node.js server, where you exchange it for theopenidandsession_keyusing WeChat’s API.
Example of getting openid:
1 | const axios = require("axios"); |
Send notifications from Node.js server
Once the user has subscribed and you have collected their openid, you can send notifications using WeChat’s API.
Get access_token
You need an access_token to authenticate your requests to WeChat’s servers. This token should be refreshed periodically and also be cached for better performance.
1 | async function getAccessToken(appId, appSecret) { |
Send the notification
With the access_token and openid, you can send a subscription message:
1 | async function sendNotification(openid, templateId, formId, data, page) { |
When the notification is successfully delivered, it arrives in the WeChat Mini Program and your mini program will open if the user taps on it.