uniapp中h5网页微信公众号授权
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:292
uniapp微信网页授权
- uniapp中h5网页微信公众号授权
- 主要代码
- 获取code返回的code截取代码
uniapp中h5网页微信公众号授权
微信官方文档–>网页授权
uniapp中h5网页微信公众号授权步骤:
1.采用用户授权获取code
2.把code传给后端后端获取openid 以及是否关注公众号判断
3.没有关注跳转至关注公众号页面
主要代码
//判断用户是否是微信环境
if (isWechat()) {
let code = getUrlParam("code"); //是否存在code 截取code代码 授权会返回code需要截取链接中code
let local = window.location.href;
if (code == null || code === "") {
//不存在就打开上面的地址进行授权
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=url&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
//appid填写你的appid redirect_uri填写请求成功后回调地址
} else {
that.code = code;
//把code传给后端判断用户是否关注相对应的公众号
uni.request({
url: 'url',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
code: that.code
},
method: 'GET',
success: (res) => {
//201没有关注公众号 跳转关注页面
if (res.data == 201) {
window.location.href =
`https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=wechatbiz#wechat_redirect`;
//_biz的获取通过登录微信公众平台 在头像那里右击查看源码 找到 uin: "658565",uin_base64: "",_biz的值等于uin_base64就可以了
} else { //关注了可以进行下一步
uni.request({
url: 'url',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'GET',
success: (ti) => {
}
})
}
},
})
}
}else{
uni.showModal({
title:'请在微信打开',
content:'请在微信打开本网页'
})
}
获取code返回的code截取代码
// 判断公众号截取code
const getUrlParam = (name) => {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}