100 lines
2.7 KiB
Python
100 lines
2.7 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
支付成功异步回调处理模块
|
|
当用户支付成功后,支付平台会把订单支付信息异步请求到回调接口
|
|
"""
|
|
|
|
import json
|
|
import asyncio
|
|
from .api import YsmPayApi
|
|
|
|
class PaymentNotify:
|
|
"""支付通知处理类"""
|
|
|
|
def __init__(self, appid, appsecret):
|
|
"""
|
|
初始化
|
|
|
|
Args:
|
|
appid: 支付通道ID
|
|
appsecret: 密钥
|
|
"""
|
|
self.appid = appid
|
|
self.appsecret = appsecret
|
|
|
|
async def process(self, request_data):
|
|
"""
|
|
处理支付通知(异步)
|
|
|
|
Args:
|
|
request_data: 请求数据(字符串或字典)
|
|
|
|
Returns:
|
|
tuple: (是否成功, 消息)
|
|
"""
|
|
# 解析请求数据
|
|
if isinstance(request_data, str):
|
|
try:
|
|
data = json.loads(request_data)
|
|
except:
|
|
return False, "数据格式错误"
|
|
else:
|
|
data = request_data
|
|
|
|
# 验证签名
|
|
calc_hash = YsmPayApi.hash_sign(data, self.appsecret)
|
|
if data.get('hash') != calc_hash:
|
|
return False, "验签失败,签名错误"
|
|
|
|
# 获取商户订单号
|
|
mch_orderid = data.get('mch_orderid')
|
|
|
|
# 处理支付结果
|
|
if data.get('state') == 'SUCCESS':
|
|
# 在这里处理订单业务逻辑
|
|
# 注意:平台可能会多次调用本接口,请确保订单不会被重复处理
|
|
|
|
# 示例:订单处理逻辑,这里可以使用异步数据库操作
|
|
"""
|
|
order = await find_order_by_id(mch_orderid)
|
|
if order and order.status != 'paid':
|
|
await update_order_status(mch_orderid, 'paid')
|
|
# 其他业务逻辑...
|
|
"""
|
|
|
|
return True, "success"
|
|
else:
|
|
# 处理未支付的情况
|
|
return False, "订单未支付"
|
|
|
|
# FastAPI Web应用示例
|
|
"""
|
|
from fastapi import FastAPI, Request, Response
|
|
from fastapi.responses import JSONResponse
|
|
|
|
app = FastAPI()
|
|
|
|
@app.post("/notify")
|
|
async def payment_notify(request: Request):
|
|
# 配置信息
|
|
appid = '20********' # 支付通道ID
|
|
appsecret = 'e605ac7******************4af5164' # AppSecret
|
|
|
|
# 创建通知处理器
|
|
notify_handler = PaymentNotify(appid, appsecret)
|
|
|
|
# 获取请求数据
|
|
request_data = await request.body()
|
|
|
|
# 处理通知
|
|
success, message = await notify_handler.process(request_data)
|
|
|
|
if success:
|
|
return Response(content=message)
|
|
else:
|
|
return JSONResponse(content={"error": message}, status_code=400)
|
|
|
|
# 启动命令: uvicorn notify:app --reload
|
|
""" |