PC端微信扫码登录

一、微信开放平台

1.创建网站应用
2.设置回调域名

二、代码

1.在index.html页面引入http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js,如果网站支持https那就把前缀改为https
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
2.创建二维码
<!-- 显示二维码的容器 -->
<div id="code-container"></div>

// 创建二维码方法
get_wx_qrcode() {
  const href = '扫码完成的回调域名' + '#/login_code' // /login_code是进行登录操作的页面

  var obj = new WxLogin({
    self_redirect: true
    , id: 'code-container' // 需要承载二维码的容器id
    , appid: '网站应用的appid'
    , scope: 'snsapi_login' // 网页授权,目前网页只有这一种方式,静默授权
    , redirect_uri: encodeURIComponent(href) // 回调域名
    , state: Math.random()
    , style: 'white'
    , href: 'data:text/css;base64,加密的样式' // 二维码样式代码base64加密
  })
};
3.获取code,调用登录接口

写在路由为/login_code的页面里

<template>
    <!-- 登录扫码 -->
    <div class="container">
        <div>{{url}}</div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      url: '登录中,请稍等...'
    }
  }
  , async activated() {
    this.getQueryVariable()
  }
  , methods: {
    // 获取url参数
    async getQueryVariable() {
      this.paramRequest = {}
      const url = window.location.href.split('?')[1]
      const urlarr = url.split('&')

      for (const item of urlarr) {
        this.paramRequest[item.split('=')[0]] = item.split('=')[1] // 前者为参数名称,后台为参数值
      }
      await this.login()
    }
    // 获取token
    , async login() {
      let res = await this.$request.getRequest({
          url:`微信扫码登录接口`,
          method:'POST'
      })
      if(res.code==200){
          this.$storage.set('token',res.data.token)
         window.parent.location.href = '回调域名'+'#/'
      }else{
          this.$message.error(res.msg);
          this.$storage.set('token',res.data.token)
          this.url = '登录失败,请刷新二维码重试'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
    .container{
        width: 180px;
        height: 164px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐