H5頁面分享到微信獲取用戶信息
注意:我們要求調(diào)試微信網(wǎng)頁授權(quán),必須開發(fā)者微信號與公眾號建立綁定關(guān)系
需求背景:將H5頁面分享到微信,頁面中的功能需要登錄,所以再進行功能操作前需要調(diào)起登錄
授權(quán)登錄
1、微信登錄的幾種情況:
PC端:
PC端微信瀏覽器 -> 網(wǎng)頁內(nèi)嵌二維碼方式(需要掃碼,使用微信服務(wù)號的 appid 和 appsecret)
PC端其他瀏覽器 -> 跳轉(zhuǎn)微信的掃碼登錄頁面(需要掃碼,使用微信開放平臺注冊的PC應(yīng)用 appid 和 appsecret)
移動端:
微信客戶端打開 -> 直接調(diào)用微信授權(quán)(不掃碼,使用微信服務(wù)號的 appid 和 appsecret)
其他手機瀏覽器打開 -> 跳轉(zhuǎn)微信的掃碼登錄頁面(需要掃碼,使用微信開放平臺注冊的PC應(yīng)用 appid 和 appsecret)
2、區(qū)分是否是PC環(huán)境的方法:
function IsPC(){
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
}
return flag;
}
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
//alert(navigator.userAgent);
window.location.href ="iPhone.html";
} else if (/(Android)/i.test(navigator.userAgent)) {
//alert(navigator.userAgent);
window.location.href ="Android.html";
} else {
window.location.href ="pc.html";
};
獲取用戶信息流程
- 獲取微信中的code
// 獲取微信用戶code
getWxCode() {
let appid = "公眾號appid"; // 一定是小程序和微信公眾號進行了綁定,否則不生效
let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
location.href
)}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`;
this.code = this.getUrlCode().code;
//如果沒有code 去獲取code
if (this.code == null) {
window.location.href = url;
} else {
//獲取到code后的邏輯
console.log("code", this.code);
this.login();
}
},
2.截取url中的code文章來源:http://www.zghlxwxcb.cn/news/detail-520444.html
// 截取url中的code
getUrlCode() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") !== -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
},
3.調(diào)用登錄接口文章來源地址http://www.zghlxwxcb.cn/news/detail-520444.html
async login() {
console.log("開始登錄");
const data = {
code: this.code,
udid: "081cvZ280Toa1F1VfB180Jv8380cvZ2i",
appletType: 4
};
ajaxMethod.doAjax("接口地址", data, (res) => {
if (res.success) {
if (res.datas.token) {
setLocalStorageBykey("ticket", res.datas.token);
console.log("登錄后進行Ticket緩存");
}
return;
}
});
},
到了這里,關(guān)于H5 及 web 頁面微信授權(quán)登錄流程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!