An article will take you to know about wechat scanning code login

Posted by Roja on Sun, 30 Jan 2022 05:22:08 +0100

preface

Hi, Hello, I'm Xiliu.
Many PC websites have the function of using wechat scanning code to log in. You don't need to enter the user name and password. Open the mobile wechat scanning to automatically log in. It's really convenient.
So, how does it achieve fast login?
This article will take you through the login scenario of the real project to understand the whole process of wechat code scanning login. If it's helpful to you, don't forget to praise and support. Thank you!

1, Functional background

The company's platform login page should add a wechat code scanning login method. Users can choose to log in with wechat account. When clicking wechat account to log in, a wechat login QR code will pop up. After scanning the code and confirming, judge whether the user account is bound to the platform account. If bound, login is completed. If it is not bound, a line of prompt text will appear under the login button. Automatically bind the account after login. You can log in directly with wechat next time.

The platform is a front-end and back-end separated project, and the technology stack used is SpringBoot+Vue.

2, Principle of code scanning login

1. Basic principles

The website application wechat login is based on oauth2 Wechat OAuth2.0 protocol standard 0 is authorized to log on to the system.

Wechat oauth2 0 authorized login allows wechat users to safely log in to third-party applications or websites using wechat identity. After wechat users are authorized to log in, they have access to wechat oauth2 After the third-party application of 0, the third-party can obtain the user's access_token through access_ Token can call the authorization relationship interface of wechat open platform, so as to obtain the basic open information of wechat users and help users realize basic open functions.

Wechat oauth2 The authorization_code mode of 0 authorization login is applicable to the application authorization with server. The overall process of this mode is:

  • 1. The third party initiates the wechat authorization login request. After the wechat user allows the authorization of the third-party application, wechat will pull up the application or redirect to the third-party website, and bring the code parameter of the authorization temporary bill;
  • 2. Add AppID and AppSecret through the code parameter, and exchange access through the API_ token;
  • 3. access_token to call the interface to obtain the user's basic data resources or help the user realize basic operations

    In short, the user enters the callback address after scanning the code on the page generating the QR code. The callback address can obtain the temporary bill code, access token through code, and all the user's information through access token; By binding the obtained user information one-to-one with the third-party application account to log in, you can log in to the third-party application using wechat scanning code;

3, Implementation effect diagram

1. Login page

2. Click wechat account to log in


3. Wechat account bound

4. Account not bound to micro signal


4, Code implementation

1. Preparation

The official account is registered on WeChat open platform (not WeChat public number platform), and has an approved website application. The corresponding AppID and AppSecret are obtained. WeChat is registered and audited, and the access process can be started. (at present, individual account registration is not supported, and company registration is required.)


2. Write code

Write front-end code:

Click wechat login to pop up the login QR code. The domain name of the callback address shall be consistent with the callback domain name set by the open platform

<div  v-if="showWxLogin">
          <img src="@/assets/img/login/wx.jpg" alt="" />
          <p style="margin-top:-30px"><a @click="onWxLogin" >Wechat account login</a></p>
</div>
<div  v-if="showBinding">
  <p ><input type="checkbox" id="checkbox" v-model="checkBinding">After successful login, connect with wechat and log in directly with wechat next time</p>
</div>

<a-modal :visible="wxLoginVisible"
              :footer="false"
              :maskClosable="false"
              @cancel="wxLoginVisible = false">
      <!-- Place QR code div -->
      <div id="login_container">
        <iframe></iframe>
      </div>
  </a-modal>

  <a-modal  :visible="bindingWxLoginVisible"
              :footer="false"            
              :closable="false"
              :maskClosable="false"
              @cancel="bindingWxLoginVisible = false">
      <p>Hello! xxx</p>
      <p>You do not have an associated learning platform account, please select an operation:</p>
      <a-button  size="small" @click="cancel">cancel</a-button>
      <a-button  type="primary" size="small" @click="binding">Log in to an existing account</a-button>
</a-modal>

<script>
import wxlogin from '@/utils/wxLogin' // Introduce js for generating wechat QR code

 watch: {
      $route() {
          /*Monitor whether the route has a code value*/
          if(this.$route.query.code != undefined) {
              //Request backend wechat login interface
              this.getWeixinLogin(this.$route.query.code,this.$route.query.state);
          }
      }
  },
methods: {
async onWxLogin() {
    // Generate wechat login QR code
    this.wechatCode()
    this.wxLoginVisible = true
},
async wechatCode () {
    // The callback address and domain name should be consistent with the set callback domain name, and the front-end routing address
    let url = process.env.VUE_APP_LEARN_BASE_URL + "/#/login/student";
    // appid
    let wxAppId = process.env.VUE_APP_WX_APP_ID;
    // Remember to note that the file type is css
    var blob = new Blob([""],{type: "text/css;charset=utf-8"});
    var reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = function(e) {
        var obj = new WxLogin({
            self_redirect: false,  // When the value is true, page Jump and other operations are directly carried out in the pop-up window of QR code,
            id:"login_container", // id of div
            appid: wxAppId,
            scope: "snsapi_login", //Fixed content
            redirect_uri:encodeURIComponent(url) // token url 
          })
        }
},
async getWeixinLogin(code) {
    // Request to judge whether wechat is bound
    let res = await api.student.wxLogin({ code: code })
    if (res.code === 200) {
        let data = res.data;
        // Wechat nickname
        this.nickname = data.nickname;
        // Wechat login
        this.refreshToken = data.refresh_token;
        // data.code == 100 indicates unbound micro signal
        if (data.code === '100') {
            this.wxLoginVisible = false;
            // The bind wechat account page pops up
            this.bindingWxLoginVisible = true;
        } else {
            // Page after successful login
            ...
        }
    }
},
async cancel() {
    this.bindingWxLoginVisible = false;
},
async binding() {
    this.bindingWxLoginVisible = false;
    this.checkBinding = true;
    this.showBinding = true;
    this.showWxLogin = false;
},
}
</script>

Write back-end Code:

The back end only needs to provide two interfaces, one is to verify whether the micro signal is bound to the platform user's interface, and the other is the interface between the micro signal and the platform user. You can view the official documents by requesting wechat interface information: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html

@GetMapping("/student/wxLogin")
public R wxLogin(String code){
    if(StringUtils.isBlank(code)){
        return R.fail("User prohibited authorization");
    }
    //Get access through code_ token
    String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
    // Request wechat interface and return token information
    Token accessToken = JSON.parseObject(HttpClientUtil.doGet(tokenUrl), Token.class);
    //Get user information
    String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken.getAccess_token()+"&openid="+accessToken.getOpenid();
    StudWx studWx = JSON.parseObject(HttpClientUtil.doGet(userUrl), StudWx.class);
    //Judge whether the user is bound to wechat. If not, jump to the binding page; Bind direct login
    ...
    
    if(...){
        //If wechat is not bound, return the information required by the front end and let the front end jump to the binding page
        ...
    }else{
        //Direct login
        ...
    }
}
@PostMapping("/student/bdingLogin")
public R bdingLogin(@RequestBody LoginParam param){
    //First judge whether the account has been bound to wechat
    ...
    if(StringUtils.isNotBlank(openId)){
        return R.fail("This account has been bound to wechat");
    }
    //Log in again and judge whether the account password is correct or not
    R login = loginService.login(param);
    //Log in successfully and choose to bind wechat account
    if(login.getCode()==200 && param.getBinding()){
        //Refresh the token to prevent expiration
        String resUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+appid+"&grant_type=refresh_token&refresh_token="+ param.getRefreshToken();
        Token token = JSON.parseObject(HttpClientUtil.doGet(resUrl), Token.class);
        String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token.getAccess_token()+"&openid="+token.getOpenid();
        StudWx studWx = JSON.parseObject(HttpClientUtil.doGet(userUrl), StudWx.class);
        //Save related operations of user binding wechat number
        ...
    }
    //Return success
}

summary

Well, the above is the whole process and implementation of wechat code scanning login. The core process is: open the page to generate the wechat login QR code, scan the QR code to log in, and you can know the user information. Through the user information, you can judge whether it is associated with the user account of the platform. The associated user can know which user the wechat login is, and then you can realize the relevant operations of login, You do not need to log in by entering the account and password.

Thank you for reading. If you have any questions or suggestions, leave me a message or add my personal wechat: xiliudd, be a friend and circle praise
Like friends can also scan the code to pay attention to me, more wonderful content waiting for you~

Topics: Java Spring Boot Vue