1、订阅消息的实现过程
微信订阅消息实现主要有两大块内容需要理解,第一,发送的消息内容需要预先定义一个模板,模板的数据可以有云函数发送,其中发送的内容可以由前端传入云函数,那什么时候发送呢?这就涉及到触发,有时间触发,到了某个时间点就发送给已订阅的用户,另一种是事件触发,当点击某个按钮时,就会发送这条订阅消息给已订阅的用户;第二,内容接收方需要订阅消息模板,订阅一次就可以接收一次这个模板的消息。
2、云函数端定义要发送的内容
touser表示要发给谁(前提是那个用户已经订阅了这个模板) data表示发哪些内容 templateId表示发模板
if(event.opr=='test'){
try{
const {OPENID} = cloud.getWXContext();
const result = await cloud.openapi.subscribeMessage.send({
touser:OPENID,
page:'pages/index/index',
data:{
//这些参数都会在模板详情那有,这些参数不能弄错,一旦弄错就发送不了
character_string1:{
value:"ff"
},
thing5:{
value:"测试"
},
date2:{
value:"2020-2-1"
},
number3:{
value:177
}
},
templateId:'***',
miniprogramState: 'developer'
})
console.log(result)
return result
}catch(err){
console.log(err)
return err
}
}
3、用户订阅某个模板
subscribeTask(){
wx.requestSubscribeMessage({
// 传入订阅消息的模板id,模板 id 可在小程序管理后台申请
tmplIds: [newTasktmplId],
success:res => {
if (res[newTasktmplId] === 'accept'){
console.log("申请订阅成功")
wx.cloud.callFunction({
name: 'subscribe',
data: {
opr: "newTasksub",
openid:this.data.openid,
num:this.data.newtasknum,
templateId: newTasktmplId,
},
}) .then(res => {
console.log("res ",res)
wx.showToast({
title: '订阅成功',
icon: 'success',
duration: 2000,
});
}) .catch(() => {
console.log("res 11 ",res)
wx.showToast({
title: '订阅失败',
icon: 'success',
duration: 2000,
})
})
}
}
});
},