在小程序的某些场景下,为了能够更好的给用户提供服务,有时需要用户对小程序的推送消息进行订阅,这样小程序才能在适当的时候给用户进行推送
微信小程序的订阅消息也有一定的限制,比如:
1.用户一次性最多只能订阅3条信息
2.用户必须主动点击按钮,才能触发订阅消息
3.用户每订阅一次,才能推送一次
4.若用户选择了“总是保持以上选择”后,将不会再有消息订阅的提示
下面是订阅消息的代码实现
首先,为了用户能够顺利的进入授权流程,我们得先检测用户是否对此小程序开启了授权
//检测用户是否开启授权权限
getSetting() {
const _this = this
uni.getSetting({
withSubscriptions: true,
success(res) {
if (!res.subscriptionsSetting.mainSwitch) {
//后台封禁了
//引导用户打开权限
uni.showModal({
title: '请在通知管理中开启接收通知的权限',
success(res) {
if (res.confirm) {
uni.openSetting({})
} else if (res.cancel) {
uni.showToast({
title: '您尚未开启接收通知的权限',
icon: 'none'
})
}
},
})
} else { //未封禁,则触发订阅消息
_this.subsribe()
}
},
})
},
//将模板消息id三个分为一组,data为所有的模板消息id组成的数组
splitArray(data) {
let result = [];
for (let i = 0; i < data.length; i += 3) {
result.push(data.slice(i, i + 3));
}
this.templateIdArray = result
},
//订阅消息
subsribe() {
const _this = this
uni.requestSubscribeMessage({
tmplIds: _this.templateIdArray[0], //前三个模板消息
success(res) {
console.log(_this.templateIdArray[0])
console.log(res)
uni.showModal({
content: '确认是否下单',
showCancel: true,
success: res => {
if (res.confirm) {
uni.requestSubscribeMessage({
tmplIds: _this.templateIdArray[1],//后三个模板消息
success(res) {
_this.createOrder() //用户订阅完消息后,需要触发的函数
}
})
}else{
return
}
}
});
}
})
},
效果如图所示