Interviewer: You tell me how scanning logins work

Me: Well, open the web page, it shows a QR code, scan it with the app, and then you can log in.

Interviewer: That’s good. I’ll keep you posted

Scanning code login is a common function of the website, and it is also a frequent test point of the interview. Although it is often used, some children may not be very clear about its implementation process and principle, resulting in missing the offer of millions of annual salary. Today, taking advantage of the weekend boring, to achieve a simple scan code login.

Initialize a uni-app project, scan code login must use app or wechat applet. Start with a simple app using uni-app

To download a HBuilderX (www.dcloud.io/hbuilderx.h.)

Initialize a random project

Scan code login, must be the need to login with the APP to scan code, so write two lines of code to achieve a simple login page

An account box, a password box, a login button

With KOA2, initialize any back-end project you want

NPM install koa-generator -g koA2 (XXXX) Project name CD XXXX NPM install NPM install koA2-corsCopy the code

Then add the following code to app.js

app.use(cors({
  origin:function (ctx) {
    if(ctx.url === '/string'){
      return "*";
    }
    return '*';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
Copy the code

Every time you change the Node project, you need to re-npm it because you are not using hot updates.

For simplicity, define a random user information and implement a login interface

After entering your account password, click Login and invoke the login interface in uni-app

uni.request({ url: 'http://xxx.xxx.xxx.xxx:3000/login', / / note that the IP can't use localhost or 127.0.0.1 here need to use ipconfig to get the real computer IP, on a mobile phone can't call interface method: 'POST', data: {userName: this.userName, // userName: this.password // password}, success: ({data}) => { if(data.code === 1) { this.isLogin = true; This. token = data.token // Records the returned token information}}, fail: (err) => {console.log(err)}});Copy the code

The purpose here is to log in to the mobile phone port. After logging in, you need to return the token information and record it

Then realize the scanning function, which has been built into UNI-app, and we can call it directly

uni.scanCode({
    success: (res) = > {
        // res.result Get the scan result
        // If the scan succeeds, the request must be initiated here}});Copy the code

Need to pay attention to the use, click the scan code button on the PC side, is unable to evoke the scan code, so you need to connect the phone, use the data line to connect the phone and computer, and then open THE usB debugging

If you have any questions, please refer to:Hx.dcloud.net.cn/Tutorial/Ap…

Click the scan button, you can see that the scan function has been activated

Now we need to prepare a random QR code to scan and install a QR-Image in the KOA back-end project

npm install qr-image
Copy the code

Create_qrcode generates a random_img_id, then generates the corresponding QR code, and returns the image to the front end (PC).

Now we need to have a PC side website to display qr code images. For simplicity, we will create a new HTML file. A single line of code can display the QR code

<img src="http://localhost:3000/create_qrcode" />
Copy the code

Scanning this QR code with wechat, you can see the corresponding 10-digit random number information of the QR code

In the actual application, after scanning the TWO-DIMENSIONAL code, we can see that the two-dimensional code will show that it has been scanned, so after scanning, we need to call an interface to modify the two-dimensional code state, and get the temporary token returned from the background

Now implement the logic after the scan

uni.scanCode({
    success: (res) = > {
	ni.request({
            url: 'http://xxx:xxx:xxx:xxx:3000/change_img_status'.method: 'POST'.data: {
                code: res.result, // Send the qr code scanning results to the background
            },
            success: ({data}) = > {
                this.isScanStaus = true; // Indicates that the QR code has been scanned
                this.random_token = data.random_token; // Record the temporary token}}}}));Copy the code

So how does the PC know that the QR code has been scanned? In fact, it is very simple, we can deal with it through websocket or polling. For the sake of simplicity, we use polling to query the status of two-dimensional code and determine whether to scan

First, you need to define an interface to query the status of the TWO-DIMENSIONAL code

Write a simple code in the CORRESPONDING HTML file on the PC

Then introduce vUE

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
Copy the code

The initial state is not logged in, get the TWO-DIMENSIONAL code button

Once you click the button to get the TWO-DIMENSIONAL code, poll to query the two-dimensional code status

When the APP scans the code, it will show the scanned code

Then we need to realize that after app code scanning, there will be a pop up to confirm login. Click “Confirm login” to complete the whole code scanning process

First, implement the login confirmation interface to verify whether the token information and temporary token information of the APP are correct. If so, modify the scan status

The interface is invoked in uni-app with the parameters token and temporary token

After clicking the “OK” button, the POLLING interface on the PC side will return the token information, and then obtain the user scan code and stop the polling

So far the whole scan code login process ends, of course, the actual application is certainly much more complex.

To summarize the whole process of scanning code login:

  1. If the PC is not logged in to the server and the server is logged in to, a TWO-DIMENSIONAL code is returned, which contains specific information

  2. The PC will always send polling requests (or websocket) to ask whether or not to scan

  3. Mobile phone users (who have logged in to their accounts) scan the QR code, call the relevant interface to identify the QR code information, and send the token to the server. After the server gets the token, the status of the QR code will change to the scanned code, so the SCANNED code will be displayed on the PC

  4. The server then verifies the token and qr code information and returns a temporary token to the mobile

  5. Click login on the mobile terminal to confirm login

  6. The temporary token is returned to the server, and the server verifies the temporary token (in order to prevent the inconsistency between the mobile phone scanned and the mobile phone logged in). After passing the verification, the server takes out the information from the token and synchronizes it to the PC

  7. The login succeeds. Procedure