From dc9c33729f41f9307ee7a23e5f40bcf685986777 Mon Sep 17 00:00:00 2001 From: zdl <3489966805@qq.com> Date: Wed, 26 Nov 2025 14:51:51 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=9B=9E=E8=B0=83=E5=A4=84=E7=90=86?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20H5=20=E6=A8=A1=E5=BC=8F=E5=88=A4=E6=96=AD?= =?UTF-8?q?=EF=BC=8C=E9=87=8D=E5=AE=9A=E5=90=91=E5=88=B0=E5=89=8D=E7=AB=AF?= =?UTF-8?q?=E5=9B=9E=E8=B0=83=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/app.py b/app.py index 552a63a3..5ef6b4e6 100755 --- a/app.py +++ b/app.py @@ -3475,6 +3475,46 @@ def get_wechat_qrcode(): }}), 200 +@app.route('/api/auth/wechat/h5-auth', methods=['POST']) +def get_wechat_h5_auth_url(): + """ + 获取微信 H5 网页授权 URL + 用于手机浏览器跳转微信 App 授权 + """ + data = request.get_json() or {} + frontend_redirect = data.get('redirect_url', '/home') + + # 生成唯一 state + state = uuid.uuid4().hex + + # 编码回调地址 + redirect_uri = urllib.parse.quote_plus(WECHAT_REDIRECT_URI) + + # 构建授权 URL(使用 snsapi_login 获取用户信息) + auth_url = ( + f"https://open.weixin.qq.com/connect/oauth2/authorize?" + f"appid={WECHAT_APPID}&redirect_uri={redirect_uri}" + f"&response_type=code&scope=snsapi_login&state={state}" + "#wechat_redirect" + ) + + # 存储 session 信息 + wechat_qr_sessions[state] = { + 'status': 'waiting', + 'expires': time.time() + 300, + 'mode': 'h5', # 标记为 H5 模式 + 'frontend_redirect': frontend_redirect, + 'user_info': None, + 'wechat_openid': None, + 'wechat_unionid': None + } + + return jsonify({ + 'auth_url': auth_url, + 'state': state + }), 200 + + @app.route('/api/account/wechat/qrcode', methods=['GET']) def get_wechat_bind_qrcode(): """发起微信绑定二维码,会话标记为绑定模式""" @@ -3714,14 +3754,23 @@ def wechat_callback(): # 更新微信session状态,供前端轮询检测 if state in wechat_qr_sessions: session_item = wechat_qr_sessions[state] - # 仅处理登录/注册流程,不处理绑定流程 - if not session_item.get('mode'): - # 更新状态和用户信息 + mode = session_item.get('mode') + + # H5 模式:重定向到前端回调页面 + if mode == 'h5': + frontend_redirect = session_item.get('frontend_redirect', '/home/wechat-callback') + # 清理 session + del wechat_qr_sessions[state] + print(f"✅ H5 微信登录成功,重定向到: {frontend_redirect}") + return redirect(f"{frontend_redirect}?wechat_login=success") + + # PC 扫码模式:更新状态供前端轮询 + if not mode: session_item['status'] = 'register_ready' if is_new_user else 'login_ready' session_item['user_info'] = {'user_id': user.id} print(f"✅ 微信扫码状态已更新: {session_item['status']}, user_id: {user.id}") - # 直接跳转到首页 + # PC 模式直接跳转到首页 return redirect('/home') except Exception as e: