1,创建个js 文件 subscribeMessage.js
// 订阅消息通知授权方法
export const subscribeMessage = (val)=> {//需要订阅的消息模板,在微信公众平台手动配置获取模板IDlet message = val; // 模板id//如果总是拒绝(subscriptionsSetting,2.10.1库才支持)if(versionCompare('2.10.1')){wx.getSetting({withSubscriptions: true,//是否同时获取用户订阅消息的订阅状态,默认不获取success: (res)=> {console.log(res)if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&res.subscriptionsSetting.itemSettings[message] == "reject"){//打开设置去设置openConfirm('检测到您没打开推送权限,是否去设置打开?');}else if(res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&res.subscriptionsSetting.itemSettings[message] == "accept") { // 已有授权过console.log('已有订阅授权过')} else {wx.requestSubscribeMessage({tmplIds: [message],success: (res)=> {if (res[message] == 'accept'){//用户允许}},fail: (res)=> { console.info(res) },})}}})}else if(versionCompare('2.4.4')){wx.requestSubscribeMessage({tmplIds: [message],success: (res)=> {if (res[message] == 'accept'){//用户允许}},fail: (res)=> { console.info(res) },})}//打开设置function openConfirm(message) {wx.showModal({content: message,confirmText: "确认",cancelText: "取消",success: (res) => {//点击“确认”时打开设置页面if (res.confirm) {wx.openSetting({success: (res) => {console.log(res.authSetting)},fail: (error) => {console.log(error)}})} else {console.log('用户点击取消')}}});}//基础库版本比较function versionCompare(v) {const version = wx.getSystemInfoSync().SDKVersionif (compareVersion(version, v) >= 0) {return true} else {return false}}function compareVersion (v1, v2) {v1 = v1.split('.')v2 = v2.split('.')var len = Math.max(v1.length, v2.length)while (v1.length < len) {v1.push('0')}while (v2.length < len) {v2.push('0')}for (var i = 0; i < len; i++) {var num1 = parseInt(v1[i])var num2 = parseInt(v2[i])if (num1 > num2) {return 1} else if (num1 < num2) {return -1}}return 0}
}
2, 页面点击事件里面使用
import {subscribeMessage} from "../../../utils/subscribeMessage.js"; // 订阅 公共方法data: {subscribeMessage: subscribeMessage // 订阅消息授权},toWhere(e) {this.data.subscribeMessage('xxxx'); // 订阅授权方法 入参是模板id}