48 lines
1.8 KiB
Python
48 lines
1.8 KiB
Python
import json
|
||
from fastapi import APIRouter, HTTPException, Request
|
||
from fastapi.responses import PlainTextResponse
|
||
from uvicorn.server import logger
|
||
from utils.wxcom import wxcpt
|
||
from utils.wxcom import (
|
||
decrypt_message,
|
||
get_request_params
|
||
)
|
||
|
||
router = APIRouter()
|
||
|
||
@router.get("/callback")
|
||
async def verify_url(msg_signature: str, timestamp: str, nonce: str, echostr: str):
|
||
"""验证URL有效性"""
|
||
try:
|
||
logger.info(
|
||
f"收到验证请求: msg_signature={msg_signature}, timestamp={timestamp}, nonce={nonce}"
|
||
)
|
||
ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
|
||
|
||
if ret == 0:
|
||
logger.info("URL验证成功")
|
||
return PlainTextResponse(content=sEchoStr)
|
||
else:
|
||
logger.error(f"URL验证失败,错误码: {ret}")
|
||
raise HTTPException(status_code=400, detail="验证失败")
|
||
except Exception as e:
|
||
logger.error(f"验证过程发生错误: {str(e)}")
|
||
raise HTTPException(status_code=500, detail="服务器内部错误")
|
||
|
||
@router.post("/callback")
|
||
async def receive_message(request: Request):
|
||
"""接收并处理企业微信消息"""
|
||
try:
|
||
|
||
# 获取请求参数并验证,返回请求体、消息签名、时间戳和随机数
|
||
body, msg_signature, timestamp, nonce = await get_request_params(request)
|
||
# 对请求体进行解密,得到解密后的消息字典
|
||
xml_dict : dict= decrypt_message(body, msg_signature, timestamp, nonce)
|
||
logger.info(f"解密后的消息字典: \n {json.dumps(xml_dict.get("xml") , ensure_ascii=False , indent=2)}")
|
||
# 处理消息
|
||
# subscription(xml_dict)
|
||
|
||
|
||
except Exception as e:
|
||
logger.error(f"处理消息时发生错误: {str(e)}")
|
||
raise HTTPException(status_code=500, detail="服务器内部错误") |