微信公众号使用微信登录

179 阅读1分钟

若是pc网站接入微信登录,请参考

step1|✨ 点击微信登录,授权获取code

window.location.replace(
          'https://open.weixin.qq.com/connect/oauth2/authorize?' + 
          'appid=' + defaultConfig.APPID + '&redirect_uri=' + encodeURIComponent(defaultConfig.webUrl + '/wx-login-bind-phone')
          + '&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'
)

step2|✨在defaultConfig.webUrl + '/wx-login-bind-phone'页面处理

async created() {
    // 微信重定向url获取code
    let code = this.$route.query.code;
    if(code) {
      try{
        // 微信登录
        let res = await this.$api.wxLogin({ code });
        
        if(res.data.binding) {
          // binding为true,直接保存token并跳转至应用首页
          this.$store.commit('user/SET_TOKEN', res.data.token);
          this.$router.push('/home');
          return;
        }

        // 切换显示绑定手机号码并登录页面
        this.pageLoading = false;
        this.loginInfo.key = res.data.key;
      }catch(e) {
        console.log(e);
      }
    }
},
/**绑定手机号码并登录*/
async handleLogin() {
  this.$refs.loginFormRef.validate()
    .then(async () => {
      this.loginLoading = true;
      try{
        await this.$store.dispatch('user/WxLoginBindPhone', this.loginInfo);
        this.$router.push('/home');
      }catch(e) {
        console.log(e);
      }finally {
        this.loginLoading = false;
      } 
    })
    .catch(e => {})

}

详情请参考微信官方文档