1、首先获取小程序用户登录openId
// 获取openid
async opid() {
let self = this
wx.login({
success(res) {
if (res.code) {
// wxappid wxsecret为小程序的appId和secretKey,登录小程序后台可查看
wx.request({
url: `https://api.weixin.qq.com/sns/jscode2session?appid=${self.$wxappid}&secret=${self.$wxsecret}&js_code=${res.code}&grant_type=authorization_code`,
success(data) {
self.useropenId = data.data.openid
self.pushmsg.touser = self.useropenid
}
})
} else {
console.log('获取失败!' + res.errMsg)
}
}
})
}
2、获取对应推送消息模板的token
getToken() {
let self = this
wx.requestSubscribeMessage({
tmplIds: [id],//此处的id替换你要发送订阅的模板id,可在小程序后台新建模板中获取
success(res) {
wx.request({
url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${self.$wxappid}&secret=${self.$wxsecret}`,
data: {},
success: function(res) {
self.mytoken = res.data.access_token
}
})
},
fail: function(res) {
}
})
}
3、最后调用消息推送方法
// 通知
notice() {
let self = this
//下方的thing1,thing2和其他,对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段,要和上面的字段一样),需要更改成你自己的
const pushmsg = {
"touser": '要发送用户的openId',
"template_id": "对应的模板id(去微信公众平台中的订阅里面找,选择对应模板,然后复制进来)",
"data": {
"thing1": {
"value": "审核中"
},
"thing2": {
"value": "预约信息"
},
"time3": {
"value": "2021年4月14日"
},
"thing8": {
"value": "2021年4月15日"
},
"phone_number5": {
"value": "185xxxx2671"
}
}
}
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + self.mytoken,
data: JSON.stringify(pushmsg),
method: 'POST',
success: function(res) {
console.log(res)
}
})
}