uniapp中h5網頁微信公衆号授權
發表時(shí)間:2020-10-19
發布人(rén):融晨科技
浏覽次數:297
uniapp微信網頁授權
- uniapp中h5網頁微信公衆号授權
- 主要(yào / yāo)代碼
- 獲取code返回的(de)code截取代碼
uniapp中h5網頁微信公衆号授權
微信官方文檔–>網頁授權
uniapp中h5網頁微信公衆号授權步驟:
1.采用用戶授權獲取code
2.把code傳給後端後端獲取openid 以(yǐ)及是(shì)否關注公衆号判斷
3.沒有關注跳轉至關注公衆号頁面
主要(yào / yāo)代碼
//判斷用戶是(shì)否是(shì)微信環境
if (isWechat()) {
let code = getUrlParam("code"); //是(shì)否存在(zài)code 截取code代碼 授權會返回code需要(yào / yāo)截取鏈接中code
let local = window.location.href;
if (code == null || code === "") {
//不(bù)存在(zài)就(jiù)打開上(shàng)面的(de)地(dì / de)址進行授權
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填寫你的(de)appid redirect_uri填寫請求成功後回調地(dì / de)址
} else {
that.code = code;
//把code傳給後端判斷用戶是(shì)否關注相對應的(de)公衆号
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的(de)獲取通過登錄微信公衆平台 在(zài)頭像那裏右擊查看源碼 找到(dào) uin: "658565",uin_base64: "",_biz的(de)值等于(yú)uin_base64就(jiù)可以(yǐ)了(le/liǎo)
} else { //關注了(le/liǎo)可以(yǐ)進行下一步
uni.request({
url: 'url',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'GET',
success: (ti) => {
}
})
}
},
})
}
}else{
uni.showModal({
title:'請在(zài)微信打開',
content:'請在(zài)微信打開本網頁'
})
}
獲取code返回的(de)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;
}