微信 之 授权流程

这里只说前端需要做的事,并且假定已经拥有了微信公众号和服务器(设置回调域名)

详情可查看微信官方文档  微信开放文档

1.在微信公众号后台配置JS接口安全域名、网页授权域名(回调域名)。 

2.切割地址,用方法拿到code


const getLookUrlInfo = (name) => {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || false;
}


let code = getLookUrlInfo('code')

3.若没有拿到code,说明没有经过授权,此时需要跳转到微信进行授权

//调用此方法
const getCodeApi = () => {//获取code  
  let urlNow = encodeURIComponent(window.location.href)
 
  //let urlNow =   https://www.bejson.com/enc/urlencode/  在线编码  https://微信公众平台上绑定好的域名
 
  let scope = 'snsapi_userinfo';    //snsapi_base   //静默授权 用户无感知   
  let appid = 'wx--------';         //公众号的id
  let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=123#wechat_redirect`;
  window.location.replace(url);
  
}

4.因为设置了回调域名,当授权成功后,会自动访问回调域名

假如公众号设置的回调域名是   = >    www.baidu.com

这里的的urlNow需要这样写  = >    encodeURIComponent(https://www.baidu.com/abc/login)

后面可以接上自己的路由地址

也就是说,授权成功后,会重新访问到当前页面,这个时候地址后面会带上code

5.拿到code后,接下来就简单了,请求后端提供的接口,把code给后端

6.后端通过code会去拿到openId和token之类的 

整体代码

<!-- //?模块说明 =>  测试模块 -->
<template>
  <div class="About-layout">
    <div>About</div>
  </div>
</template>
<script>
import { getOpenId, getWxConfig } from '_ser/wx';
export default {
  name: 'About',
  props: {},
  components: {},
  data() {
    return {
      code: '',
      openId: ''
    };
  },
  methods: {
    /**
     * 监听方法
     */
    // wx初始化
    wxInit() {
      // 不在微信中直接返回
      if (!this.isWeiXin()) return;
      this.code = getLookUrlInfo('code');
      // 判断是否有code,若没有,跳去授权
      if (!this.code) {
        this.getCode();
      }
      // 若有,请求后台,拿到openId
      this.getOpenId();
    },
    // 判断浏览器是从外部浏览器打开还是从微信浏览器打开
    isWeiXin() {
      let browser = {
        versions: (function() {
          let u = navigator.userAgent;
          let app = navigator.appVersion;
          return {
            // 移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, // IE内核
            presto: u.indexOf('Presto') > -1, // opera内核
            webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, // 火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, // 是否iPad
            webApp: u.indexOf('Safari') == -1 // 是否web应该程序,没有头部与底部
          };
        })(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
      };
      if (browser.versions.mobile) {
        // 判断是否是移动设备打开。browser代码在下面
        var ua = navigator.userAgent.toLowerCase(); // 获取判断用的对象
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    //获取地址栏的信息
    getLookUrlInfo(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || false;
    },
    //微信授权,获取code
    getCode() {
      let urlNow = encodeURIComponent(window.location.href);
      let scope = 'snsapi_userinfo'; //snsapi_userinfo   //静默授权 用户无感知
      let appid = 'wx--------'; //公众号的id
      let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=123&connect_redirect=1#wechat_redirect`;
      window.location.replace(url);
    },
    /**
     * 请求数据
     */
    // 从后端获取openId
    async getOpenId() {
      // 若缓存了,直接返回
      const codeCache = sessionStorage.getItem('code');
      if (this.code === codeCache) {
        this.openId = sessionStorage.getItem('openId');
        return;
      }
      const { data: res } = await getOpenId(params);
      this.openId = res.openId;
      // 缓存code 和 openId
      sessionStorage.setItem('code', this.code);
      sessionStorage.setItem('openId', this.openId);

      // 接下来就可以去请求后端获取一些微信的配置信息了
      this.getWxConfig();
    },
    //获取微信的配置信息
    async getWxConfig() {
      // 传当前的域名过去,因人而异
      const paramsUrl = encodeURIComponent(window.location.href.split('#')[0]);
      const { data: res } = await getWxConfig(paramsUrl);
      window.wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: res.appId, // 必填,公众号的唯一标识
        timestamp: res.timestamp, // 必填,生成签名的时间戳
        nonceStr: res.nonceStr, // 必填,生成签名的随机串
        signature: res.signature, // 必填,签名
        jsApiList: res.jsApiList // 必填,需要使用的JS接口列表
      });
      // 后面可开始配置微信分享之类的配置
      wx.ready(function () {      //需在用户可能点击分享按钮前就先调用
          wx.updateTimelineShareData({ 
            title: '', // 分享标题
            link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: '', // 分享图标
            success: function () {
              // 设置成功
            }
          })
      });
    }
  },
  mounted() {
    this.wxInit();
  },
  computed: {},
  watch: {},
  filters: {}
};
</script>
<style lang="scss" scoped>
//.About-layout{}
</style>

猜你喜欢

转载自blog.csdn.net/a15297701931/article/details/120865583