微信公眾號(hào)網(wǎng)頁(yè)授權(quán)
1. 判斷是否登錄(這里判斷是否登錄是通過(guò)判斷是否有token),判斷url中是否有帶code的參數(shù)
if (this.$store.getters.token || getToken("authToken")) {
return;
}
let code = utils.GetQueryString("code");
if (!code) {
this.redirectWechatOAuth();
return;
}
this.getUserInfo(code);
1.1 判斷url是否有某個(gè)參數(shù)
function GetQueryString(name) {
var reg =new RegExp('(^|&)' + name +'=([^&]*)(&|$)');
? var r = window.location.search.substr(1).match(reg);
? if (r !=null)return unescape(r[2]);
return null;
}
2.獲取openId荸恕,?redirect_uri重定向地址的url中不能帶code參數(shù)角寸,跳轉(zhuǎn)到登錄頁(yè)url上帶著code和openid
redirectWechatOAuth() {
let url = window.location.href;
? url = utils.removeQueryByName(url, "code");
? let redirectUri =encodeURIComponent(url);
? this._apis.my.getPageLoginOpenid().then(response => {
?let weiChatAppId = response;
?let weChatOAuthUrl =
"https://open.weixin.qq.com/connect/oauth2/authorize?
appid=" +weiChatAppId +
"&redirect_uri=" +redirectUri +
"&response_type=code&scope=snsapi_userinfo" +
"&component_appid=wx18dce921dbb69c72" +
"#wechat_redirect";
? ? ? window.location.href = weChatOAuthUrl;
? ? })
.catch(error => {
console.error(error);
? ? });
},
2.1 去除url地址上的某個(gè)參數(shù)
function removeQueryByName(url, name) {
var str ="";
? if (url.indexOf('?') != -1) {
str = url.substr(url.indexOf('?') +1);
? }
else {
return url;
? }
var arr ="";
? var returnurl ="";
? var setparam ="";
? if (str.indexOf('&') != -1) {
arr = str.split('&');
? ? for (var i =0; i < arr.length; i++) {
if (arr[i].split('=')[0] != name) {
returnurl = returnurl + arr[i].split('=')[0] +"=" + arr[i].split('=')[1] +"&";
? ? ? }
}
return url.substr(0, url.indexOf('?')) +"?" + returnurl.substr(0, returnurl.length -1);
? }
else {
arr = str.split('=');
? ? if (arr[0] == name) {
return url.substr(0, url.indexOf('?'));
? ? }
else {
return url;
? ? }
}
}
3.通過(guò)code來(lái)獲取登錄信息
getUserInfo(code) {
if (code) {
this.$store.dispatch("login", channelId:"2", wxCode: code})
.then(response => {
this._apis.my
? ? ? ? ? .getPageSignClick()
.then(response => {
//登錄之后的操作
? ? ? ? ? })
.catch(error => {
console.error(error);
? ? ? ? ? });
? ? ? })
.catch(error => {
console.log("報(bào)錯(cuò)");
? ? ? });
? }else {
return false;
? }
},