Saltar para o conteúdo principal

How to Configure WeChat OAuth Authentication for Captive Portals

Este guia técnico explica como configurar a autenticação OAuth do WeChat para captive portals. Detalha os registos de plataforma necessários, o fluxo OAuth 2.0, a seleção de scope e os mecanismos de aplicação de rede necessários para capturar dados primários de visitantes chineses de forma segura.

📖 4 min de leitura📝 815 palavras🔧 2 exemplos práticos3 perguntas de prática📚 8 definições principais

Ouça este guia

Ver transcrição do podcast
HOW TO CONFIGURE WECHAT OAUTH AUTHENTICATION FOR CAPTIVE PORTALS A Purple Technical Briefing - Approximately 10 Minutes --- INTRODUCTION AND CONTEXT (approximately 1 minute) Welcome. If you are responsible for guest WiFi at a hotel, retail chain, stadium, or conference centre that serves Chinese visitors, this briefing is for you. WeChat has 1.38 billion monthly active users, according to Tencent's 2024 data. The overwhelming majority are in China, but the platform has a meaningful international footprint too - four million users in the United States, 12 million in Malaysia, and growing numbers across Southeast Asia, Europe, and the Middle East. When a Chinese guest connects to your WiFi and sees a login page with only email, Facebook, or a voucher code, they face immediate friction. They may not have a local email address set up on that device. They almost certainly have WeChat. So the question is not whether you should offer WeChat login - it is how you configure it correctly, securely, and in a way that generates first-party data you can actually use. That is what we are going to cover today. We will walk through the OAuth 2.0 flow, the two platform registrations you need, the scope decision that determines what data you collect, the network-side enforcement mechanism, and the compliance considerations that matter in 2026. --- TECHNICAL DEEP-DIVE (approximately 5 minutes) Let us start with the architecture. A captive portal intercepts HTTP traffic from an unauthenticated device and redirects it to a login page. That login page is hosted on a portal server - either on-premises or in the cloud. When you add WeChat OAuth, you are inserting a third-party identity provider into that flow. Here is the sequence. The guest connects to your SSID. The access point or wireless controller detects that the device has no authenticated session and redirects all HTTP traffic to your captive portal URL. The portal page loads and presents login options - including WeChat. The guest taps WeChat login. Your portal server redirects the browser to WeChat's authorisation endpoint at open.weixin.qq.com, passing your AppID, the redirect URI, the response type of code, and the scope. WeChat handles the authentication entirely on its own servers. If the guest is already logged into WeChat in their browser, they see a consent screen. If they are using the WeChat in-app browser, the experience can be silent with snsapi_base scope - no consent prompt at all. WeChat then redirects back to your portal's redirect URI with a temporary authorisation code. Your portal server exchanges that code for an access token by calling api.weixin.qq.com/sns/oauth2/access_token, passing your AppID, AppSecret, the code, and grant type of authorization_code. WeChat returns an access token, a refresh token, the user's OpenID, and the scope granted. If you requested snsapi_userinfo scope, you can then make a second API call to retrieve the user's nickname, avatar, gender, and city. Now, the two platform registrations. This is where most implementations go wrong. WeChat has two separate developer platforms. The WeChat Open Platform at open.weixin.qq.com handles website applications and mobile apps. The WeChat Official Accounts Platform at mp.weixin.qq.com handles public accounts - what most venues actually need. For a captive portal serving guests inside the WeChat in-app browser, you need a Service Account on the Official Accounts Platform. A Subscription Account will not work - it does not have OAuth web page authorisation permissions. A Service Account does, and it supports both snsapi_base and snsapi_userinfo scopes. For a captive portal accessed from a standard mobile browser outside WeChat - Chrome on Android, Safari on iOS - you need a Website Application registered on the Open Platform. This uses snsapi_login scope and presents a QR code that the user scans with their WeChat app. In practice, most venue deployments use both. A guest on a hotel's WiFi might open the portal in Chrome, see a QR code, scan it with WeChat, and authenticate. Or they might follow a link in WeChat itself, land in the in-app browser, and authenticate silently with snsapi_base. Let us talk about scope selection, because this is a genuine decision point. snsapi_base returns only the OpenID - a unique identifier for that user within your Official Account. It requires no user consent prompt. The authentication is invisible to the user. This is ideal for returning guests you have already profiled, or for venues where you want zero friction at the cost of zero new data. snsapi_userinfo returns the OpenID plus the user's WeChat nickname, profile picture, gender, language setting, and city. It requires an explicit consent screen. The user sees a prompt asking whether they allow your Official Account to access their information. Most users accept, but there is friction. The right choice depends on your use case. For a first-time guest registration where you want to build a profile, use snsapi_userinfo and pair it with a GDPR-compliant consent layer on your portal page. For a returning guest who has already consented and whose profile you already hold, use snsapi_base for silent re-authentication. Now, the network enforcement side. Getting an OAuth token proves identity, but it does not automatically open the network. You need a mechanism to translate a successful authentication into network access. The two standard approaches are RADIUS Change of Authorisation, defined in RFC 3576, and MAC address bypass. With RADIUS CoA, your portal server sends a CoA request to the network controller after successful OAuth, and the controller moves the device from the unauthenticated VLAN to the guest VLAN. This works with Cisco Meraki, HPE Aruba, Ruckus, Juniper Mist, and most enterprise-grade controllers. With MAC bypass, the portal server registers the device's MAC address as an authorised client, and the controller allows it. MAC bypass is simpler to implement but less secure, because MAC addresses can be spoofed. Purple's Guest WiFi platform handles both mechanisms. After WeChat OAuth completes, Purple's cloud overlay sends the appropriate signal to the underlying hardware - whether that is Cisco Meraki, HPE Aruba, Ruckus, Juniper Mist, Ubiquiti UniFi, Cambium, Extreme, or Fortinet. The venue operator does not need to manage that translation manually. --- IMPLEMENTATION RECOMMENDATIONS AND PITFALLS (approximately 2 minutes) Let me give you the five things that cause WeChat OAuth captive portal implementations to fail. First: the redirect URI mismatch. WeChat validates the redirect URI against the authorised domain you registered on the platform. If your portal server uses a different subdomain, a different path, or HTTP instead of HTTPS, the OAuth flow fails with error 40029 - invalid code. Register every domain variant you use, including staging environments. Second: the AppSecret on the client side. Your AppSecret must never appear in client-side JavaScript or in a mobile app binary. It belongs on your server. If it is exposed, anyone can impersonate your application and call WeChat's APIs on your behalf. Third: missing CSRF protection. The state parameter in the OAuth request exists specifically to prevent cross-site request forgery. Generate a cryptographically random state value, store it in the user's session, and validate it when WeChat redirects back. Skip this and you have a real vulnerability. Fourth: the in-app browser detection gap. WeChat's in-app browser sets a specific user agent string containing "MicroMessenger". If your portal does not detect this and serve the correct OAuth flow - Official Account flow for in-app browser, Open Platform QR flow for standard browsers - users get a broken experience or an error. Fifth: GDPR and PIPL alignment. If you serve European visitors, GDPR applies to the data you collect via WeChat OAuth. If you serve Chinese visitors, China's Personal Information Protection Law - PIPL - applies to how you process their data. Both require a lawful basis for processing, clear purpose limitation, and data minimisation. snsapi_base is easier to justify under data minimisation principles than snsapi_userinfo. Whatever you collect, document your legal basis and your retention period. --- RAPID-FIRE Q AND A (approximately 1 minute) Question: Can I use WeChat login on a portal that also offers email and SMS login? Yes. Most enterprise portal platforms, including Purple, support multiple authentication methods on the same portal page. WeChat appears as one option alongside others. Question: Does WeChat OAuth work on iOS? Yes, but with a nuance. Apple's App Tracking Transparency framework does not affect server-side OAuth flows. WeChat login in Safari on iOS works via the QR code flow or redirect flow. The WeChat app itself handles the authentication. Question: What happens if WeChat's API is unavailable? Your portal should implement a fallback. If the WeChat API call times out or returns an error, redirect the user to an alternative login method. Do not leave them with a blank screen. Question: Can I use the OpenID as a persistent customer identifier? Within your Official Account, yes. The OpenID is stable for a given user and a given Official Account. If you have multiple Official Accounts, the same user will have different OpenIDs across them. For cross-account identity resolution, WeChat provides a UnionID, which requires your accounts to be linked on the Open Platform. --- SUMMARY AND NEXT STEPS (approximately 1 minute) To summarise. WeChat OAuth authentication for captive portals is a two-platform registration exercise, a scope decision, a network enforcement integration, and a compliance review. Get those four things right and you have a login method that serves over a billion potential visitors with zero password friction. The practical next steps are these. First, determine whether your visitors encounter the portal inside the WeChat in-app browser or in a standard mobile browser - that determines which platform registration you need. Second, decide on scope - snsapi_base for returning guests, snsapi_userinfo for first-time registration with consent. Third, confirm your network hardware supports RADIUS CoA or configure MAC bypass as an alternative. Fourth, review your privacy notice and consent flow against GDPR and PIPL requirements. Fifth, test the redirect URI, the state parameter validation, and the in-app browser detection before you go live. If you want to see how Purple handles WeChat OAuth as part of a broader Guest WiFi and analytics platform - across 80,000 venues and 440 million logins in 2024 - visit purple.ai or speak to your account team. Thanks for listening. --- END OF SCRIPT

header_image.png

Resumo Executivo

Quando os visitantes chineses se ligam ao seu WiFi, apresentar uma página de início de sessão apenas com e-mail ou Facebook cria uma fricção imediata. O WeChat tem 1,38 mil milhões de utilizadores ativos mensais, e configurá-lo como fornecedor de identidade elimina esta barreira. Este guia explica como implementar a autenticação OAuth 2.0 do WeChat para captive portals, detalhando os registos de plataforma necessários, o fluxo OAuth e os mecanismos de aplicação de rede necessários para traduzir um início de sessão bem-sucedido em acesso à rede. Abordamos a implementação técnica em hardware empresarial e os requisitos de conformidade ao abrigo do GDPR e da PIPL.

Arquitetura Técnica

Um captive portal interceta o tráfego HTTP de um dispositivo não autenticado e redireciona-o para uma página de início de sessão alojada num servidor de portal. Ao integrar o OAuth do WeChat, insere um fornecedor de identidade de terceiros neste fluxo.

architecture_overview.png

A sequência funciona da seguinte forma:

  1. O visitante liga-se ao SSID.
  2. O ponto de acesso ou controlador sem fios deteta a falta de uma sessão autenticada e redireciona o tráfego HTTP para o URL do captive portal.
  3. O visitante seleciona o início de sessão do WeChat.
  4. O servidor do portal redireciona o navegador para o endpoint de autorização do WeChat (open.weixin.qq.com), transmitindo o AppID, redirect_uri, response_type=code e scope.
  5. O WeChat processa a autenticação. Se o visitante utilizar o navegador interno da aplicação WeChat com o scope snsapi_base, isto ocorre de forma silenciosa.
  6. O WeChat redireciona de volta para o redirect_uri do portal com um código de autorização temporário.
  7. O servidor do portal troca este código por um token de acesso ao chamar api.weixin.qq.com/sns/oauth2/access_token.
  8. O WeChat devolve um access_token, refresh_token e o openid do utilizador.

Requisitos de Registo na Plataforma

A implementação do início de sessão do WeChat requer o registo na plataforma de programadores correta. O WeChat opera duas plataformas distintas, e selecionar a errada fará com que a integração falhe.

Plataforma de Contas Oficiais do WeChat

Para um captive portal que serve visitantes dentro do navegador interno da aplicação WeChat, necessita de uma Conta de Serviço (Service Account) na Plataforma de Contas Oficiais (mp.weixin.qq.com). Uma Conta de Subscrição (Subscription Account) não tem as permissões de autorização de página web OAuth necessárias. Uma Conta de Serviço suporta os scopes snsapi_base e snsapi_userinfo.

Plataforma Aberta do WeChat

Para um captive portal acedido a partir de um navegador móvel padrão fora do WeChat (como o Chrome em Android ou o Safari em iOS), necessita de uma Aplicação Web (Website Application) registada na Plataforma Aberta (open.weixin.qq.com). Esta utiliza o scope snsapi_login e apresenta um código QR que o utilizador digitaliza com a sua aplicação WeChat.

A maioria das implementações empresariais requer ambos os registos para abranger todos os métodos de acesso.

Seleção de Scope e Recolha de Dados

O parâmetro scope determina quais os dados que o WeChat devolve ao seu servidor de portal. Esta decisão tem impacto tanto na fricção do utilizador como na conformidade com a privacidade de dados.

scope_comparison_chart.png

snsapi_base

Este scope devolve apenas o OpenID, um identificador único para o utilizador dentro da sua Conta Oficial. Não requer qualquer pedido de consentimento do utilizador, tornando a autenticação invisível para o mesmo. Isto é ideal para visitantes recorrentes dos quais já possui um perfil, ou para locais que priorizam a ausência de fricção em detrimento da recolha de novos dados.

snsapi_userinfo

Este scope devolve o OpenID mais a alcunha (nickname) do WeChat do utilizador, a foto de perfil, o género, a definição de idioma e a cidade. Requer um ecrã de consentimento explícito, introduzindo fricção. Utilize isto para o registo de visitantes pela primeira vez, onde a criação de um perfil é necessária, combinado com uma camada de consentimento em conformidade com o GDPR.

Integração de Aplicação de Rede

A aquisição de um token OAuth prova a identidade, mas não abre a rede. Deve traduzir uma autenticação bem-sucedida em acesso à rede utilizando protocolos padrão.

RADIUS Change of Authorisation (CoA)

Definido em IEEE 802.1X e RFC 3576, o RADIUS CoA permite que o servidor do portal envie um pedido ao controlador de rede após um OAuth bem-sucedido. O controlador move então o dispositivo da VLAN não autenticada para a VLAN de convidados. Este é o padrão para hardware empresarial, incluindo Cisco Meraki, HPE Aruba, Ruckus e Juniper Mist.

MAC Address Bypass

Alternativamente, o servidor do portal regista o endereço MAC do dispositivo como um cliente autorizado, e o controlador permite-o. Embora seja mais simples de implementar, é menos seguro, uma vez que os endereços MAC podem ser falsificados.

A sobreposição de nuvem da Purple automatiza esta tradução, enviando o sinal apropriado para o hardware subjacente (incluindo Ubiquiti UniFi, Cambium, Extreme e Fortinet) assim que o OAuth do WeChat for concluído.

Considerações de Conformidade e Segurança

Alinhamento com o GDPR e a PIPL

Se serve visitantes europeus, o GDPR aplica-se aos dados recolhidos através do OAuth do WeChat. Se serve visitantes chineses, aplica-se a Lei de Proteção de Informações Pessoais (PIPL) da China. Ambas as estruturas exigem uma base legal para o processamento, limitação clara da finalidade e minimização de dados. O scope snsapi_base alinha-se mais facilmente com os princípios de minimização de dados do que o snsapi_userinfo.

Proteção CSRF

O parâmetro state no pedido OAuth previneevita cross-site request forgery. Deve gerar um valor de estado criptograficamente aleatório, armazená-lo na sessão do utilizador e validá-lo quando o WeChat redirecionar de volta.

Validação do URI de Redirecionamento

O WeChat valida o redirect_uri em relação ao domínio autorizado registado na plataforma. Se o servidor do seu portal utilizar um subdomínio, caminho ou HTTP diferente em vez de HTTPS, o fluxo OAuth falha com o erro 40029.

Para mais informações sobre como proteger a sua rede, consulte o nosso Segurança de WiFi Empresarial: Um Guia Completo para 2026 .

Definições Principais

snsapi_base

A WeChat OAuth scope that returns only the user's OpenID without displaying a consent prompt.

Used when IT teams need to authenticate returning visitors silently without causing login friction.

snsapi_userinfo

A WeChat OAuth scope that returns the OpenID along with demographic data (nickname, gender, city) and requires explicit user consent.

Used during first-time registration when marketing teams need to build a visitor profile.

OpenID

A unique identifier for a specific user within a specific WeChat Official Account.

Used as the primary key in the portal database to track visitor behaviour and return visits.

RADIUS CoA

Change of Authorisation. A mechanism defined in RFC 3576 that allows a server to modify the authorisation state of an active session.

Used by the portal server to tell the wireless controller to grant network access after successful WeChat authentication.

PIPL

Personal Information Protection Law. China's comprehensive data privacy regulation.

Must be considered alongside GDPR when designing the consent flow for Chinese visitors using WeChat login.

AppID and AppSecret

The credentials provided by WeChat to identify and authenticate your application.

The AppSecret must remain securely on the portal server and never be exposed in client-side code.

State Parameter

A cryptographically random string passed in the OAuth request and validated upon return.

Essential for preventing Cross-Site Request Forgery (CSRF) attacks on the captive portal.

MAC Address Bypass

A method of granting network access by authorising the device's hardware address rather than requiring 802.1X authentication.

An alternative to RADIUS CoA for simpler network setups, though less secure.

Exemplos Práticos

A luxury retail brand in London wants to offer WeChat login for Chinese shoppers. They want to collect demographic data to understand their customer base, but they are concerned about GDPR compliance and high drop-off rates at the portal.

The retailer should register a Service Account on the WeChat Official Accounts Platform. They must configure the portal to use the snsapi_userinfo scope for first-time connections to gather demographic data (nickname, gender, city). To ensure GDPR compliance, the portal page must display a clear, conscious-choice opt-in before the WeChat redirect, explaining exactly what data is collected and why. For returning shoppers, the portal should detect the MAC address and use snsapi_base for silent re-authentication, minimising friction.

Comentário do Examinador: This approach balances data collection with user experience. By limiting the high-friction `snsapi_userinfo` flow to the first visit and using `snsapi_base` subsequently, the retailer maximises conversion while remaining compliant with data minimisation principles.

A stadium deploys a new WiFi network using HPE Aruba controllers. They have configured WeChat OAuth, and the portal successfully receives the access token, but the visitor's device remains on the captive portal page and cannot access the internet.

The integration lacks a network enforcement mechanism. The portal server has verified the user's identity with WeChat, but it has not instructed the HPE Aruba controller to grant access. The portal server must be configured to send a RADIUS Change of Authorisation (CoA) message to the controller, instructing it to transition the user's MAC address from the pre-authentication role to the authenticated guest role.

Comentário do Examinador: This highlights the distinction between identity verification and network access control. Enterprise networks require a protocol like RADIUS CoA to bridge the gap between the web application (portal) and the network infrastructure.

Perguntas de Prática

Q1. You are deploying a captive portal across a retail chain. Testing shows that users opening the portal in Safari on iOS receive an error when selecting WeChat login, but users opening the portal from within a WeChat message link authenticate successfully. What is the likely cause?

Dica: Consider the difference between the WeChat in-app browser and standard mobile browsers.

Ver resposta modelo

The implementation is likely relying solely on a Service Account registered on the Official Accounts Platform, which only supports OAuth within the WeChat in-app browser. To support Safari on iOS, you must also register a Website Application on the WeChat Open Platform and implement user agent detection to route Safari users to the QR code flow.

Q2. Your portal server logs show frequent 40029 'invalid code' errors returning from the WeChat API during the access token exchange. What configuration should you check first?

Dica: Think about how WeChat validates the source of the authentication request.

Ver resposta modelo

You should verify the redirect_uri configuration. WeChat strictly validates the redirect URI against the authorised domain registered in the developer console. If the portal is using a different subdomain, or if it drops HTTPS, WeChat will reject the code exchange.

Q3. A venue operator wants to collect visitor data but insists on zero friction during the login process. They request that you configure WeChat login to collect the visitor's nickname and city without showing a consent prompt. How do you respond?

Dica: Review the capabilities of the different OAuth scopes.

Ver resposta modelo

You must inform the operator that this is technically impossible. Collecting demographic data like nickname and city requires the snsapi_userinfo scope, which mandatorily triggers a WeChat consent prompt. To achieve zero friction, you must use snsapi_base, which operates silently but only returns the OpenID.

Continue a ler esta série

How to Set Up a Captive Portal on Starlink: A Guide for Remote & Maritime Venues

Este guia detalha como contornar o hardware nativo da Starlink e integrar um captive portal gerido na cloud utilizando equipamento de encaminhamento empresarial. Irá aprender a superar a limitação de CGNAT, impor a segmentação de VLAN, gerir as restrições de largura de banda de satélite e garantir a conformidade regulamentar.

Ler o guia →

Hotel Guest WiFi Management: Integrating PMS, Portals, and Brand Standards

Este guia técnico detalha como arquitetar redes WiFi de hotéis de nível empresarial, focando-se na segmentação de VLAN, integração de PMS para gestão automatizada de sessões e otimização de captive portal para captura de dados em conformidade com o GDPR.

Ler o guia →

Captive Portal Best Practices: Designing for High Conversion and Compliance

Este guia técnico oferece aos gestores de TI, arquitetos de rede e diretores de operações de espaços um plano completo para implementar captive portals que equilibram a segurança da rede com uma elevada conversão de utilizadores. Abrange toda a arquitetura, desde a segmentação de VLAN e autenticação RADIUS até ao design de consentimento em conformidade com o GDPR e à seleção do método de autenticação. Baseado na experiência operacional da Purple em mais de 80.000 espaços e 440 milhões de inícios de sessão em 2024, cada recomendação é fundamentada em dados reais de implementação.

Ler o guia →