Frontend Development 10 min read

A Front‑End Developer’s Guide to Integrating WeChat QR‑Code Login

This step‑by‑step tutorial walks front‑end developers through the entire process of integrating WeChat QR‑code login, covering prerequisite checklist, platform setup, core JavaScript SDK usage, callback handling, common pitfalls, security hardening, performance tweaks, debugging tricks, and a learning roadmap.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
A Front‑End Developer’s Guide to Integrating WeChat QR‑Code Login

1. Preparation: Checklist to Avoid Detours

1. Required Materials

WeChat Open Platform account (personal or enterprise; enterprise must be verified)

Website domain (must be ICP‑recorded; for testing you can use localhost but it has restrictions)

Server IP whitelist (configured in the Open Platform)

300 CNY certification fee (required for enterprise accounts, optional for personal developers)

💡 Lesson: I once discovered at 2 AM that login failed because the test environment IP was not added to the whitelist.

2. Create the Website “ID Card”

Log in to the WeChat Open Platform .

Navigate to Website Applications → Create Website Application .

Fill in the required fields, e.g.: Application Name: My Awesome Site Domain: www.yourdomain.com Callback URL: www.yourdomain.com/auth/wechat

2. Development Practice: Front‑End Code Journey

1. Include the Official JS‑SDK (Pitfall Warning)

<!-- Official recommendation -->
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

<!-- My improved version (avoids CDN failure) -->
<script>
  function loadWXSDK() {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
      script.onload = resolve;
      script.onerror = () => reject(new Error('WeChat SDK load failed'));
      document.head.appendChild(script);
    });
  }
</script>

2. Initialize QR Login (with Safe Parameters)

async function initWechatLogin() {
  await loadWXSDK();

  new WxLogin({
    self_redirect: true, // true → automatic redirect, false → embed in iframe
    id: "wechat-login-container",
    appid: "YOUR_APPID", // not the public account ID!
    scope: "snsapi_login", // fixed value
    redirect_uri: encodeURIComponent("https://www.yourdomain.com/auth/wechat"),
    state: "random_csrf_string", // generate with UUID
    style: "black", // theme options
    href: "" // custom CSS URL (cross‑origin limits)
  });
}

3. Handle the Callback “Reef”

// Callback page logic
const parseAuthResponse = () => {
  const hash = window.location.hash.substr(1);
  const params = new URLSearchParams(hash);

  const accessToken = params.get('access_token');
  const expiresIn = params.get('expires_in');
  const state = params.get('state'); // must match the original

  if (!accessToken) {
    const errCode = params.get('error');
    showError(`Login failed: ${getErrorMsg(errCode)}`);
    return;
  }

  // Exchange token for user info (requires backend support)
  fetchUserInfo(accessToken);
};

// Common error‑code mapping
const getErrorMsg = (code) => {
  const errors = {
    10003: 'redirect_uri domain does not match backend config',
    10004: 'public account is banned',
    10005: 'requested scope not authorized'
  };
  return errors[code] || `Unknown error (code: ${code})`;
};

3. Night‑Owl Pitfalls

1. Domain Verification “Mystery”

Symptom: Configured www.domain.com but users accessing domain.com receive errors.

Solution: Normalize the domain on the front end:

// Front‑end canonical domain handling
const canonicalDomain = 'www.yourdomain.com';
if (location.host !== canonicalDomain) {
  window.location.href = `https://${canonicalDomain}${location.pathname}`;
}

2. Mobile “Ghost” Issue

Symptom: After scanning on a mobile browser, the page does not jump back.

Cause: WeChat blocks redirects to non‑whitelisted domains.

Solution: Detect mobile devices and fall back to a QR image with polling:

// Detect mobile and use fallback UI
if (/Mobile|Android|iPhone/i.test(navigator.userAgent)) {
  showQRCodeWithFallback(); // display QR with notice
  startPollingAuthResult(); // poll for login status
}

3. Style Customisation “Iron Wall”

Requirement: Change the QR‑code button appearance.

Reality: Direct styling of the WeChat widget is prohibited; use CSS tricks:

/* Scale the iframe QR code */
#wechat-login-container iframe {
  transform: scale(1.2);
  pointer-events: none;
}

/* Add a custom UI overlay */
.qr-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

4. Security Hardening: From Basics to Defense

1. State Parameter for CSRF Protection

// Generate a random state string
const generateState = () => {
  return [
    Date.now().toString(36),
    Math.random().toString(36).substr(2),
    window.crypto.getRandomValues(new Uint8Array(3))[0].toString(36)
  ].join('-');
};

// Validate state on callback
const isValidState = (receivedState) => {
  const savedState = sessionStorage.getItem('wx_state');
  return receivedState === savedState;
};

2. Token Secure Handling

// Proper token handling
const handleToken = (token) => {
  // 1. Remove token from URL
  window.history.replaceState({}, '', window.location.pathname);

  // 2. Store in HttpOnly cookie
  document.cookie = `auth_token=${token}; Path=/; Secure; SameSite=Strict`;

  // 3. Prevent XSS leakage
  window.__PRIVATE_TOKEN__ = undefined;
};

5. Performance Optimisation

1. Lazy‑Load Strategy

// Load the auth module only after user clicks login
document.getElementById('wechat-login-btn').addEventListener('click', () => {
  import('./wechatAuth.js').then(module => {
    module.initWechatLogin();
  });
}, { once: true });

2. Multi‑Instance Issue Resolution

// Prevent duplicate initialisation
let wxLoginInstance = null;

function safeInitWechatLogin() {
  if (!wxLoginInstance) {
    wxLoginInstance = new WxLogin({/* configuration */});
  }
  return wxLoginInstance;
}

6. Ultimate Debugging Tricks

1. Local Development Work‑Around

# Edit /etc/hosts
127.0.0.1   test.yourdomain.com
// Development‑only tweaks
if (process.env.NODE_ENV === 'development') {
  window.__wxjs_is_wkwebview = true; // fixes iOS debugging issue
}

2. Real‑Device Debugging Tools

WeChat Developer Tools : Simulate the QR‑code login flow.

Charles Proxy : Inspect the redirect chain.

Eruda : Mobile console debugging.

7. My Learning Roadmap

WeChat Open Platform documentation (read three times).

OAuth 2.0 protocol (understand the underlying mechanics).

SameSite Cookie deep‑dive (solve cross‑origin issues).

Final advice: always have a Plan B . When WeChat services hiccuped on launch day, I added a fallback of "account + password + SMS verification" and avoided a major outage. Users notice only that the site is broken, not which API failed.

For more AI‑coding news, visit the AI Coding section: https://juejin.cn/aicoding
debuggingperformanceFront-endsecurityWeChat LoginOAuth
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login 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.