Front-end encapsulation of WeChat applet message subscription function (encapsulated and used directly)

export function subscription() {
	wx.getSetting({
		withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
		success: function(res) {
			console.log(res, '调起授权界面弹窗');
			// 调起授权界面弹窗
			if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
				// 每次执到这都会拉起授权弹窗
				wx.requestSubscribeMessage({ // 调起消息订阅界面
					tmplIds: ['模板1的id', '模板2的id'],
					success(res) {
						console.log(res, '订阅消息 成功 ');
					},
					fail(err) {
						console.log(err, "订阅消息 失败 ");
					},
				})
			} else {
				uni.showToast({
					title: '请到小程序设置-订阅消息-接收通知中开启订阅消息',
					icon: 'none',
					duration: 8000
				});
			}
		},
		fail: function(error) {
			console.log(error);
		}
	})
}

When using it, just call the subscribeio() method directly at the place you want to call

Note: The template id needs to be logged into the WeChat public platform, and can be checked in the subscription news, my template

Guess you like

Origin blog.csdn.net/honeymoon_/article/details/129611771