From eabff3b9201b65eb5064eb274d0e454aa1258837 Mon Sep 17 00:00:00 2001 From: 16337 <1633794139@qq.com> Date: Mon, 23 Mar 2026 12:59:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9AH5=20=E5=B7=A5?= =?UTF-8?q?=E5=8D=95=E9=A1=B5=E4=BC=81=E5=BE=AE=20OAuth2=20=E8=AE=A4?= =?UTF-8?q?=E8=AF=81=E6=8E=A5=E5=8F=A3=EF=BC=88code=20=E6=8D=A2=20userid?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/routers/work_order_api.py | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/app/routers/work_order_api.py b/app/routers/work_order_api.py index af880de..e89681a 100644 --- a/app/routers/work_order_api.py +++ b/app/routers/work_order_api.py @@ -2,6 +2,7 @@ H5 工单处理 API 供企微 H5 工单详情页调用: +- GET /auth — 企微 OAuth2 code 换 userid - GET /detail — 获取告警+工单详情 - POST /submit — 提交处理结果(描述+图片) - POST /upload-image — 上传处理后照片到 COS @@ -10,7 +11,9 @@ H5 工单处理 API from fastapi import APIRouter, Query, UploadFile, File from pydantic import BaseModel from typing import Optional, List +import httpx +from app.config import settings from app.utils.logger import logger router = APIRouter(prefix="/api/work-order", tags=["H5工单处理"]) @@ -22,6 +25,39 @@ class SubmitRequest(BaseModel): resultImgUrls: Optional[List[str]] = None +@router.get("/auth") +async def wechat_oauth( + code: str = Query(..., description="企微 OAuth2 授权码"), +): + """企微 OAuth2:用 code 换取 userid""" + try: + # 1. 获取 access_token + from app.services.wechat_service import get_wechat_service + wechat = get_wechat_service() + access_token = await wechat._get_access_token() + + # 2. 用 code 换 userid + url = f"https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token={access_token}&code={code}" + async with httpx.AsyncClient(timeout=10) as client: + resp = await client.get(url) + data = resp.json() + + if data.get("errcode", 0) != 0: + logger.warning(f"OAuth2 获取用户失败: {data}") + return {"code": -1, "msg": data.get("errmsg", "授权失败"), "data": None} + + userid = data.get("UserId") or data.get("userid") or "" + if not userid: + return {"code": -1, "msg": "非企业成员", "data": None} + + logger.info(f"OAuth2 认证成功: userid={userid}") + return {"code": 0, "msg": "success", "data": {"userId": userid}} + + except Exception as e: + logger.error(f"OAuth2 认证异常: {e}") + return {"code": -1, "msg": str(e), "data": None} + + @router.get("/detail") async def get_work_order_detail( alarmId: str = Query(..., description="告警ID"),