Start by choosing the desired message template from the WeChat public platform.
Invoking the subscription on the client
Use wx.requestSubscribeMessage to prompt the user for permission. Pass the template ID(s) in side tmplIds.
const templateIds = ['7UezzOrfJg_NIYdE1p*******']
wx.requestSubscribeMessage({
tmplIds: templateIds,
success(resp) {
console.log(resp)
wx.getSetting({
success(settingsResp) {
console.log(settingsResp.authSetting)
}
})
}
})
Server-side delivery
Obtaining an access token
Call the token endpoint with grant_type, appid, and secret.
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&secret=
Response example:
{
"access_token": "82_F1FSYNxipQKw2TOr0_uMpLDQR9Z9Zf9FkNPslS4q9Dz9KqwYdT-aSBypJz6ZVZ8x_FlbPQCFpRY-Xwio5GBtQRChp8pq21k6JaCrdrLP75DoCGzDNFO4g0E8pwYHDZjAGADZV",
"expires_in": 7200
}
Dispatching the subscription message
Send a POST to the subscribe/message endpoint, appending the access token as a query parameter. The request body contains the receiver's openid, page path, template ID, and the message payload.
Payload structure:
{
"template_id": "ij1o1NjVjwqFmZ1ftWoPMer*****",
"page": "pages/index/home",
"touser": "oWvGc63WN****",
"data": {
"thing6": { "value": "Smoke Detector" },
"thing7": { "value": "Xiao Ming" },
"phone_number8": { "value": "18771556**" },
"thing9": { "value": "Living Room" },
"thing10": { "value": "Urgent: fire detected in living room" }
},
"miniprogram_state": "developer",
"lang": "zh_CN"
}
optional miniprogram_state values: developer (dev), trial (beta), or formal (production). Defaults to formal. Supported language codes: zh_CN, en_US, zh_HK, zh_TW.
The endpoint:
POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=82_F1FSYNxipQKw2TOr0_uMpLDQR9Z9Zf9FkNPslS4q9Dz9KqwYdT-aSBypJz6ZVZ8x_FlbPQCFpRY-Xwio5GBtQRChp8pq21k6JaCrdrLP75DoCGzDNFO4g0E8pwYHDZjAGADZV
The payload reflects the template key mapping and24-hour delivery constraints.
Final user-facing notification appears according to the template layout.