小程序消息订阅-uniapp实现
// 订阅消息授权async function requestSubscribeMessage() {try {const res = await uni.requestSubscribeMessage({tmplIds: ['模板ID1', '模板ID2'], // 需要订阅的模板ID列表success: (res) => {console.log('订阅成功', res);// 处理订阅成功的逻辑},fail: (err) => {console.log('订阅失败', err);// 处理订阅失败的逻辑}});return res;} catch (error) {console.log('订阅消息失败', error);return false;}}
// 后端发送订阅消息示例(Node.js)const axios = require('axios');async function sendSubscribeMessage(openid, templateId, data, page) {try {// 获取access_tokenconst tokenRes = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`);const accessToken = tokenRes.data.access_token;// 发送订阅消息const sendRes = await axios.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`,{touser: openid, // 用户openidtemplate_id: templateId, // 模板IDpage: page, // 点击消息跳转的页面data: data // 模板数据});return sendRes.data;} catch (error) {console.log('发送订阅消息失败', error);return false;}}
<viewclass="container"><button @click="checkAndSubscribe"type="primary">订阅消息</button></view>
// 检查并订阅消息async checkAndSubscribe() {try {// 1. 尝试请求订阅const subscribeRes = await this.requestSubscribe();// 2. 根据订阅结果处理if (subscribeRes) {console.log('订阅成功');} else {// 3. 订阅失败,检查权限状态await this.checkPermissionStatus();}} catch (error) {console.log('订阅流程出错', error);uni.showToast({title: '操作失败,请重试',icon: 'none'});}},// 请求订阅消息async requestSubscribe() {return new Promise((resolve, reject) => {uni.requestSubscribeMessage({tmplIds: [this.templateId],success: (res) => {console.log('订阅结果', res);if (res[this.templateId] === 'accept') {uni.showToast({title: '订阅成功',icon: 'success'});resolve(true);} else if (res[this.templateId] === 'reject') {console.log('用户拒绝订阅');resolve(false);} else if (res[this.templateId] === 'ban') {console.log('用户被禁止订阅');uni.showToast({title: '您已被禁止订阅消息',icon: 'none'});resolve(false);} else {console.log('订阅状态未知', res[this.templateId]);resolve(false);}},fail: (err) => {console.log('请求订阅失败', err);resolve(false);}});});},// 检查权限状态async checkPermissionStatus() {return new Promise((resolve) => {uni.getSetting({success: (res) => {console.log('当前权限设置', res.authSetting);// 检查订阅消息权限const hasSubscribePermission = res.authSetting['scope.subscribeMessage'];if (hasSubscribePermission === false) {// 权限被拒绝,引导用户去设置页面this.guideToSetting();} else {// 权限未设置或已允许,可能是其他原因导致订阅失败uni.showToast({title: '订阅失败,请稍后重试',icon: 'none'});}resolve();},fail: (err) => {console.log('获取设置失败', err);resolve();}});});},// 引导用户去设置页面guideToSetting() {uni.showModal({title: '需要权限',content: `您需要开启${this.templateTitle}的订阅权限才能接收相关通知,是否前往设置页面开启?`,confirmText: '去设置',cancelText: '暂不开启',success: (modalRes) => {if (modalRes.confirm) {this.openSetting();}}});},// 打开设置页面openSetting() {uni.openSetting({success: (settingRes) => {console.log('设置页面操作结果', settingRes.authSetting);// 检查用户是否开启了订阅消息权限if (settingRes.authSetting['scope.subscribeMessage']) {uni.showToast({title: '权限开启成功',icon: 'success'});// 可以再次尝试订阅this.requestSubscribe();} else {uni.showToast({title: '权限未开启',icon: 'none'});}},fail: (err) => {console.log('打开设置页面失败', err);uni.showToast({title: '打开设置页面失败',icon: 'none'});}});}
代码说明:
1. checkAndSubscribe方法:整合了权限检查、订阅请求和引导设置的完整流程
2. requestSubscribe方法:封装了订阅消息的请求逻辑,返回订阅结果
3. checkPermissionStatus 方法:获取用户当前的权限设置状态
4. guideToSetting 方法:当权限被拒绝时,引导用户去设置页面
5. openSetting方法:打开小程序设置页面,并处理用户操作结果
夜雨聆风