I. Overall Architecture
Scheme A: Direct Connection Mode (Default)
Scheme B: Reverse Proxy Mode (Recommended)
Core Principle: The frontend does not directly call WeChat API. All WeChat API calls are proxied through Supabase Edge Functions to avoid exposingAppSecret on the client side. Users can choose either direct connection mode or reverse proxy mode to solve the IP whitelist problem.
II. Prerequisites
2.1 WeChat Developer Platform Configuration
Complete the following operations on the WeChat Developer Platform:-
Obtain Developer Credentials
- Visit the WeChat Developer Platform
- Select the corresponding Official Account
- View or reset in “Basic Information”
- Record
AppID(Developer ID) - Record or reset
AppSecret(Developer Secret)
-
Configure IP Whitelist
- Add Edge Function egress IP in “Basic Information → Developer Secret → API IP Whitelist”
- ⚠️ Important: Supabase Edge Functions use dynamic IPs. The first call will return
errcode: 40164. Extract the IP from the error message and add it to the whitelist - Extraction method: Parse
invalid ip x.x.x.xfromerrmsg
-
Confirm Official Account Type
- Verified service accounts have full API permissions
- Subscription accounts have limited API access (e.g., custom menus, data statistics)
2.2 Supabase Project Configuration
-
Environment Variables / Edge Function Secrets
Configure the following Secrets (via Supabase Dashboard or CLI):
Secret Name Description Example SUPERUN_WECHAT_APP_IDOfficial Account AppID wx1234567890abcdefSUPERUN_WECHAT_APP_SECRETOfficial Account AppSecret a1b2c3d4e5f6...SUPERUN_WECHAT_API_PROXY_URLReverse proxy address (optional) https://wechat-proxy.example.comSUPABASE_URLSupabase project URL (built-in) https://xxxxx.supabase.coSUPABASE_ANON_KEYSupabase anonymous key (built-in) eyJhbG...SUPABASE_SERVICE_ROLE_KEYSupabase service role key (built-in) eyJhbG...SUPABASE_URL,SUPABASE_ANON_KEY, andSUPABASE_SERVICE_ROLE_KEYare built-in Supabase variables and do not need manual configuration.SUPERUN_WECHAT_API_PROXY_URLis optional. If not configured, it will directly connect to WeChat API (requires manual IP whitelist maintenance). If configured, all WeChat requests will go through the proxy server. -
Edge Function Configuration (
supabase/config.toml)verify_jwt = falseallows Edge Functions to call each other. Authentication logic is manually implemented by parsing JWT inside the function.
III. Database Table Structure
3.1 wechat_tokens — Token Cache Table
3.2 articles — Article Content Table
3.3 menu_configs — Menu Configuration Table
3.4 auto_reply_rules — Auto Reply Rules Table
IV. Edge Functions Details
4.1 wechat-token — Token Management Service
Responsibility: Obtain and cache WeChat access_token. All other Edge Functions get tokens by calling this service.
Request Method: GET or POST
Core Logic:
4.2 wechat-data — Data Statistics Service
Responsibility: Proxy WeChat data statistics interfaces (datacube) and follower / menu queries.
Request Method: POST
TokenResult Pattern (unified use for all functions requiring access_token):
Key Design: When token acquisition fails (e.g., IP blocked), do not throw an exception. Instead, return { blocked_ip } to the frontend for friendly display.
Supported actions:
| action | WeChat API | Description | Date Limit |
|---|---|---|---|
get-menu | GET /cgi-bin/menu/get | Get current menu | None |
get-follower-count | GET /cgi-bin/user/get | Get total followers | None |
user-summary | POST /datacube/getusersummary | User growth data | Max 7 days |
user-cumulate | POST /datacube/getusercumulate | Cumulative user data | Max 7 days |
article-summary | POST /datacube/getarticlesummary | Article broadcast daily data | Max 1 day |
article-total | POST /datacube/getarticletotal | Article broadcast total data | Max 1 day |
upstream-msg | POST /datacube/getupstreammsg | Message overview | Max 7 days |
interface-summary | POST /datacube/getinterfacesummary | Interface analysis | Max 30 days |
4.3 wechat-articles — Article Management Service
Responsibility: Article CRUD, publish to WeChat, sync published articles from WeChat.
Supported actions:
| action | Description | Requires Authentication |
|---|---|---|
save-draft | Save / update draft | ✅ |
publish | Publish to WeChat (draft → broadcast) | ✅ |
delete | Soft delete article | ✅ |
sync-published | Sync published articles from WeChat | ✅ |
4.4 wechat-menu — Custom Menu Service
Responsibility: Sync local menu configuration to WeChat, clear WeChat menu.
Supported actions:
| action | Description | Parameters |
|---|---|---|
publish | Publish menu to WeChat | menu_config_id (required) |
delete | Clear WeChat menu | menu_config_id (optional) |
publish finds an empty menu (button.length === 0), automatically call the delete interface to clear the WeChat menu instead of creating an empty menu.
Menu Data Structure (WeChat standard format):
V. Frontend Integration Patterns
5.1 Unified Hook Encapsulation
All WeChat API calls are encapsulated as React Query hooks:5.2 IP Whitelist Error Handling (Common Pattern)
All pages interacting with WeChat implement unified IP whitelist error handling:5.3 Manual Sync (Connectivity Check)
VI. Key Considerations
6.1 IP Whitelist Problem — Two Solutions
Supabase Edge Functions use dynamic egress IPs and cannot pre-configure whitelists. Users can choose either of the following solutions based on their situation:Scheme A: IP Whitelist (Manual Maintenance)
Suitable for: Quick verification, temporary use, no server resources. Steps:- First WeChat API call will return
errcode: 40164 - Extract the rejected IP from
errmsg:invalid ip x.x.x.x - Add this IP to the Official Account whitelist
- The application frontend will display an orange alert bar with one-click IP copy
- Edge Function IP may change, requiring re-addition
- Requires manual operation in WeChat backend
Scheme B: Reverse Proxy (Recommended, One-Time Setup)
Suitable for: Production environment, long-term use, don’t want to manually add whitelist every time IP changes. Principle: Deploy an Nginx reverse proxy on a server with a fixed public IP. All WeChat API requests are forwarded through this server. WeChat only sees the proxy server’s fixed IP, so adding it to the whitelist once makes it permanent. Step 1: Deploy Proxy Server Prepare a server with a fixed public IP (cloud server is fine, lowest configuration works), install Nginx, configure as follows:HTTP (port 80) can also be used, but HTTPS is recommended for transmission security.Step 2: Configure WeChat IP Whitelist Add the proxy server’s fixed public IP to the WeChat Developer Platform “Basic Information → Developer Secret → API IP Whitelist”. Step 3: Configure Edge Function Secret Add Edge Function Secret in Supabase backend:
| Secret Name | Value | Example |
|---|---|---|
SUPERUN_WECHAT_API_PROXY_URL | Proxy server address | https://wechat-proxy.your-domain.com |
Note: Do not add / at the end of the address.
Step 4: Verify
After configuration, redeploy Edge Functions and call any WeChat interface to verify connectivity.
Code-Level Implementation:
All Edge Functions automatically switch between direct connection / proxy mode through this single line of code:
SUPERUN_WECHAT_API_PROXY_URLnot configured → Direct connection toapi.weixin.qq.com(Scheme A)- Configured → All requests go through proxy address (Scheme B)
wechat-token(1 location)wechat-data(8 locations)wechat-articles(3 locations)wechat-menu(3 locations)
- Switch from Scheme A to Scheme B: Add
SUPERUN_WECHAT_API_PROXY_URLSecret and redeploy - Switch from Scheme B back to Scheme A: Delete the Secret and redeploy
- No code changes needed for switching
Comparison of Two Schemes
| Scheme A: IP Whitelist | Scheme B: Reverse Proxy | |
|---|---|---|
| Configuration Difficulty | No additional server needed | Requires a cloud server + domain |
| Maintenance Cost | Manual update when IP changes | No maintenance after one-time setup |
| Stability | Depends on Edge Function IP staying unchanged | Always stable |
| Suitable For | Development testing, temporary use | Production environment, long-term operation |
| Switching Method | Default | Add/delete Secret |
6.2 Access Token Management
- WeChat access_token is valid for 2 hours with limited daily calls
- Cached in
wechat_tokenstable, refreshed 5 minutes early - All Edge Functions get tokens by calling
wechat-tokenfunction to avoid duplicate requests - Regularly clean up expired token records
6.3 Common WeChat API errcode
| errcode | Meaning | Handling Method |
|---|---|---|
40001 | access_token invalid | Clear cache and re-acquire |
40164 | IP not in whitelist | Extract IP and prompt user to add |
42001 | access_token expired | Auto refresh |
46003 | Menu does not exist | Normal case, return empty menu |
61501 | Date range exceeds limit | Check if date range exceeds API limit |
45047 | Exceeds publish frequency limit | Prompt user to retry later |
6.4 Data Statistics Date Limits
- WeChat data has 1 day delay,
end_datecan only be as early as yesterday getusersummary/getusercumulate: Maximum span 7 days (inclusive)getarticlesummary/getarticletotal: Maximum span 1 daygetupstreammsg: Maximum span 7 daysgetinterfacesummary: Maximum span 30 days- Date format:
YYYY-MM-DD
6.5 freepublish/batchget Field Notes
- The identifier field in each record returned by this interface is
article_id, notmedia_id media_idis the field returned by the draft box interface (draft/add)- Confusing these two fields will cause all values to be
undefinedduring sync, preventing data from being written
6.6 Inter-Edge Function Calls
wechat-data,wechat-articles,wechat-menuall callwechat-tokenvia HTTP- Use
SUPABASE_ANON_KEYorSUPABASE_SERVICE_ROLE_KEYas Bearer Token when calling - Set
verify_jwt = falseinconfig.tomlto allow cross-function calls
6.7 Error Return Strategy
All Edge Functions involving WeChat API uniformly follow:- Token acquisition failure + IP blocked: Return HTTP
200+{ blocked_ip: "x.x.x.x" }- Returning 200 allows frontend
supabase.functions.invoke()to correctly readdata(non-200 will be put intoerror)
- Returning 200 allows frontend
- WeChat API business error: Return HTTP
200+{ error: "...", errcode: xxx } - System error: Return HTTP
500+{ error: "..." }
VII. Deployment Checklist
Pre-Deployment Checklist
Common Steps (both schemes require):- Obtained
AppIDandAppSecretfrom WeChat Developer Platform - Configured
SUPERUN_WECHAT_APP_IDandSUPERUN_WECHAT_APP_SECRETin Supabase Edge Function Secrets - Created database tables:
wechat_tokens,articles,menu_configs,auto_reply_rules - Set
verify_jwt = falsefor all WeChat-related functions insupabase/config.toml
- After deployment, get Edge Function egress IP from error response on first call
- Add egress IP to WeChat Developer Platform IP whitelist
- Call again to verify connectivity
- Deploy proxy server (Nginx configuration see section 6.1)
- Add proxy server’s fixed IP to WeChat IP whitelist
- Configure Edge Function Secret
SUPERUN_WECHAT_API_PROXY_URL - Redeploy and verify connectivity

