微信扫码登录

微信扫码登录

场景 ① 直接跳转一个新链接页面; ② 网站将微信登录二维码内嵌到自己页面中

① 直接跳转一个新链接页面
pc端展示登录按钮,点击登录按钮,打开二维码页面,手机微信扫描二维码,授权同意,pc页面跳转新页面

<template>
  <div class="container">
    <!-- pc端展示 登录按钮 -->
    <button @click="login">微信登录</button>
  </div>
</template>
<script>
const APPID = 'wx536e555555555555'
export default {
  data () {
    return {
    };
  },
  async created () {
    // const wxCode = this.getQueryString('code')
    const wxCode = this.getQs('code')
    if (wxCode){
      /* 微信授权获取code成功后,重定向到某个页面,这里写的是当前页,再次来到beforeCreate生命周期,可以通过location的search来获取code
         获取到code值后,将code发送接口到后台,后台获取到code后,通过code获取 access_token,再通过access_token来获取用户info,后台返回前端一个token,登录用的token
       */
      const response = await this.$http.post('getToken', { wxCode: wxCode })
      token = response.data.openid
      this.$cookie.set('token', token)
      /* 业务逻辑,在路由守卫进行权限控制 */
      /* 用户微信授权成功后,会进入redirect_uri中的地址,这里设置的是本页, 
      此时会重新走一遍vue的生命周期,来到created时,获取到code值,发送接口 ,获取到了token
      同时,页面跳转到别的页面
      */
      this.$router.push('/list')
    }
  },
  methods: {
    login () {
      /* 展示二维码:
      https://open.weixin.qq.com/connect/qrconnect 
      appid=xxxxxxxxxxxxxxxx 
      redirect_uri=https://xxxxxx.com/index.html  // 二维码登录成功后跳转的链接地址
      response_type=code
      scope=snsapi_login
      state=state
      #wechat_redirect
       */
      window.location.href = 'https://open.weixin.qq.com/connect/qrconnect?appid=wxafc256bf83583323&redirect_uri=http://www.yiyuanlive.com/mall/index.html&response_type=code&scope=snsapi_login&state=state#wechat_redirect'
    },
    getQs (name) {
      const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      const r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
  }
};
</script>

② 支持网站将微信登录二维码内嵌到自己页面中,用户使用微信扫码授权后通过JS将code返回给网站

<div id="wxqr" class="wxqr"></div>

//步骤1:在页面中先引入如下JS文件(支持https):
http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js

//步骤2:在需要使用微信登录的地方实例以下JS对象:
const obj = new WxLogin({
	id:"wxqr",
	appid: "wxb9e2238ff05c7bd7", 
	scope: "snsapi_login",
	redirect_uri: "https://test.2or3m.com/newWeb/binding_phone.html",
	state: "2or3m",
	style: "white"
});
posted @ 2021-11-09 17:42  shine_lovely  阅读(1672)  评论(0编辑  收藏  举报