WeChat Official Account Service Deployment
When to Use
Deploy a production-ready WeChat Official Account (微信服务号) backend with Hermes AI kernel as the customer service brain. Used when the user provides:
- WeChat Official Account credentials (AppID, AppSecret)
- A domain name pointing to the server (required by WeChat)
- A public cloud VM (Ubuntu/Debian) with root/sudo access
What It Delivers
| Feature | Description |
|---|---|
| WeChat Server Verification | GET /wechat with signature check |
| Message Handling | Text, image, voice, video, location, link, events |
| AI Customer Service | LLM-powered (same model as Hermes) with conversation history |
| Auto Reply | Subscribe welcome, menu click, keyword fallback |
| Custom Menu | DB-stored, syncable to WeChat |
| OAuth2 Login | Web page WeChat authorization |
| Template Messages | Push notifications to subscribers |
| Admin Dashboard | Web UI for stats, users, messages, menu |
| Hermes API | /api/hermes/* endpoints for Hermes Agent to push/send/manage |
| Encryption | SSL + Nginx reverse proxy |
Workflow (9 Phases)
Phase 0: Gather Inputs
Ask user for:
inputs:
domain: "fwh.example.com" # DNS → server IP
app_id: "wx1234567890abcdef"
app_secret: "abcdef1234567890..."
wechat_token: "my_custom_token" # 16-32 chars alpha-numeric
admin_password: "secure_admin_pwd"
llm_api_key: "" # optional—falls back to OPENAI_API_KEY
llm_base_url: "https://api.deepseek.com"
llm_model: "deepseek-v4-flash"
Requirement: domain MUST resolve to server's public IP before starting.
Prompt pattern:
你有一个微信服务号需要搭建后端,请提供以下信息:
1. 服务号 AppID 和 AppSecret
2. 指向本机的域名(用于微信服务器回调)
3. 你想要的服务器 Token(之后也要填到微信后台)
Phase 1: Environment Setup
# System dependencies
sudo apt update -qq && sudo apt install -y -qq nginx certbot python3-certbot-nginx python3-venv python3-pip
# Project scaffold
PROJECT=~/projects/wechat-$(echo $RANDOM | md5sum | head -c 8)
mkdir -p $PROJECT/{app/{wechat,ai,notification,oauth,api,admin,templates},deploy}
cd $PROJECT
# Python venv
python3 -m venv venv
source venv/bin/activate
Phase 2: Core Code Generation
Create files in this order. Each file is a self-contained module:
requirements.txt
fastapi==0.115.0
uvicorn[standard]==0.30.6
wechatpy==1.5.1
sqlalchemy==2.0.35
aiosqlite==0.20.0
httpx==0.27.2
python-dotenv==1.0.1
pydantic==2.9.2
pydantic-settings==2.5.2
jinja2==3.1.4
python-multipart==0.0.12
apscheduler==3.10.4
app/config.py
CRITICAL: Use extra="ignore" in model_config to prevent .env parsing failures.
import os
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
wechat_app_id: str = ""
wechat_app_secret: str = ""
wechat_token: str = ""
wechat_encoding_aes_key: str = ""
llm_api_key: str = ""
@property
def effective_llm_api_key(self) -> str:
return self.llm_api_key or os.getenv("OPENAI_API_KEY", "")
llm_base_url: str = "https://api.deepseek.com"
llm_model: str = "deepseek-v4-flash"
llm_max_tokens: int = 2048
database_url: str = "sqlite+aiosqlite:///./wechat.db"
admin_username: str = "admin"
admin_password: str = "changeme"
oauth_redirect_domain: str = ""
host: str = "0.0.0.0"
port: int = 8000
model_config = {"env_file": ".env", "extra": "ignore"}
settings = Settings()
.env.example
WECHAT_APP_ID=your_app_id
WECHAT_APP_SECRET=your_app_secret
WECHAT_TOKEN=your_token_here
WECHAT_ENCODING_AES_KEY=
LLM_API_KEY=
LLM_BASE_URL=https://api.deepseek.com
LLM_MODEL=deepseek-v4-flash
LLM_MAX_TOKENS=2048
DATABASE_URL=sqlite+aiosqlite:///./wechat.db
ADMIN_USERNAME=admin
ADMIN_PASSWORD=changeme
OAUTH_REDIRECT_DOMAIN=https://your-domain.com
⚠️ IMPORTANT: Use terminal command with echo to write secrets to .env, NOT write_file — the write_file tool may corrupt secrets via content redaction.
echo "WECHAT_APP_ID=$APP_ID" >> $PROJECT/.env
echo "WECHAT_APP_SECRET=$APP_SECRET" >> $PROJECT/.env
echo "WECHAT_TOKEN=$TOKEN" >> $PROJECT/.env
app/wechat/handler.py — Key patterns
def verify_server(request: Request) -> bool:
"""WeChat verification — MUST catch exception from wechatpy."""
signature = request.query_params.get("signature", "")
timestamp = request.query_params.get("timestamp", "")
nonce = request.query_params.get("nonce", "")
try:
return check_signature(settings.wechat_token, signature, timestamp, nonce)
except Exception:
return False
app/main.py — Entry point pattern
@app.api_route("/wechat", methods=["GET", "POST"])
async def wechat_router(request: Request):
if request.method == "GET":
if verify_server(request):
return HTMLResponse(content=request.query_params.get("echostr", ""))
return HTMLResponse(content="verification failed", status_code=403)
elif request.method == "POST":
xml_data = await request.body()
reply = await handle_message(xml_data.decode("utf-8"))
if reply:
return HTMLResponse(content=reply, media_type="application/xml")
return HTMLResponse(content="")
Phase 3: Nginx Configuration
Write nginx config file:
server {
listen 80;
server_name ${DOMAIN};
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name ${DOMAIN};
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
client_max_body_size 10M;
}
Prompt for user to deploy (since sudo commands are agent-blocked):
# User must execute these:
sudo apt install nginx certbot python3-certbot-nginx -y
# Write config
sudo tee /etc/nginx/sites-available/wechat > /dev/null << 'EOF'
... nginx config ...
EOF
sudo ln -sf /etc/nginx/sites-available/wechat /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
# Get SSL cert
sudo certbot --nginx -d ${DOMAIN} --non-interactive --agree-tos -m admin@${DOMAIN}
Phase 4: systemd Service
[Unit]
Description=WeChat Service Backend
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/projects/wechat-app
ExecStart=/home/ubuntu/projects/wechat-app/venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8000
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
sudo cp ~/wechat.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now wechat
Phase 5: Start & Verify
cd ~/projects/wechat-app && source venv/bin/activate
uvicorn app.main:app --host 127.0.0.1 --port 8000 &
sleep 3
curl -s http://127.0.0.1:8000/health # → {"status":"ok"}
curl -s https://$DOMAIN/health # → same via nginx
Phase 6: WeChat Platform Config
User configures in mp.weixin.qq.com:
| Field | Value |
|---|---|
| URL | https://${DOMAIN}/wechat |
| Token | (the WECHAT_TOKEN) |
| IP Whitelist | Server's public IP |
Phase 7: Sync Users & Menu
# Test menu sync
curl -X POST http://127.0.0.1:8000/admin/menu/sync
# Sync user list from WeChat
curl -X POST http://127.0.0.1:8000/api/hermes/sync-users
Pitfalls (from real deployment)
| Pitfall | Solution |
|---|---|
wechatpy.check_signature() raises InvalidSignatureException instead of returning False |
Must wrap in try/except in verify_server() |
.env secrets silently corrupted by Hermes content redaction |
Use echo "KEY=value" >> .env in terminal, not write_file |
RedirectResponse not available from top-level fastapi |
Import from fastapi.responses |
pydantic_settings rejects extra env vars |
Add extra="ignore" to model_config |
| Port conflict on restart | kill $(lsof -ti :8000) before restarting |
| Self-signed SSL doesn't work with WeChat | Must use Let's Encrypt / proper CA-signed cert |
| Port 8000 stuck after crash | fuser -k 8000/tcp or wait for socket release |
Key Prompt Patterns
Initial user query
你有一个微信服务号需要搭建后端,请提供以下信息:
1. 服务号 AppID 和 AppSecret
2. 指向本机的域名
3. 你想要的服务器 Token
Architecture confirmation
## 整体架构方案
微信用户 ←→ 微信服务器 ←→ Nginx(SSL) ←→ FastAPI + Hermes AI 内核
├── /wechat 消息路由
├── AI Kernel (DeepSeek/Claude)
├── 对话历史 (SQLite)
├── Admin Dashboard
└── Hermes Push API
技术栈:FastAPI + wechatpy + SQLAlchemy + SQLite + Nginx
Debugging verification failure
检查步骤:
1. curl -sk "https://$DOMAIN/wechat?...signature..." 看返回
2. 确认 .env 中 WECHAT_TOKEN 与微信后台完全一致
3. 确认服务器 IP 在微信白名单中
4. 检查 uvicorn 日志中的具体 traceback
All Template Files
Full project template is at ~/projects/hongzhua-wechat/ — copy and adapt for each new deployment. Key files:
app/main.py— FastAPI app with WeChat routeapp/config.py— Pydantic settingsapp/database.py— SQLAlchemy asyncapp/models.py— User, Conversation, MessageLog, MenuConfigapp/wechat/handler.py— Message/event routingapp/wechat/token_manager.py— Access token auto-refreshapp/ai/kernel.py— LLM API callerapp/ai/personality.py— System prompt + conversation historyapp/oauth/handler.py— WeChat OAuth2app/notification/push.py— Template/custom messagesapp/api/hermes.py— Hermes Agent integrationapp/admin/dashboard.py— Web management UIapp/templates/*.html— Admin UI templatesdeploy/nginx.conf— Nginx reverse proxydeploy/hongzhua.service— systemd unit