小程序模板消息即将被废弃掉,于是有了新接口wx.requestSubscribeMessage
步骤:
1、获取用户openid 、access_token(前面文章提到过)
2、获取模板 ID
3、获取下发权限(api)
4、发送订阅消息 (api)
模板id
小程序代码:
获取下发权限:
// login.js
requestMsg(){
return new Promise((resolve, reject) => {
wx.requestSubscribeMessage({
tmplIds: ["MUtLwsw0xCndRULTgNHiXwGDyHJ-ZwAFL-b3kALcl0c"],
success: (res) => {
if (res['MUtLwsw0xCndRULTgNHiXwGDyHJ-ZwAFL-b3kALcl0c'] === 'accept'){
wx.showToast({
title: '订阅OK!',
duration: 1000,
success(data) {
//成功
resolve()
}
})
}
},
fail(err) {
//失败
console.error(err);
reject()
}
})
})
}
// index.wxml
<button class="v-btn mt40" bindtap="sendMsg">发生订阅消息</button>
// index.js
// 点击发生订阅
sendMsg:function(e){
wx.request({
url: 'https://cff.mynatapp.cc/wxXcx/sendMessage',
method: 'POST',
data: { },
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log(res)
}
})
}
nodejs(koa2)代码:
发送订阅消息:
// index.js
const router = require('koa-router')()
const request = require('superagent')
let AppID = 'xxxxx'
let AppSecret = 'xxxxx'
let access_token = 'xxxxx'
let openid = 'xxxxx'
// 点击发生订阅消息
router.post('/wxXcx/sendMessage', async (ctx, next) => {
let requestData ={
"touser": openid,
"template_id": "MUtLwsw0xCndRULTgNHiXwGDyHJ-ZwAFL-b3kALcl0c",
"page": "index",
"data": {
"phrase1": {
"value": "王小二"
},
"date5": {
"value": "2019年10月1日 15:01"
},
"phrase4": {
"value": "王老师"
},
"thing2": {
"value": "ps入门到精通"
},
"character_string6": {
"value": "1/10"
}
}
}
// 2、发送模板消息
let res = await request
.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`)
.send(requestData)
.set('Accept', 'application/json')
console.log(res)
ctx.body = {
code: '200',
data: null,
msg: '操作成功'
}
})