How IM login function of scan code to achieve? Get to know a text scan code to log mainstream technical principles

1 Introduction

Scan code to log this feature, the first should be the PC side began to engage in micro-channel, though a bit against humanity functions (scan code did not otherwise log in), but have to say is pretty cool.

The picture below, regardless of IM users or ordinary developer, you should be familiar with:

So, engage in IM product owners and product managers, from the addition of a programmer who needs to be thrown - "Why are believed to have micro sweep the login, and we do not?."

Well, every time as long as there is a micro-channel function, IM programmers who want to dump the pot, the difficulty a bit big, after all, would assume that the bosses are, and some micro letter "I" in IM products have to have.

Since we can not avoid, you can only get to know the technical principles of honest, hard line and then own it.

This article will briefly introduce technology to log scan code to implement logic functions, and the realities of Taobao, scan code login feature micro-letters, learning and research applications of technology giant mainstream thinking.

2, the basic technical principles

2.1 scan code login feature in the end is what?

What is at first introduced the scan code to log on. Now most of the students are equipped with micro letter, qq and Taobao this type of software on your phone. These app have their corresponding web client. To allow users to log more convenient and safe when using their web page, using a cell phone service can log sweep swept away, it is naturally the obvious.

Several major manufacturers use interface sweeping effect when login code as follows:

There are many small partners may feel very magical, the page just shows a two-dimensional code, how would it know which phone to sweep the two-dimensional code, and to sign it? Moreover, after the registration is completed, the user can direct the information to the user, it is really amazing ah.

2.2 scan code login feature complete technical logic

1) with the mating end of a logical web server:

The next step is for the detailed implementation of this service.

First, the user opens the site's login page when the browser sends a request login server gets two-dimensional code. After the server receives the request, it generates a random uuid, this id as key values ​​are stored in redis server, and set an expiration time, and then after expired, the user logs on two-dimensional code need to be refreshed to reacquire.

Meanwhile, the key value and the company's authentication string together, the two-dimensional code is generated by the interface, generate a picture of the two-dimensional code (two-dimensional code generation, there are many online interface and ready-made source code, will not be described here ). Then, the two-dimensional code images and uuid return together to the user's browser.

The browser to get the two-dimensional code and uuid, will be sent to the browser once every second, the login request is successful. Uuid request carries an identifier of the current page. Here some students will be strange, one server only saved in redis uuid as the key value, how will the user id information it?

Here indeed there will be information about the user id, the id information is stored by the phone in the redis server. For details, please read on "with the logical end of the phone to the server."

2) with the logical server and mobile terminal:

Saying that the browser get the two-dimensional code, the two-dimensional code to display on the page, and give the user a hint: Make out your phone, open sweep the log.

Out of cell phone users to scan two-dimensional code, you can get a verification message and a uuid (two-dimensional code scanning function to obtain a string on the Internet there are also many demo, here not described in detail).

Since the end of the phone has been login when accessing the phone side of the server, the parameters are back to carry a user's token, the mobile phone terminal server parses the user userId (direct pass this value from the token instead of the mobile phone side userid is for security, direct transfer userid can be intercepted and modified, token is encrypted, the risk is modified will be much) smaller. Mobile terminal parses the data and user token as parameters together to send authenticated login request to the server (the server where the server is the phone, the phone side of the web server with client-server is not the same server).

After the server receives the request, the first comparison parameter verification information, determine whether the user login request interface. If so, it returns a confirmation message to the mobile phone side.

After receipt of returned mobile terminal, the registration confirmation box is displayed to the user (to prevent user errors, while more humane login). After the user confirms that the login operation, the phone sends a request again. After the server and get uuId userId, the user's userid value as the value stored to redis uuid keys as the key pair.

3) When the login is successful logic:

Then, when the browser again sent the request, the browser server can get a user Id, and call the login method, the sound into a browser's token, when then the browser sends a request again, user information back to the browser , a successful login. Here store user id instead of directly store user information is because the mobile phone end user information, and user information is not necessarily exactly the same browser.

4) Detailed technical principle shown in FIG summarized as follows:

3, log on Taobao scan code technology

In this section we scan code to log on Taobao, for example, to actually study to analyze the scan code to log Taobao implement the logic.

Login screen login.taobao.com/member/logi... pass back parameters:

Then requests (GET) message is this:

https://qrlogin.taobao.com/qrcodelogin/qrcodeLoginCheck.do?lgToken=2c3b4d53ef0513787bf4ce711ea5ba53&defaulturl=&_ksTS=1540106757739_2804&callback=jsonp2805复制代码

The key is to lgToken, is a unique ID page, sign in when you open the two-dimensional code when the page in the polling (long-polling should be long polling) call interface to request the server.

If no scan code, it is returned:

If the sweep, then it will return:

{

"code": "10001",

"message": "mobile scan QRCode success",

"success": true

}

Long time no scan code words, web client will stop polling, two-dimensional code failure!

When the mobile terminal to confirm login, the interface returns:

{ "code": "10006", "success": true, "url": "https://login.taobao.com/member/loginByIm.do?uid=cntaobaoxxx&token=ff82fc0d1d395a33d3b38ec5a4981336&time=1530179143250&asker=qrcodelogin&ask_version=1.0.0&defaulturl=https://www.taobao.com&webpas=0b7aed2d43f01825183e4a49c6cae47d1479929926"}

Indicates that the login is successful, of course, the mobile phone terminal and the server at the click of the interaction between the "Confirm login" is probably what happened: page generated lgToken end to end service request, the server remember this and think lgToken logged, when the web client again polling request interface, it returns a true login state Token, then you can With web client to log in the Token.

Detailed technical logic as shown below:

4, the micro-channel technology scan code login

4.1 Technical principle flow chart

Web version of the micro-channel access address is: wx.qq.com/ , are interested can own in-depth study.

4.2 The actual logic technology

1) obtain a unique uuid, as well as two-dimensional code that contains information about uid:

// Get uuid

getUUID: function() {

vare = t.defer();

returnwindow.QRLogin = {},

$.ajax({

url: i.API_jsLogin,

dataType: "script"

}).done(function() {

200 == window.QRLogin.code ? e.resolve(window.QRLogin.uuid) : e.reject(window.QRLogin.code)

}).fail(function() {

e.reject ()

}),

e.promise

}

2) the browser poll the server, acquires scan code state:

// Check scan code status

checkLogin: function(e, a) {

varn = t.defer()

, a = a || 0;

returnwindow.code = 0,

window.checkLoginPromise = $.ajax({

url: i.API_login + "?loginicon=true&uuid="+ e + "&tip="+ a + "&r="+ ~newDate,

dataType: "script",

timeout: 35e3

}).done(function() {

newRegExp("/"+ location.host + "/");

if(window.redirect_uri && window.redirect_uri.indexOf("/"+ location.host + "/") < 0)

returnvoid (location.href = window.redirect_uri);

product = {

code: window.code,

redirect_uri: window.redirect_uri,

userAvatar: window.userAvatar

};

n.resolve(e)

}).fail(function() {

n.reject ()

}),

n.promise

}

3) The state of the scan code returned by the server, the corresponding action:

* 408 scan code Timeout: If the phone does not scan code or no authorization login, the server will block about 25s, then the return status code 408 -> continue to poll the front

Failure dimensional code 400 *: not scan code within about 5 minutes, the two-dimensional code fails

* 201 is scan code: If the phone has scan code, immediately return to the basic information of the server and the user's status code (window.code = 201, window.code.userAvator = " ..."), -> continue to poll the front end

* 200 Authorized: If the phone clicked to confirm login, the server returns a 200 and token -> stop polling front-end, access to the token, redirected to the target page

Specific code examples are as follows:

The scan code // server returns state, corresponding operation

functiono(c) {

switch(c.code) {

case200:

t.newLoginPage(c.redirect_uri).then(function(t) {

varo = t.match(/<ret>(.*)<\/ret>/)

, r = t.match(/<script>(.*)<\/script>/)

, c = t.match(/<skey>(.*)<\/skey>/)

, s = t.match(/<wxsid>(.*)<\/wxsid>/)

, l = t.match(/<wxuin>(.*)<\/wxuin>/)

, d = t.match(/<pass_ticket>(.*)<\/pass_ticket>/)

, f = t.match(/<message>(.*)<\/message>/)

, u = t.match(/<redirecturl>(.*)<\/redirecturl>/);

returnu ? void (window.location.href = u[1]) : o && "0"!= o[1] ? (alert(f && f[1] || "登录失败"),

i.report(i.AUTH_FAIL_COUNT, 1),

void location.reload()) : (e.$emit("newLoginPage", {

Ret: o && o[1],

SKey: c && c[1],

Sid: s && s[1],

Uin: l && l[1],

Passticket: d && d[1],

Code: r

}),

void (a.getCookie("webwx_data_ticket") || n.report(n.ReportType.cookieError, {

text: "webwx_data_ticket bill lost"

cookie: document.cookie

})))

});

break;

case201:

e.isScan = !0,

n.report(n.ReportType.timing, {

timing: {

scan: Date.now()

}

}),

t.checkLogin(e.uuid).then(o, function(t) {

!t && window.checkLoginPromise && (e.isBrokenNetwork = !0)

});

break;

case408:

t.checkLogin(e.uuid).then(o, function(t) {

!t && window.checkLoginPromise && (e.isBrokenNetwork = !0)

});

break;

case400:

case500:

case0:

vars = a.getCookie("refreshTimes") || 0;

s < 5 ? (s++,

a.setCookie("refreshTimes", s, .5),

document.location.reload()) : e.isNeedRefresh = !0;

break;

case202:

e.isScan = !1,

e.isAssociationLogin =! 1,

a.setCookie("login_frequency", 0, 2),

window.checkLoginPromise && (window.checkLoginPromise.abort(),

window.checkLoginPromise = null),

r()

}

e.code = c.code,

e.userAvatar = c.userAvatar,

a.log("get code", c.code)

}

4.3 Summary

When the end of the micro channel scan code login page, the polling data is returned in the form of JSONP, which is cross-domain in order to solve the problem.

When the end of the micro channel scan code login page, using a polling request in accordance with front blocking background scan code, the optimized reduced polling and polled distal invalid.

5. This Summary

Scan code to log this feature, there are now only appear IM applications, the online site with a variety of mobile terminals also have this feature, so the technical principles described in this article is not limited only to the implementation of IM applications scan code to log on.

In addition, in order to facilitate gripping real data analysis, the PC case analysis in this paper is aimed at web client, but in fact if your PC end is a rich client (that is, .exe, .dmg this installation version), the principle is the same, and does not need to consider the browser's cross-domain issues.


BLOG Address : www.liangsonghua.com

Focus on micro-channel public number: preserved egg blackboard, get more exciting!

Public No. Description: sharing technology insights to work in Jingdong, as well as JAVA technology and industry best practices, most of them are pragmatic, can understand, reproducible


Guess you like

Origin juejin.im/post/5e45f943e51d45271d5d2dce