Integrating WeChat Mini Program Login Using Python
Authentication Protocol Overview
Secure access for WeChat Mini Programs relies on a handshake mechanism where the client obtains a temporary credential and exchanges it via a custom backend. This proces involves coordinating JavaScript logic on the client side with a Python server to validate user identity and establish a session.
Client-Side Implementation
The mini program initiates the process by invoking the login API. Upon receiving a successful resposne containing a code, the application transmits this data to the developer's server for verification.
// Mini Program Page Logic
Page({
state: {},
triggerAuthentication: function () {
wx.login({
success: this.handleCredentialSuccess,
fail: this.handleAuthError,
});
},
handleCredentialSuccess: function (response) {
if (response && response.code) {
const tempCode = response.code;
this.forwardCredentialToBackend(tempCode);
} else {
console.error('Login failed', response.errMsg);
}
},
forwardCredentialToBackend: function (code) {
wx.request({
url: 'https://api.domain.com/v1/verify',
method: 'POST',
data: {
jsCode: code,
appId: CONFIG_ID,
},
success: this.processServerResponse,
fail: this.handleNetworkError,
});
},
});
If public profile data such as avatars or nicknames is required, the wx.getUserProfile interface should be called separately to request user authorization before transmitting details to the server.
Backend Verification Logic
The server exposes an endpoint to receive the temporary code. It then communicates with the WeChat authority server to swap the code for a unique user identifier and session key.
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
CLIENT_ID = 'your_app_id'
CLIENT_SECRET = 'your_app_secret'
AUTH_ENDPOINT = 'https://api.weixin.qq.com/sns/jscode2session'
@app.route('/v1/verify', methods=['POST'])
def validate_user_identity():
payload = request.get_json()
js_code = payload.get('jsCode')
# Exchange code with vendor API
vendor_response = exchange_code_for_session(js_code)
if not vendor_response or 'openid' not in vendor_response:
return jsonify({'error': 'Validation failed'}), 401
user_unique_id = vendor_response.get('openid')
session_token = create_secure_session_token()
# Save session to database
persist_session_data(user_unique_id, session_token)
return jsonify({'token': session_token}), 200
def exchange_code_for_session(code):
params = {
'appid': CLIENT_ID,
'secret': CLIENT_SECRET,
'js_code': code,
'grant_type': 'authorization_code'
}
response = requests.get(AUTH_ENDPOINT, params=params)
return response.json() if response.status_code == 200 else None
def create_secure_session_token():
# Generate random secure string
return 'secure_token_placeholder'
def persist_session_data(uid, token):
# Database logic to store user session
pass
Additional endpoints should be prepared to handle user profile updates, ensuring that any received information is linked correctly to the unique identifier generated during the initial verification step.