diff --git a/video-gen-api/app/api/v1/payments.py b/video-gen-api/app/api/v1/payments.py index 5c8f3840..09181f53 100644 --- a/video-gen-api/app/api/v1/payments.py +++ b/video-gen-api/app/api/v1/payments.py @@ -185,18 +185,28 @@ async def wechat_callback(request: Request, db: AsyncSession = Depends(get_db)): # 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 = bytes.fromhex(nonce_str) # 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) except InvalidTag: logger.error("WeChat callback decryption failed: Invalid tag (key or data mismatch)") raise HTTPException(status_code=400, detail="数据解密失败(密钥或数据不匹配)") + except ValueError as e: + logger.error(f"WeChat callback decryption failed: Invalid hex string or other error: {e}") + raise HTTPException(status_code=400, detail="数据解密失败(格式错误)") except Exception as e: logger.error(f"WeChat callback decryption failed: {e}") raise HTTPException(status_code=400, detail="数据解密失败")