wx-微信公众号-静默登陆授权

介绍

功能: 支持微信/支付宝网页静默授权
为什么需要线上html
因为在开发环境的时候,是本地服务http://localhost:8080,但是微信需要JS接口安全域名.

配置信息

  1. 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“网页授权域名”
  2. 然后把 html 文件放到服务器上, 安全域名指向这个html
  3. 在 vue 环境配置文件(.env.development、.env.production),中配置以下参数
    1. VUE_APP_WX_GET_CODE_DOMAIN = ‘第二步的html文件的线上地址’
    2. VUE_APP_APP_ID = ‘微信/支付宝的appid’
  4. 使用方法:
    1. 直接调取 util 文件中的 getAuthorCode 方法
    2. 调取完后,就可以在地址栏中,看到那个 code 了 (获取code的时候,可以使用这个方法 onGetRequest().code )

代码信息

授权文件


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>授权code</title>
</head>
<body>
  
</body>
</html>
<script>
(function () {
  var tools = {
    getParamer: function (key) {
      var map = this.getSearch();
      return map[key];
    },
    getSearch: function () {
      var search = window.location.search;
      return this.getSearchByStr(search);
    },
    getSearchByStr: function (search) {
      if (search) {
        search = search.substring(1);
      } else {
        return {};
      }
      var strsz = search.split("&");
      var map = {};
      for (var i = 0; i < strsz.length; i++) {
        var strs = strsz[i];
        if (strs.indexOf("=") != -1) {
          var tempsz = strs.split("=");
          var tempkey = tempsz[0];
          var tempvalue = tempsz[1];
          map[tempkey] = decodeURIComponent(tempvalue);
        }
      }
      return map;
    },
    setLocalStorage: function (key, val) {
      var map = {};
      map[key] = val;
      localStorage.setItem(key, JSON.stringify(map));
    },
    getLocalStorage: function (key) {
      var mapStr = localStorage.getItem(key);
      if (!mapStr) {
        mapStr = "{}";
      }
      var map = JSON.parse(mapStr);
      return map[key];
    },
    urlAddProp: function (url, key, val) {
      var jing = url.indexOf("#");
      var left = "";
      var right = "";
      if (jing == -1) {
        //无#号情况
        left = url;
      } else {
        //有#号情况
        left = url.substring(0, jing);
        right = url.substring(jing);
      }
      if (left.indexOf("?" + key + "=") != -1 || left.indexOf("&" + key + "=") != -1) {
        var start = left.indexOf("?" + key + "=");
        if (start == -1) {
          start = left.indexOf("&" + key + "=");
        }
        var end = left.indexOf("&", start + 1);
        if (end == -1) {
          end = left.length;
        }
        right = left.substring(end) + right;
        left = left.substring(0, start + 1);
      } else {
        var type = left.indexOf("?") != -1 ? "&" : "?";
        left += type;
      }
      var data = key + "=" + val;
      return left + data + right;
    },
    /**
     * 设置环境
     */
    getCodeName() {
      if (/MicroMessenger/.test(window.navigator.userAgent)) {  // 微信
        return 'code'
      } else if (/AlipayClient/.test(window.navigator.userAgent)) { // 支付宝
        return 'auth_code'
      } else {
        return ''
      }
    }
  }
  
  function wxLogin(callback) {
    const codeName = tools.getCodeName()
    if (tools.getParamer(codeName)) {
      callback(tools.getParamer(codeName));
    } else {
      //去取code
      let url = ''
      var appid = tools.getParamer('appid');
      if(codeName === 'code'){
        url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(window.location.href) + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
      }else if(codeName === 'auth_code'){
        url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + appid + "&redirect_uri=" + encodeURIComponent(window.location.href) + "&response_type=code&scope=auth_base";
      }
      window.location.href = url;
    }
  }
  var url = tools.getParamer("url");
  tools.setLocalStorage("url", url);
  wxLogin(function (code) {
    const codeName = tools.getCodeName()
    var toUrl = tools.getLocalStorage("url");
    toUrl = tools.urlAddProp(toUrl, codeName, code);
    window.location.href = toUrl;
  });
})()
</script>

util 文件

// 在util 文件中放入一下方法
/**
 * 获取认证 code
 * @param {String}} routerCallback  回调路由
 */
function getAuthorCode(routerCallback) {
  const a = document.createElement('a');
  const urlCallback = encodeURIComponent(
    process.env.VUE_APP_BASE_DOMAIN + routerCallback
  );
  if (process.env.NODE_ENV === 'development') {
    // 测试环境走线上
    a.href = `${process.env.VUE_APP_WX_GET_CODE_DOMAIN}?url=${urlCallback}&appid=${process.env.VUE_APP_APP_ID}`;
  } else {
    // 正式环境 直接获取
    switch (judgeEnvironment()) {
     case 'WX':
        a.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.VUE_APP_APP_ID}&redirect_uri=${urlCallback}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
       break;
     case 'ZFB':
        a.href = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${process.env.VUE_APP_APP_ID}&redirect_uri=${urlCallback}&response_type=code&scope=auth_base`;
       break;
     case 'OTHER':
       a.href = 'javascript:;'
       console.error('当前环境不支持授权~')
       break;
    }
  }
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
/**
 *  获取 url
 * @returns params的参数
 */
function getUrl() {
  const url = window.location.href
  var params = []
  var h
  var hash = url.slice(url.indexOf('?') + 1).split('&')
  for (var i = 0; i < hash.length; i++) {
    h = hash[i].split('=') //
    params[h[0]] = h[1]
  }
  return params
}
/**
 * 判断浏览器环境
 */
function judgeEnvironment() {
  if (/MicroMessenger/.test(window.navigator.userAgent)) {
    return 'WX'
  } else if (/AlipayClient/.test(window.navigator.userAgent)) {
    return 'ZFB'
  } else {
    return 'OTHER'
  }
}
/**
 *
 * @returns {Object} url参数集
 */
function onGetRequest() {
  const url = window.location.href
  var params = []
  var h
  var hash = url.slice(url.indexOf('?') + 1).split('&')
  for (var i = 0; i < hash.length; i++) {
    h = hash[i].split('=')
    params[h[0]] = h[1]
  }
  return params
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值