微信公众号原生H5订阅消息开发
简单说一下流程:
在页面带参数跳转到 https://mp.weixin.qq.com/mp/subscribemsg ,然后用户授权确认或者取消以后,会返回参数里面 redirect_url 的地址,并且带上openid 等相应参数,在前端的页面判断链接里面携带了相关参数后就告诉后端,用户订阅消息的结果,最后由后端触发订阅消息的发送,后端调用 https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=ACCESS_TOKEN 去发送订阅消息。
下面看看代码:
1.让用户授权订阅消息:
————————————————
let redirect_url = encodeURIComponent(location.href);
let appId = '你的appid'
let scene = '场景值,可以填id或者其它值'
let template_id = '订阅消息的模板id'
const href = `https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=${appId}&scene=${id}&template_id=${template_id}&redirect_url=${redirect_url}#wechat_redirect`;
location.href = href;
2.在页面接收用户授权订阅消息的回调信息
onLoad: function(options) {
const { openid, action } = options;
if (action == 'confirm') {
const { class_id } = JSON.parse(uni.getStorageSync('courseInfo') || '{}');
//subscribe() 是封装的接口请求,用户告诉后端授权结果
subscribe({ class_id: class_id }).then(res => {
if (res.data.code == 0) {
uni.navigateTo({
url: '/pages/classRoom/courseList/courseList?id=' + class_id
});
} else {
uni.showToast({
title: res.data.msg,
icon: 'none'
});
}
});
}
}
本文由 我爱PHP169 作者:admin 发表,其版权均为 我爱PHP169 所有,文章内容系作者个人观点,不代表 我爱PHP169 对观点赞同或支持。如需转载,请注明文章来源。