本文主要介紹下 微信小程式 訂閱消息 功能的使用及一些注意事項
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裡面的資料對應的就是選用模闆裡面字段設定的名稱
4. 上面都沒有問題,最後下發消息後微信就可以收到消息啦!如下:
好啦,訂閱消息功能 就ok啦!