1
This commit is contained in:
@@ -181,24 +181,22 @@ async def wechat_callback(request: Request, db: AsyncSession = Depends(get_db)):
|
||||
raise HTTPException(status_code=400, detail="随机数为空")
|
||||
|
||||
# 使用 AES-GCM 解密(符合官方文档规范)
|
||||
# 官方文档:https://pay.weixin.qq.com/doc/v3/merchant/4012071382
|
||||
try:
|
||||
# API v3 key 需要转换为字节串
|
||||
api_v3_key_bytes = api_v3_key.encode('utf-8')
|
||||
|
||||
# ciphertext 和 nonce 都是 Base64 编码的,需要解码
|
||||
# ciphertext 是 Base64 编码的,需要解码
|
||||
ciphertext_bytes = b64decode(ciphertext)
|
||||
nonce_bytes = b64decode(nonce_str)
|
||||
|
||||
# nonce 直接使用字符串编码(官方文档方式)
|
||||
nonce_bytes = nonce_str.encode('utf-8')
|
||||
|
||||
# associated_data 是字符串,直接编码
|
||||
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)
|
||||
decrypted_str = aesgcm.decrypt(ciphertext_bytes, associated_data_bytes, nonce_bytes)
|
||||
decrypted_str = aesgcm.decrypt(nonce_bytes, ciphertext_bytes, associated_data_bytes)
|
||||
except InvalidTag:
|
||||
logger.error("WeChat callback decryption failed: Invalid tag (key or data mismatch)")
|
||||
raise HTTPException(status_code=400, detail="数据解密失败(密钥或数据不匹配)")
|
||||
|
||||
Reference in New Issue
Block a user