Front-end implementation of WeChat authorized login

PC web WeChat authorization login

One: the way of web page jump

01. Request the background interface, it will return a WeChat scan code interface address, use js to jump to the past

 

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

02. After the user scans the code and clicks to confirm the authorization, the background will get the information of the WeChat authorized user, and will help us jump to the address page that redirected to the background in advance (here I created a blank page to receive the background Returned data), a token will be stitched in the background behind the address, we get this token, to get user information, jump to the home page, you can complete the login

 

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

Two: Web page embedded QR code

01. Configure the following relevant parameters to generate WeChat authorized login / bind QR code, (Note: setWxerwma () This method needs to be called in 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. The following logic can be processed according to the data returned by the background, similar to the method one step two

Authorized login on WeChat official account

01. Create a button and click the trigger event to jump to the WeChat authorization page

 

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. The code returned to WeChat from the redirected page will be spliced ​​behind the URL. We get this code and request the back-end interface in exchange for the token to complete the WeChat login

 

Published 51 original articles · 19 praises · 60,000+ views

Guess you like

Origin blog.csdn.net/qq_40999917/article/details/104555998