vue2 pc端使用微信扫码登录

73 阅读1分钟

具体步骤

  1. 引入jssdk
  2. 页面初始化出二维码组件
  3. 在重定向页面根据code,向服务端获取用户信息以及凭证token

引入js

<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

初始化

<div class="code-container" ref="codeContainer" id="code-container"></div>
new window.WxLogin({
    self_redirect: false,
    id: 'code-container',
    appid: 'wx6***140b',
    scope: 'snsapi_login',
    redirect_uri: encodeURIComponent(`https://***/login-success?redirect=${this.redirect}`),
    state: Math.random(),
    style: 'black',
    href: ''
  })

用户扫码会直接重定向到初始化设定的redirect_url地址,并且携带参数code

· 前端需要在该跳转页面获取code
· 携带code向后端发送请求获取凭证code以及用户信息 · 登录完成后,一般需要回到原页面,也就是地址上携带的redirect路径