2026-01-21 15:49:12 +08:00
|
|
|
/**
|
|
|
|
|
* 支付宝回调通知 API
|
|
|
|
|
* 基于 Universal_Payment_Module v4.0 设计
|
|
|
|
|
*
|
|
|
|
|
* POST /api/payment/alipay/notify
|
|
|
|
|
*/
|
|
|
|
|
|
2026-01-09 11:58:08 +08:00
|
|
|
import { type NextRequest, NextResponse } from "next/server"
|
2026-01-21 15:49:12 +08:00
|
|
|
import { PaymentFactory, SignatureError } from "@/lib/payment"
|
|
|
|
|
|
|
|
|
|
// 确保网关已注册
|
|
|
|
|
import "@/lib/payment/alipay"
|
2026-01-09 11:58:08 +08:00
|
|
|
|
|
|
|
|
export async function POST(request: NextRequest) {
|
|
|
|
|
try {
|
2026-01-21 15:49:12 +08:00
|
|
|
// 获取表单数据
|
2026-01-09 11:58:08 +08:00
|
|
|
const formData = await request.formData()
|
|
|
|
|
const params: Record<string, string> = {}
|
|
|
|
|
|
|
|
|
|
formData.forEach((value, key) => {
|
|
|
|
|
params[key] = value.toString()
|
|
|
|
|
})
|
|
|
|
|
|
2026-01-21 15:49:12 +08:00
|
|
|
console.log("[Alipay Notify] 收到回调:", {
|
|
|
|
|
out_trade_no: params.out_trade_no,
|
|
|
|
|
trade_status: params.trade_status,
|
|
|
|
|
total_amount: params.total_amount,
|
2026-01-09 11:58:08 +08:00
|
|
|
})
|
|
|
|
|
|
2026-01-21 15:49:12 +08:00
|
|
|
// 创建支付宝网关
|
|
|
|
|
const gateway = PaymentFactory.create("alipay_wap")
|
2026-01-09 11:58:08 +08:00
|
|
|
|
2026-01-21 15:49:12 +08:00
|
|
|
try {
|
|
|
|
|
// 解析并验证回调数据
|
|
|
|
|
const notifyResult = gateway.parseNotify(params)
|
|
|
|
|
|
|
|
|
|
if (notifyResult.status === "paid") {
|
|
|
|
|
console.log("[Alipay Notify] 支付成功:", {
|
|
|
|
|
tradeSn: notifyResult.tradeSn,
|
|
|
|
|
platformSn: notifyResult.platformSn,
|
|
|
|
|
amount: notifyResult.payAmount / 100, // 转换为元
|
|
|
|
|
payTime: notifyResult.payTime,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// TODO: 更新订单状态
|
|
|
|
|
// await OrderService.updateStatus(notifyResult.tradeSn, 'paid')
|
|
|
|
|
|
|
|
|
|
// TODO: 解锁内容/开通权限
|
|
|
|
|
// await ContentService.unlockForUser(notifyResult.attach?.userId, notifyResult.attach?.productId)
|
2026-01-09 11:58:08 +08:00
|
|
|
|
2026-01-21 15:49:12 +08:00
|
|
|
// TODO: 分配佣金(如果有推荐人)
|
|
|
|
|
// if (notifyResult.attach?.referralCode) {
|
|
|
|
|
// await ReferralService.distributeCommission(notifyResult)
|
|
|
|
|
// }
|
|
|
|
|
} else {
|
|
|
|
|
console.log("[Alipay Notify] 非支付成功状态:", notifyResult.status)
|
|
|
|
|
}
|
2026-01-09 11:58:08 +08:00
|
|
|
|
2026-01-21 15:49:12 +08:00
|
|
|
// 返回成功响应
|
|
|
|
|
return new NextResponse(gateway.successResponse())
|
2026-01-09 11:58:08 +08:00
|
|
|
|
2026-01-21 15:49:12 +08:00
|
|
|
} catch (error) {
|
|
|
|
|
if (error instanceof SignatureError) {
|
|
|
|
|
console.error("[Alipay Notify] 签名验证失败")
|
|
|
|
|
return new NextResponse(gateway.failResponse())
|
|
|
|
|
}
|
|
|
|
|
throw error
|
2026-01-09 11:58:08 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
2026-01-21 15:49:12 +08:00
|
|
|
console.error("[Alipay Notify] 处理失败:", error)
|
2026-01-09 11:58:08 +08:00
|
|
|
return new NextResponse("fail")
|
|
|
|
|
}
|
|
|
|
|
}
|