How WeChat Open Platform OAuth Login Works in Mini-Shop Server: A Complete Integration Guide
The Mini-Shop server implements WeChat Open Platform OAuth login through a three-step flow: generating an authorization URL, handling the WeChat redirect with a temporary code, and exchanging that code for an access token and user profile before issuing a JWT.
The Mini-Shop server (allen7d/mini-shop-server) provides a complete integration with the WeChat Open Platform OAuth login system, enabling users to authenticate via WeChat QR codes. This implementation follows the standard OAuth 2.0 authorization code flow, handling URL generation, token exchange, and user data retrieval through dedicated service modules.
Step 1: Generate the WeChat Authorization URL
The WeChat Open Platform OAuth login process begins when the front-end requests a redirect URL from the server. The endpoint GET /v1/token/open_redirect_url in app/api/v1/token.py returns a pre-configured authorization URL:
# app/api/v1/token.py (line 51-52)
return Success(data={'redirect_url': current_app.config['OPEN_AUTHORIZE_URL']})
The authorization URL is constructed in app/config/secure.py using the WeChat Open Platform endpoints:
# app/config/secure.py (line 29-31)
OPEN_AUTHORIZE_URL = (
'https://open.weixin.qq.com/connect/oauth2/authorize?'
'appid={0}&redirect_uri={1}&response_type=code&'
'scope={2}&state={3}#wechat_redirect'
).format(
OPEN_APP_ID, # WeChat Open Platform AppID
OPEN_APP_SECRET, # Encoded redirect URI placeholder
OPEN_SCOPE, # Usually "snsapi_login"
OPEN_STATE # CSRF protection string
)
The front-end uses this URL to open the WeChat QR-code scan page, where the user scans and authorizes the application.
Step 2: Handle the OAuth Callback and Extract the Code
After the user grants permission, WeChat redirects to the REDIRECT_URI configured in app/config/secure.py:
# app/config/secure.py (line 38)
REDIRECT_URI = 'https%3a%2f%2fapi.ivinetrue.com%2ftoken%2fuser'
WeChat appends a temporary authorization code and the state parameter to this URL:
GET https://api.ivinetrue.com/token/user?code=AUTH_CODE&state=3d6be0a4035d839573b04816624a415e
The server extracts this code and initiates the token exchange process to complete the WeChat Open Platform OAuth login.
Step 3: Exchange the Code for Access Token and User Info
The core logic resides in app/service/open_token.py, which orchestrates the exchange of the temporary code for a WeChat access token and subsequent user profile retrieval.
Fetching the Access Token
The service constructs the access token request URL using configuration from app/config/secure.py:
# app/service/open_token.py (line 25-27)
access_token_url = current_app.config['OPEN_ACCESS_TOKEN_URL'].format(
current_app.config['OPEN_APP_ID'],
current_app.config['OPEN_APP_SECRET'],
code # The code received from the redirect
)
The OPEN_ACCESS_TOKEN_URL template is defined in app/config/secure.py:
# app/config/secure.py (line 32)
OPEN_ACCESS_TOKEN_URL = (
'https://api.weixin.qq.com/sns/oauth2/access_token?'
'appid={0}&secret={1}&code={2}&grant_type=authorization_code'
)
The server receives a JSON response containing:
{
"access_token": "...",
"expires_in": 7200,
"refresh_token": "...",
"openid": "USER_OPENID",
"scope": "snsapi_login"
}
Retrieving User Profile Data
Using the access_token and openid, the service fetches the user's WeChat profile:
# app/service/open_token.py (line 29-30)
user_info_url = current_app.config['OPEN_USER_INFO_URL'].format(
access_token,
openid
)
The user info endpoint is configured in app/config/secure.py:
# app/config/secure.py (line 33)
OPEN_USER_INFO_URL = (
'https://api.weixin.qq.com/sns/userinfo?'
'access_token={0}&openid={1}&lang=zh_CN'
)
This returns the user's nickname, avatar URL, gender, and other profile details.
Creating the Mini-Shop JWT
The obtained WeChat user data is mapped to a Mini-Shop User record (created if it doesn't exist). Finally, LoginVerifyService.get_token() generates a signed JWT that the front-end stores for authenticated API requests.
Code Example: Complete Front-End Integration
import requests
# 1️⃣ Get the QR-code redirect URL from the server
resp = requests.get('https://api.ivinetrue.com/v1/token/open_redirect_url')
redirect_url = resp.json()['data']['redirect_url']
# 2️⃣ Open the URL in a browser or QR-code widget
# ... user scans, WeChat redirects back to your callback endpoint ...
# 3️⃣ Your callback endpoint receives `code` and calls the server to finish login
def wechat_callback(request):
code = request.args.get('code')
# Send the `code` to the server endpoint that finishes the login
token_resp = requests.post(
'https://api.ivinetrue.com/v1/token',
json={'type': 201, 'code': code} # type 201 = WeChat scan login
)
jwt = token_resp.json()['data']['access_token']
# Store `jwt` for authenticated requests
Key Files in the WeChat OAuth Integration
| File | Purpose |
|---|---|
app/config/secure.py |
Contains all WeChat OAuth constants: OPEN_APP_ID, OPEN_APP_SECRET, OPEN_AUTHORIZE_URL, OPEN_ACCESS_TOKEN_URL, OPEN_USER_INFO_URL, and REDIRECT_URI. |
app/api/v1/token.py |
Exposes /open_redirect_url endpoint that front-end uses to initiate the flow. |
app/service/open_token.py |
Implements the code → access-token → user-info exchange logic. |
app/service/login_verify.py |
Wraps the token-creation logic for all login types, including WeChat Open Platform (type 201). |
Summary
- WeChat Open Platform OAuth login in Mini-Shop server follows the standard authorization code flow through three distinct steps: URL generation, callback handling, and token exchange.
- Configuration is centralized in
app/config/secure.py, defining all WeChat endpoints, credentials, and the redirect URI. - Token exchange logic resides in
app/service/open_token.py, which converts the temporary code into a WeChat access token and retrieves user profile data. - Authentication completion uses
LoginVerifyService.get_token()to issue a Mini-Shop JWT after mapping the WeChat OpenID to a local user record.
Frequently Asked Questions
What is the purpose of the state parameter in the WeChat OAuth URL?
The state parameter acts as a CSRF protection mechanism. Defined in app/config/secure.py as OPEN_STATE, this random string is sent to WeChat and returned unchanged in the redirect URI. The server validates that the returned state matches the original to prevent cross-site request forgery attacks during the WeChat Open Platform OAuth login process.
How does the server handle the temporary authorization code from WeChat?
When WeChat redirects to the REDIRECT_URI configured in app/config/secure.py, it appends a code query parameter. The server extracts this code and passes it to app/service/open_token.py, which constructs the OPEN_ACCESS_TOKEN_URL by formatting the code with OPEN_APP_ID and OPEN_APP_SECRET. A GET request to this URL exchanges the temporary code for a permanent access token and the user's OpenID.
What user information does the server retrieve from WeChat?
After obtaining the access token, the server calls the OPEN_USER_INFO_URL endpoint defined in app/config/secure.py. This request returns the user's nickname, avatar URL, gender, country, province, and city. The server uses this data to either locate an existing user record or create a new one in the Mini-Shop database, mapping the WeChat OpenID to the internal user ID.
Where is the JWT token generated in the WeChat login flow?
The JWT token is generated by LoginVerifyService.get_token() in app/service/login_verify.py after the WeChat user profile has been successfully retrieved and mapped to a local user record. This service handles all authentication types, including WeChat Open Platform login (identified as type 201), and returns a signed JWT that the client uses for subsequent authenticated API requests to the Mini-Shop server.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →