pc端微信授权登录

191 阅读1分钟

1.pc 端微信扫码登录思路
1.1 点击微信登录方式或者初始化微信登录得 页面

       <div class="wxLogin">
            <div class="other">其他登录方式</div>
            <div @click="fnWeixingOauther"><img src="@/assets/images/wx.png" alt=""></div>
          </div>
        </div>

        <div class="weixinLogin" v-show="wxLoginShow">
            <div class="wxBox">
              <div id="login_container"></div>
            </div>
        </div>        
 

1.2 方法

  mounted(){
    this.fnWeixingOauther(1)
  },
  methods:{
   // 微信授权
    fnWeixingOauther(type) {
      if (type != 1) {
        this.wxLoginShow = true;
      }

      var obj = new WxLogin({
        self_redirect: false,
        id: "login_container", ////需要承载二维码的容器id
        appid: "",
        scope: "snsapi_login",
        redirect_uri: encodeURIComponent(`要跳到的那个页面获取code 比如index.html`),

        state: Math.random(),
        style: "",
        href: "",
      });
    },
    }

1.3 跳转的那个index.html代码

    let href = window.location.href   
    let codeObj = getUrlCode() // 获取code
     window.location.href = `再跳转页面传code过去?code=${codeObj.code}` // 线上环境调试
    // 获取凑得 
    // http://index.html?code=''&state=STATE
    function getUrlCode() {
        // 截取url中的code方法
        var url = location.search;
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
        }
        // console.log(theRequest);
        return theRequest;
    }

1.4 授权的页面

 mounted() {  
    this.getOauth(); // 授权
  },
   methods: {
    async getOauth() {
      let params = {
        code: this.$route.query.code,
        
      };
      let res = await this.$post("接口登录的", params);
      if (res && res.code === 10000) {
        //获取用户的手机号
        let phone = res.data.phone;
        if (isvalidPhone(phone)) {
          // 手机号存在就获取用户信息
          this.getUserInfo(res.data.phone);
        } else {
        // 不存在就绑定手机号
          this.$router.replace("/bindPhone"); // 绑定手机号
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    async getUserInfo(phone) {
      let url = this.url.getUserInfoURL;
      let info = await this.$get(url);
      if (info.code === 10000) {
        try {
         // 对当前用户保存数据 根据你页面需要保存          
          this.successMessage("授权成功");
          this.$router.replace({
            path: "/home",
          });       
        } catch (e) {}
      } else {       
      }
    },
  },