回调逻辑

This commit is contained in:
aaron 2025-01-26 00:35:28 +08:00
parent c8c86e5d1c
commit 2e0de79799

View File

@ -258,8 +258,47 @@ class WeChatClient:
except Exception as e: except Exception as e:
raise Exception(f"创建支付订单失败: {str(e)}") raise Exception(f"创建支付订单失败: {str(e)}")
def decrypt_callback_data(self, ciphertext: str, nonce: str, associated_data: str = None) -> dict:
"""
解密回调数据
Args:
ciphertext: 密文
nonce: 随机串
associated_data: 附加数据可选
Returns:
dict: 解密后的数据
"""
try:
# Base64解码密文和随机串
ciphertext_bytes = base64.b64decode(ciphertext)
nonce_bytes = base64.b64decode(nonce)
# 处理附加数据
associated_data_bytes = associated_data.encode('utf-8') if associated_data else b''
# 使用 API v3 密钥进行解密
key_bytes = self.api_v3_key.encode('utf-8')
aesgcm = AESGCM(key_bytes)
# 解密数据
decrypted_data = aesgcm.decrypt(
nonce_bytes,
ciphertext_bytes,
associated_data_bytes
)
# 解析JSON数据
return json.loads(decrypted_data)
except Exception as e:
print(f"解密回调数据失败: {str(e)}")
raise Exception(f"解密回调数据失败: {str(e)}")
async def verify_payment_notify(self, request: Request) -> dict: async def verify_payment_notify(self, request: Request) -> dict:
"""验证支付回调通知""" """验证支付回调通知"""
try:
# 获取请求头 # 获取请求头
headers = { headers = {
'Wechatpay-Signature': request.headers.get('Wechatpay-Signature'), 'Wechatpay-Signature': request.headers.get('Wechatpay-Signature'),
@ -268,33 +307,44 @@ class WeChatClient:
'Wechatpay-Serial': request.headers.get('Wechatpay-Serial') 'Wechatpay-Serial': request.headers.get('Wechatpay-Serial')
} }
print("微信支付回调请求头:", headers)
# 读取请求体 # 读取请求体
body = await request.body() body = await request.body()
print("微信支付回调请求体:", body.decode('utf-8'))
# 验证签名 # 验证签名
if not self.verify_response(headers, body): if not self.verify_response(headers, body):
raise Exception("回调通知签名验证失败") print("签名验证失败")
return None
# 解析数据 # 解密回调数据
try: data = await request.json()
data = json.loads(body) print("解析的JSON数据:", data)
resource = data.get('resource', {})
resource = data.get("resource", {})
ciphertext = resource.get("ciphertext")
nonce = resource.get("nonce")
associated_data = resource.get("associated_data")
if not all([ciphertext, nonce]):
print("缺少必要的解密参数")
return None
# 解密数据 # 解密数据
nonce = base64.b64decode(resource['nonce']) decrypted_data = self.decrypt_callback_data(
associated_data = resource.get('associated_data', '').encode('utf-8')
ciphertext = base64.b64decode(resource['ciphertext'])
aesgcm = AESGCM(self.api_v3_key.encode('utf-8'))
decrypted_data = aesgcm.decrypt(
nonce,
ciphertext, ciphertext,
nonce,
associated_data associated_data
) )
return json.loads(decrypted_data) print("解密后的数据:", decrypted_data)
return decrypted_data
except Exception as e: except Exception as e:
raise Exception(f"解析回调数据失败: {str(e)}") print(f"处理支付回调异常: {str(e)}")
import traceback
print("详细错误信息:", traceback.format_exc())
raise Exception(f"处理支付回调失败: {str(e)}")