fix: 小程序服务号绑定先打开门户域名再跳转微信授权。

web-view 不能直接打开 open.weixin.qq.com,移动端改为打开已配置的业务域名中转页。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-10-29 01:44:40 +08:00
1 parent 459b820f95
commit e7c1762113
7 files changed
+137 -8

No files matched your search

+28 -1
View File
@@ -1,5 +1,6 @@
"""服务号身份绑定:扫码候选 + 原登录端确认,两步均在短时会话内完成。"""
import json
import re
import secrets
import time
from urllib.parse import urlencode, urlparse
@@ -15,6 +16,7 @@ from app.models.wechat_notice import WechatBinding
from app.services.wechat_oa_client import client, WechatAPIError
TTL = 300
_STATE_RE = re.compile(r"^[A-Za-z0-9_-]{20,100}$")
_GETDEL = "local v=redis.call('GET',KEYS[1]); redis.call('DEL',KEYS[1]); return v"
_UNLOCK = "if redis.call('GET',KEYS[1]) == ARGV[1] then return redis.call('DEL',KEYS[1]) end return 0"
@@ -125,10 +127,35 @@ def _start_binding(user, *, mode="desktop"):
_save(session_id, data)
_call("set", "wechat:oa:state:" + state, session_id, ex=TTL)
_call("set", _owner_key(user), session_id, ex=TTL)
# 小程序 web-view 只能打开已配置的业务域名。open.weixin.qq.com 不能作为 src,
# 移动端先打开门户中转页,再由该页跳到微信授权;电脑扫码仍直接使用授权链接。
authorize_url = mobile_launch_url(state) if mode == "mobile" else oauth_authorize_url(state)
return {"sessionId": session_id, "authorizeUrl": authorize_url, "expiresIn": TTL}
def oauth_authorize_url(state):
callback = settings.WECHAT_OA_PUBLIC_BASE_URL.rstrip("/") + settings.API_V1_PREFIX + "/public/wechat-notices/oauth/callback"
params = {"appid": settings.WECHAT_OA_APPID, "redirect_uri": callback,
"response_type": "code", "scope": "snsapi_base", "state": state}
return {"sessionId": session_id, "authorizeUrl": "https://open.weixin.qq.com/connect/oauth2/authorize?" + urlencode(params) + "#wechat_redirect", "expiresIn": TTL}
return "https://open.weixin.qq.com/connect/oauth2/authorize?" + urlencode(params) + "#wechat_redirect"
def mobile_launch_url(state):
base = settings.WECHAT_OA_PUBLIC_BASE_URL.rstrip("/") + settings.API_V1_PREFIX
return base + "/public/wechat-notices/oauth/launch?" + urlencode({"state": state})
def resolve_mobile_authorize_target(state):
"""校验尚未消费的 state,返回官方授权地址。不删除 state,授权回调才消费。"""
if not _STATE_RE.fullmatch(state or ""):
raise HTTPException(400, "授权链接无效,请返回小程序重新绑定")
if not enabled():
raise HTTPException(503, "服务号通知尚未配置启用")
raw = _call("get", "wechat:oa:state:" + state)
session_id = _decode(raw) if raw else ""
if not session_id or not _load(session_id):
raise HTTPException(400, "授权已过期,请返回小程序重新绑定")
return oauth_authorize_url(state)
def oauth_callback(state, code):