微信公众号的授权登录

微信公众号网页授权


1. 判断是否登录(这里判断是否登录是通过判断是否有token),判断url中是否有带code的参数

if (this.$store.getters.token || getToken("authToken")) {

return;

}

let code = utils.GetQueryString("code");

if (!code) {

this.redirectWechatOAuth();

return;

}

this.getUserInfo(code);

1.1 判断url是否有某个参数

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参数,跳转到登录页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地址上的某个参数

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.通过code来获取登录信息

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("报错");

      });

  }else {

return false;

  }

},

你可能感兴趣的:(微信公众号的授权登录)