選擇或創建訂閱消息模板
登錄到微信小程序里面找到功能->訂閱消息。可以在公共模板庫里選擇需要的模板,如果沒有找到自己需要的也可以自己創建然后等待審核、
選擇完模板查看詳情會得到模板ID,以及發送推送時需要的字段、
小程序發送訂閱的請求
需要用到上一步獲取的模板Id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 小程序 <Text className= 'rights-buy' onClick={ this .messageSubmit}> 入駐申請 </Text> // 入駐申請消息訂閱 messageSubmit = () => { Taro.requestSubscribeMessage({ tmplIds: [ 'SuGMwqyYY9cocuP-LxfElcM3a7ITaF34lKNux6EaE9' ], success: (res) => { // 調用服務端接口,在數據庫寫入一條訂閱記錄 // this.subscribeDeal() } }) } |
服務端發起推送
推送一般有兩種
- 手動觸發、
- 還有就是訂閱消息后,達到某個條件自動觸發推送、
對于第一種情況,就直接調用微信的推送接口就好了。第二中情況稍微麻煩一點,可以加一個定時的任務,或者使用相關的隊列庫、等條件符合了再觸發、
需要注意的地方
- 發送推送的時候需要用戶的openid,以及模板id。具體的推送內容字段,在第一步模板詳情里面可以查看、
- 調用微信推送的接口的時候需要access_token,最好緩存一下,頻繁調用會有失效的問題、
獲取access_token并緩存
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
|
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) } }) } |
向微信發送推送請求
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
35
|
async sendSubscribeMsg (openid) { let requestData = { "touser" : `${openid}`, "template_id" : "SuGMwqyYY9cocuP-LxfElcM3a7ITaF34lKNux6EaE9" , "page" : `/pages/certification/index`, "data" : { "phrase2" : { "value" : `審核通過` }, "thing3" : { "value" : `您的申請已經審核通過` } } } const { host } = this .app.config.idolWxAConfig; // 獲取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( '========推送成功========' ) // TODO } else { console.log( '========推送失敗========' ) // TODO } } |
到此這篇關于Nodejs 微信小程序消息推送的實現的文章就介紹到這了,更多相關Nodejs小程序消息推送內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/6919404252804677645