How QR Code Login Works Behind the Scenes: From WeChat to Taobao

This article explains the technical workflow of QR code login, covering the generation of UUIDs, QR images, server‑side Redis storage, mobile‑side token verification, long‑polling mechanisms, and the concrete implementations used by WeChat and Taobao, providing a complete reference for developers building similar authentication features.

21CTO
21CTO
21CTO
How QR Code Login Works Behind the Scenes: From WeChat to Taobao

1. Introduction

QR code login first appeared on WeChat's PC client. Although the feature forces users to scan a code to log in, it is undeniably cool.

The following diagram is familiar to both IM developers and ordinary users.

Consequently, product managers start demanding, “Why does WeChat have QR login while our product does not?”

When a feature exists in WeChat, developers often feel pressured to implement it, even though the underlying difficulty may be non‑trivial.

Since the demand cannot be avoided, the only option is to understand the technical principles and implement it ourselves.

This article briefly introduces the technical logic of QR code login and studies the implementations used by major platforms such as Taobao and WeChat.

2. Basic Technical Principles

2.1 What Is QR Code Login?

Most users have apps like WeChat, QQ, or Taobao on their phones, each with a corresponding web version. To make web login more convenient and secure, scanning a QR code with the mobile app can directly log the user in.

Typical UI screenshots from major platforms are shown below:

Users often wonder how a simple QR image on a web page can identify which phone scanned it and complete the login, and how the user information is then displayed.

2.2 Complete Technical Logic of QR Login

1) Interaction between the web page and the server:

When a user opens the login page, the browser requests a QR code from the server. The server generates a random UUID, stores it as a key in Redis with an expiration time, and returns the UUID together with a QR image generated from the UUID.

The browser receives the QR image and UUID, then starts polling the server every second, sending the UUID to check whether the login has succeeded.

The server stores the UUID in Redis; the mobile side later writes the user ID associated with that UUID into Redis as well.

2) Interaction between the mobile client and the server:

The browser displays the QR image and prompts the user to scan it with their phone.

After scanning, the mobile app obtains a verification string and the same UUID. The mobile client sends a verification request to its own server (different from the web server) together with the user's token.

The mobile server validates the token, extracts the userId, and returns a confirmation to the mobile client.

The mobile client then shows a confirmation dialog to the user. Once the user confirms, the mobile client sends another request; the server stores the userId in Redis using the UUID as the key.

3) Logic when login succeeds:

When the browser polls again, it can retrieve the userId from Redis, generate a session token for the web side, and return the user information to complete the login.

4) Summary diagram:

3. Taobao's QR Login Implementation

We take Taobao as an example to analyze the concrete implementation.

The login page https://login.taobao.com/member/login.jhtml returns the following parameters:

Subsequent GET request example:

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

The lgToken is the unique ID for the web page. The page polls the server (long‑polling) to check the login status.

If the QR code is not scanned, the server returns an empty response.

If the QR code is scanned, the server returns:

{
  "code": "10001",
  "message": "mobile scan QRCode success",
  "success": true
}

When the mobile client confirms login, the server returns a URL containing the final token:

{
  "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"
}

The web page then receives the token, redirects to the target URL, and the login is completed.

4. WeChat's QR Login Implementation

4.1 Technical Flowchart

WeChat's web login address is https://wx.qq.com/.

4.2 Actual Implementation Logic

1) Obtain a unique UUID and generate a QR image containing the UID:

// Get UUID
function getUUID() {
  var defer = t.defer();
  return window.QRLogin = {},
    $.ajax({
      url: i.API_jsLogin,
      dataType: "script"
    }).done(function () {
      200 == window.QRLogin.code ? defer.resolve(window.QRLogin.uuid) : defer.reject(window.QRLogin.code);
    }).fail(function () { defer.reject(); })
    .promise;
}

2) Browser polls the server for QR status:

// Check login status
function checkLogin(e, a) {
  var defer = t.defer(),
    a = a || 0;
  window.code = 0;
  window.checkLoginPromise = $.ajax({
    url: i.API_login + "?loginicon=true&uuid=" + e + "&tip=" + a + "&r=" + ~new Date,
    dataType: "script",
    timeout: 35000
  }).done(function () {
    // Process response
    var data = {
      code: window.code,
      redirect_uri: window.redirect_uri,
      userAvatar: window.userAvatar
    };
    defer.resolve(data);
  }).fail(function () { defer.reject(); })
    .promise;
}

3) Handle server responses based on status codes:

function handleStatus(c) {
  switch (c.code) {
    case 200:
      // Login successful, redirect
      t.newLoginPage(c.redirect_uri).then(function (t) {
        // Extract tokens from response
        var ret = t.match(/<ret>(.*)<\/ret>/),
            script = t.match(/<script>(.*)<\/script>/),
            skey = t.match(/<skey>(.*)<\/skey>/),
            wxsid = t.match(/<wxsid>(.*)<\/wxsid>/),
            wxuin = t.match(/<wxuin>(.*)<\/wxuin>/),
            passTicket = t.match(/<pass_ticket>(.*)<\/pass_ticket>/),
            message = t.match(/<message>(.*)<\/message>/),
            redirectUrl = t.match(/<redirecturl>(.*)<\/redirecturl>/);
        if (redirectUrl) {
          void(window.location.href = redirectUrl[1]);
        } else {
          // Emit login data
          e.$emit("newLoginPage", {
            Ret: ret && ret[1],
            SKey: skey && skey[1],
            Sid: wxsid && wxsid[1],
            Uin: wxuin && wxuin[1],
            Passticket: passTicket && passTicket[1],
            Code: script
          });
        }
      });
      break;
    case 201:
      // QR scanned but not confirmed
      e.isScan = true;
      t.checkLogin(e.uuid).then(o, function () { window.checkLoginPromise && (e.isBrokenNetwork = true); });
      break;
    case 408:
      // Scan timeout, continue polling
      t.checkLogin(e.uuid).then(o, function () { window.checkLoginPromise && (e.isBrokenNetwork = true); });
      break;
    case 400:
    case 500:
    case 0:
      // Retry logic for network errors
      var refreshTimes = a.getCookie("refreshTimes") || 0;
      if (refreshTimes < 5) {
        refreshTimes++;
        a.setCookie("refreshTimes", refreshTimes, .5);
        document.location.reload();
      } else {
        e.isNeedRefresh = true;
      }
      break;
    case 202:
      // Already authorized
      e.isScan = false;
      e.isAssociationLogin = false;
      a.setCookie("login_frequency", 0, 2);
      window.checkLoginPromise && (window.checkLoginPromise.abort(), window.checkLoginPromise = null);
      r();
      break;
    default:
      break;
  }
  e.code = c.code;
  e.userAvatar = c.userAvatar;
  a.log("get code", c.code);
}

4.3 Summary

WeChat's web QR login uses JSONP for cross‑origin polling. The server blocks the request until the scan status changes, reducing unnecessary front‑end polling.

For more details on JSONP, see: http://www.52im.net/thread-1038-1-1.html
For an in‑depth discussion of the blocking‑polling technique, see: http://www.52im.net/thread-338-1-1.html

5. Article Summary

QR code login is now common not only in IM applications but also in many web sites with mobile components. The principles described here are applicable to a wide range of scenarios, including native desktop clients where cross‑origin issues do not arise.

If you are unfamiliar with real‑time web communication techniques such as long‑polling, you may want to study related materials on web instant messaging.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TaobaoredisWeChatWeb Authenticationlong pollingQR login
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.