本文主要介绍下 微信小程序 订阅消息 功能的使用及一些注意事项
1. 首先,需要到小程序后台去添加消息模板
添加模板之后就是使用啦,下发消息是需要用户授权的,来看下API
2. wx.requestSubscribeMessage(Object object) 调起客户端小程序订阅消息界面,如下图所示
dingyue: function (tmplId){
let that = this
wx.getSetting({
withSubscriptions: true,
success(res) {
console.log(res)
if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
if (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings[tmplId]) {
let item = res.subscriptionsSetting.itemSettings[tmplId]
if (item == "reject") {
that.dingyueComfirm(tmplId)
} else if (item == "accept") {
console.log('提示:您已经开启订阅消息')
} else if (item == "ban") {
console.log('提示:您已经被后台封禁')
}
}else{
that.dingyueComfirm(tmplId)
}
} else {
that.dingyueComfirm(tmplId)
}
}
})
},
dingyueComfirm: function (tmplId){
wx.showModal({
title: '订阅消息',
content: '订阅后,有消息会通过微信通知您',
success: (res) => {
if (res.confirm) {
wx.requestSubscribeMessage({
tmplIds: [tmplId],
success: (res) => {
if (res[tmplId] === 'accept') {
wx.showToast({
title: '订阅成功!',
duration: 1000,
success(data) {
//成功
console.error(data);
}
})
} else if (res[tmplId] == "reject") {
//引导用户,手动引导用户点击按钮,去设置页开启,## Modals是自定义组件
wx.showModal({
title: '订阅消息',
content: '您当前拒绝接受消息通知,是否去开启',
confirmText: '开启授权',
confirmColor: '#345391',
cancelText: '仍然拒绝',
cancelColor: '#999999',
success: res => {
this.globalData.isUpload = true
wx.openSetting({
success(res) {
console.log(res.authSetting)
// res.authSetting = {
// "scope.userInfo": true,
// "scope.userLocation": true
// }
},
fail(err) {
//失败
console.error(err);
}
})
}
})
}
},
fail(err) {
//失败
console.error(err);
}
})
}
}
})
}
首先通过调用wx.getSetting() 获取用户授权列表的授权状态 ,如果拒绝可以申请用户授权,也可以通过wx.openSetting()指引用户去设置页更改设置
注:如果用户没有勾选红框里的内容,那么下次还是需要用户授权才可以下发消息的。
如果用户允许了,那么就可以给用户下发消息了
3. subscribeMessage.send 发送订阅消息
参数都很简单,文档也很清晰。也有示例
data里面的数据对应的就是选用模板里面字段设置的名称