前端实现微信授权登录

PC网页微信授权登录

一:网页外链跳转的方式

01.请求后台的接口,会返回一个微信扫码的界面地址,使用js跳转过去即可

    wxlogin () {
       User.wxlogins().then(res => {
        console.log(res)
        window.location.href = res.result.url
      })
    },

02.用户在扫完码点击确定授权后,后台会拿到微信授权用户的信息后,会帮我们跳转到事先给后台重定向的地址页面(这里我是新建了一个空白页用来接收后台返回的数据),在地址后面后台会拼接一个token,我们拿到这个token,去获取用户信息,跳转到首页,即可完成登录

let token = this.$route.query.token
    if (token) {
      this.getUserInfo().then(ures => {
        this.$router.push({
          name: 'home'
        })
      })
    }

二:网页内嵌二维码方式

01.配置好下面相关参数,即可生成微信授权登录/绑定二维码,(注意:setWxerwma ()此方法需在mounted中调用)

 setWxerwma () {
      const s = document.createElement('script')
      s.type = 'text/javascript'
      s.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
      const wxElement = document.body.appendChild(s)
      wxElement.onload = function () {
        var obj = new WxLogin({
          id: '', // 需要显示的容器id
          appid: '', // 公众号appid wx*******
          scope: 'snsapi_login', // 网页默认即可
          redirect_uri: encodeURIComponent(''), // 授权成功后回调的url
          state: Math.ceil(Math.random() * 1000), // 可设置为简单的随机数加session用来校验
          style: 'black', // 提供"black"、"white"可选。二维码的样式
          href: '' // 外部css文件url,需要https
        })
      }
    },

02.后面的逻辑根据后台返回的数据来处理即可,同方法一步骤二类似

微信公众号网页授权登录

01.创建一个按钮,点击触发事件,跳转到微信授权页面

wxlogin () {
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${this.url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    }
//this.appid 公众号APPID  this.url  用户点击授权后,会跳转到后台帮我们重定向的页面(这里我是新建了一个空白页,专门接收code)

02.在重定向的页面拿到微信那边给我们返回的code,会拼接在URL后面,我们拿到这个code再请求后台的接口换取token,完成微信登录

发布了51 篇原创文章 · 获赞 19 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_40999917/article/details/104555998