web前端技术博客
您当前的位置:web前端 > 微信小程序

vue项目获取微信授权code

作者: 发布时间:2021-06-05 12:09:26 浏览量:20

1、判断是否微信端

 function is_weixin() {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}

2、通过appid 跳转到获取code

function getCodeApi(state) {//获取code
  let appId = "wxa197appid";//替换自己公众号appid
  let path = window.location.protocol + '//' + window.location.hostname + "/" + window.location.hash;
  let urlNow = encodeURIComponent(path);
  let scope = 'snsapi_userinfo';// snsapi_base //snsapi_userinfo 弹出授权获取昵称头像,snsapi_base静默授权不获取昵称头像
  let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
  window.location.replace(url);
}

3、获取授权链接返回的code
//调用方法 getUrlKey('code')

​​​​​​​function getUrlKey(name) {
  var url = window.location.search;
  if (url.indexOf('?') == 1) { return false; }
  url = url.substr(1);
  url = url.split('&');
  name = name || '';
  var nameres;
  for (var i = 0; i < url.length; i++) {
    var info = url[i].split('=');
    var obj = {};
    obj[info[0]] = decodeURI(info[1]);
    url[i] = obj;
  }
  if (name) {
    for (var i2 = 0; i2 < url.length; i2++) {
      for (const key in url[i2]) {
        if (key == name) {
          nameres = url[i2][key];
        }
      }
    }
  } else {
    nameres = url;
  }
  return nameres;
}


 

发表评论
验证码:
联系我
粤ICP备17092958号