This commit is contained in:
2026-06-15 10:33:31 +08:00
parent faa3c165dc
commit 95847e146e
+6 -8
View File
@@ -181,24 +181,22 @@ async def wechat_callback(request: Request, db: AsyncSession = Depends(get_db)):
raise HTTPException(status_code=400, detail="随机数为空") raise HTTPException(status_code=400, detail="随机数为空")
# 使用 AES-GCM 解密(符合官方文档规范) # 使用 AES-GCM 解密(符合官方文档规范)
# 官方文档:https://pay.weixin.qq.com/doc/v3/merchant/4012071382
try: try:
# API v3 key 需要转换为字节串 # API v3 key 需要转换为字节串
api_v3_key_bytes = api_v3_key.encode('utf-8') api_v3_key_bytes = api_v3_key.encode('utf-8')
# ciphertext 和 nonce 都是 Base64 编码的,需要解码 # ciphertext 是 Base64 编码的,需要解码
ciphertext_bytes = b64decode(ciphertext) ciphertext_bytes = b64decode(ciphertext)
nonce_bytes = b64decode(nonce_str)
# nonce 直接使用字符串编码(官方文档方式)
nonce_bytes = nonce_str.encode('utf-8')
# associated_data 是字符串,直接编码 # associated_data 是字符串,直接编码
associated_data_bytes = associated_data.encode('utf-8') if associated_data else b'' associated_data_bytes = associated_data.encode('utf-8') if associated_data else b''
# 验证 nonce 长度(AES-GCM 要求 8-128 字节)
if len(nonce_bytes) < 8 or len(nonce_bytes) > 128:
logger.error(f"WeChat callback invalid nonce length: {len(nonce_bytes)} bytes")
raise HTTPException(status_code=400, detail="无效的随机数长度")
aesgcm = AESGCM(api_v3_key_bytes) aesgcm = AESGCM(api_v3_key_bytes)
decrypted_str = aesgcm.decrypt(ciphertext_bytes, associated_data_bytes, nonce_bytes) decrypted_str = aesgcm.decrypt(nonce_bytes, ciphertext_bytes, associated_data_bytes)
except InvalidTag: except InvalidTag:
logger.error("WeChat callback decryption failed: Invalid tag (key or data mismatch)") logger.error("WeChat callback decryption failed: Invalid tag (key or data mismatch)")
raise HTTPException(status_code=400, detail="数据解密失败(密钥或数据不匹配)") raise HTTPException(status_code=400, detail="数据解密失败(密钥或数据不匹配)")