How to send template message for WeChat Mini-program?
To fully take advantage of WeChat Mini-program, you don’t want to miss out the opportunity to send a template message. It triggers WeChat’s notification and sends your user a hit of dopamine.
What is a template message?
Instead of letting developers to send whatever to users, WeChat has 138 templates with interchangeable keywords to have a more unified experience for the end-users.
Prerequisite
A mini-program account’s AppID and AppSecret.
Example Code
Mini-program code — Need WeChat Devtool to emulate
Backend Code — Node.js and Express.js
Reverse Engineer
Let’s start with the end result.
Happy Ending: User receives your message in the “Service Message” box
To do that, you will have to make a POST request to
https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN
Along with the required parameters below:
https://developers.weixin.qq.com/miniprogram/en/dev/api/notice.html#send-template-message
Now it’s just the matter of putting the puzzle together.
How to get Access Token?
3 options:
- Good old fashion GET request to https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
- Use a library: wechat-jssdk
const { Wechat, MiniProgram } = require('wechat-jssdk');
const wechatConfig = {
"appId": process.env.APP_ID,
"appSecret": process.env.APP_SECRET,
"miniProgram": {
"appId": process.env.APP_ID,
"appSecret": process.env.APP_SECRET,
}
};
const wx = new Wechat(wechatConfig);
const { access_token } = await wx.jssdk.getAccessToken();
- The short term and lazy way: put in your appID and appSecret here
How to get user’s OpenID?
In your Mini-program code, do something like
onLaunch: function () {
const self = this;
// Login
wx.login({
success: res => {
wx.request({
url: `http://your-backend-server.com/login?code=${res.code}`,
header: {
'content-type': 'application/json'
},
success(res) {
const { session_key, openid } = res.data;
// Save user's openid globally for later use
self.globalData.openid = openid;
}
})
}
})
}
In your backend code, send a GET request to
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
JSCODE being the code you got from the Mini-program
OR you could utilize the library again, and do something like
const session = await wx.miniProgram.getSession(req.query.code);
Then you should get both the session_key and openid
How to get the template ID and template data?
After logging in at https://mp.weixin.qq.com, go to the template message tab on the left and click the add button on the right. (not sure why this dashboard is only half translated, but if you’re having trouble getting around, google translate)
After clicking add, you will see a list of templates
After selecting a template by clicking 选用, you will be able to select the keywords that you want to include
After submitting by pressing the green button, you will see the list of template you created, copy the template ID from there
So what’s the data I am supposed to pass?
"data": {
keyword1: {
value: 'Product Name',
},
keyword2: {
value: 'Product Description',
},
keyword3: {
value: '10/10/2018',
},
keyword4: {
value: '10/10/2018',
}
Based on the keywords you chose, the value of keywords will be inserted based on the order you arranged when creating the template.
How to get the form ID?
This might make a lot of sense, but WeChat requires a form ID that’s only generated by the form component in mini-program. Or you can use a prepay_id from WeChat payment.
In your wxml file of the mini-program code, have a simple button to test.
Note* include the report-submit flag to form tag for it to return form id
<form bindsubmit="formSubmit" report-submit>
<button form-type="submit">Submit</button>
</form>
In the js file of the mini-program code, handle the submit event like this
formSubmit(e) {
const { formId } = e.detail;
wx.request({
// Use your local IP address if you're just testing
url: `http://your-backend-server.com/send-message`,
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
form_id: formId,
// Use the openid saved earlier
touser: app.globalData.openid
},
success(res) {
// Message should be sent, check your messages
}
});
}
Getting the message
Once you hit the test button, you will feel a nice sensation of vibration from your phone and the little red notification badge pops up.
That means you have succeeded.
Giant Caveats
Mini-program sandbox account doesn’t work for template message
The message can only be sent to the same user who generated the form_id or prepay_id.
One form_id is valid for seven days and good for one message.
One prepay_id is also valid for seven days and good for 3 messages.
So you might wonder, but what if I have an event booking system, I want to send messages to a group of users when the event is neared.
There’s a workaround where you can save the form_id in your database when a user interacts with a button on the mini-program.
When you send a group message, then you fetch the users associated with the form_id(s).
Then you will have to keep track of the expiration date and usage of the form_id(s).
Conclusion
If you’re looking to up your software development game, I have put together a Free WeChat Glossary for you to digest.
Perfect article! David, Can I ask you about sending message from Django to weChat users?