前端PC端微信扫码登录

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>

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值