文檔:小程序訂閱消息(用戶通過彈窗訂閱)開發(fā)指南
步驟一:獲取模板 ID
在微信公眾平臺(https://mp.weixin.qq.com)手動配置獲取模板 ID
步驟二:小程序端獲取參數(shù)
2.1、獲取消息下發(fā)權(quán)限
文檔:一次性訂閱消息、長期訂閱消息
示例代碼
const res = await wx.requestSubscribeMessage({
tmplIds: ['']
})
console.log(res)
這里需要注意一個坑,如果用戶未授權(quán),需要引導用戶打開設(shè)置手動設(shè)置
handleRequestSubscribeMessage(e) {
let templeteId = 'zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE'
// 先檢查授權(quán)情況,如未授權(quán)需要提醒用戶手動設(shè)置權(quán)限
wx.getSetting({
withSubscriptions: true,
success(res) {
console.log(res.subscriptionsSetting);
// res.subscriptionsSetting = {
// mainSwitch: true, // 訂閱消息總開關(guān)
// itemSettings: { // 每一項開關(guān)
// SYS_MSG_TYPE_INTERACTIVE: 'accept', // 小游戲系統(tǒng)訂閱消息
// SYS_MSG_TYPE_RANK: 'accept'
// zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'reject', // 普通一次性訂閱消息
// ke_OZC_66gZxALLcsuI7ilCJSP2OJ2vWo2ooUPpkWrw: 'ban',
// }
// }
// 模板授權(quán)
if ("accept" == res.subscriptionsSetting.itemSettings[templeteId]) {
// 用戶已授權(quán)
} else {
wx.showModal({
title: "授權(quán)提示",
content: "請允許接收小程序消息",
success: function (res) {
if (res.confirm) {
console.log("用戶點擊確定");
wx.openSetting({
withSubscriptions: true, // 是否同時獲取用戶訂閱消息的訂閱狀態(tài),默認不獲取
success(res) {
console.log(res.authSetting);
// res.authSetting = {
// "scope.userInfo": true,
// "scope.userLocation": true
// }
},
});
} else if (res.cancel) {
console.log("用戶點擊取消");
}
},
});
}
},
});
// 請求用戶授權(quán)
wx.requestSubscribeMessage({
tmplIds: [templeteId],
success(res) {
console.log(res);
// 授權(quán)成功
},
});
}
2.2、獲取登錄憑證(code)
文檔:接口獲取登錄憑證(code)
const loginRes = await wx.login()
if(loginRes.code){
console.log(loginRes.code)
}
步驟三:后端調(diào)用接口下發(fā)訂閱消息
3.1、獲取OPENID
使用 小程序端獲取的登錄憑證(code)通過服務(wù)端接口獲取openid
文檔:小程序登錄
請求數(shù)據(jù)示例文章來源:http://www.zghlxwxcb.cn/news/detail-824005.html
GET https://api.weixin.qq.com/sns/jscode2session?
appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
返回數(shù)據(jù)示例
{
"openid":"xxxxxx",
"session_key":"xxxxx"
}
注意:這里和文檔不一樣,接口調(diào)用成功時,不會返回
unionid
、errcode
、errmsg
3.2、獲取ACCESS_TOKEN
文檔:獲取接口調(diào)用憑據(jù)
請求數(shù)據(jù)示例
GET https://api.weixin.qq.com/cgi-bin/token?
grant_type=client_credential&appid=APPID&secret=APPSECRET
返回數(shù)據(jù)示例
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200
}
3.3、下發(fā)訂閱消息
文檔:一次性訂閱消息、長期訂閱消息,服務(wù)端接口
請求數(shù)據(jù)示例
POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
{
"touser": "OPENID",
"template_id": "TEMPLATE_ID",
"page": "index",
"miniprogram_state":"developer",
"lang":"zh_CN",
"data": {
"number01": {
"value": "339208499"
},
"date01": {
"value": "2015年01月05日"
},
"site01": {
"value": "TIT創(chuàng)意園"
} ,
"site02": {
"value": "廣州市新港中路397號"
}
}
}
返回數(shù)據(jù)文章來源地址http://www.zghlxwxcb.cn/news/detail-824005.html
{
"errcode":0,
"errmsg":"ok"
}
到了這里,關(guān)于微信小程序:發(fā)送小程序訂閱消息的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!