Implement notifications for WeChat mini programs with Node.js

  1. Request subscription permission
  2. Obtain User’s openid
  3. Send notifications from Node.js server
    1. Get access_token
    2. Send the notification

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
2
3
4
5
6
7
8
9
wx.requestSubscribeMessage({
tmplIds: ["YOUR_TEMPLATE_ID"], // Replace with your template ID
success(res) {
console.log("Subscription successful:", res);
},
fail(err) {
console.error("Subscription failed:", err);
},
});

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.login API on the client-side to get a code.
  • Send this code to your Node.js server, where you exchange it for the openid and session_key using WeChat’s API.

Example of getting openid:

1
2
3
4
5
6
7
const axios = require("axios");

async function getOpenId(appId, appSecret, code) {
const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
const response = await axios.get(url);
return response.data.openid; // This is the user's openid
}

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
2
3
4
5
async function getAccessToken(appId, appSecret) {
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
const response = await axios.get(url);
return response.data.access_token;
}

Send the notification

With the access_token and openid, you can send a subscription message:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
async function sendNotification(openid, templateId, formId, data, page) {
const accessToken = await getAccessToken("YOUR_APP_ID", "YOUR_APP_SECRET");
const url = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`;

const payload = {
touser: openid, // User's openid
template_id: templateId, // Template ID from WeChat
page: page, // Optional: Page to redirect the user
data: data, // The content of your message
};

const response = await axios.post(url, payload);
console.log("Notification response:", response.data);
if (response.data.errmsg === "ok") {
console.log("successful");
} else {
console.log("failed");
}
}

// Example usage
const openid = "USER_OPENID"; // Retrieved openid
const templateId = "YOUR_TEMPLATE_ID";
const data = {
thing1: {
value: "Your report is ready",
},
date2: {
value: "2024-08-14",
},
};
const page = "pages/report/index";

sendNotification(openid, templateId, null, 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.