微信支付回调修复

This commit is contained in:
ahao 2025-03-13 10:25:21 +08:00
parent 669ee02cff
commit 235fe0f594

View File

@ -283,25 +283,18 @@ async def wxpay_notify(request: Request):
try:
# 获取回调数据
headers = dict(request.headers)
body_bytes = await request.body()
print(body_bytes)
body_unicode = body_bytes.decode('utf-8')
print(body_unicode)
# 验证微信支付签名
if not wxpay.verify(headers, body_bytes):
logging.warning("签名验证失败")
return JSONResponse(content={"code": "FAIL", "message": "签名验证失败"}, status_code=400)
data = await request.body()
# 解密回调数据
result = wxpay.decrypt_callback(headers, body_bytes)
print(result)
out_trade_no = result.get('out_trade_no')
print(out_trade_no)
transaction_id = result.get('transaction_id')
print(transaction_id)
result = wxpay.callback(headers, data)
if result and result.get('event_type') == 'TRANSACTION.SUCCESS':
print("收到支付成功信息")
print(result)
out_trade_no = result.get('out_trade_no')
print(out_trade_no)
transaction_id = result.get('transaction_id')
print(transaction_id)
if not out_trade_no or not transaction_id:
return JSONResponse(content={"code": "FAIL", "message": "缺少必要参数"}, status_code=400)
# 获取数据库连接
connection = get_connection()
@ -315,28 +308,16 @@ async def wxpay_notify(request: Request):
FOR UPDATE""", (out_trade_no,))
order = cursor.fetchone()
if not order:
logging.error(f"订单不存在: {out_trade_no}")
return JSONResponse(content={"code": "FAIL", "message": "订单不存在"}, status_code=404)
# 验证金额(示例)
callback_total = int(result.get('amount', {}).get('total', 0))
payable_cents = int(order['payable_price'] * 100)
if callback_total != payable_cents:
logging.error(f"金额不匹配: 订单应支付{payable_cents}分,回调收到{callback_total}")
return JSONResponse(content={"code": "FAIL", "message": "金额不匹配"}, status_code=400)
# 更新订单状态
cursor.execute("""
UPDATE orders SET
order_status = 'completed',
payment_method = 'wechat',
wx_transaction_id = %s,
settlement_time = NOW()
WHERE order_id = %s""",
UPDATE orders SET
order_status = 'completed',
payment_method = 'wechat',
wx_transaction_id = %s,
settlement_time = NOW()
WHERE order_id = %s""",
(transaction_id, order['order_id']))
connection.commit()
# 返回微信要求的成功响应