Files
life-echo/api/app/features/payment/order_service.py
Kevin 309a051038 feat: 回忆录证据血缘与内部评测可追溯,顺带对齐本地评测台与 CI
数据库与模型:新增多版迁移(章节证据快照、对话血缘、记忆事实/时间线 lineage 等),把「成稿 ↔ 对话/记忆」的溯源信息落到表结构里。
业务链路:会话与 WS、回忆录/故事流水线、记忆写入与 enrichment 等跟着接上线索与快照;新增章节证据快照与评测侧 EvalTraceService 等模块,方便组评审用的证据包。
内部评测:自动化 run 与手工 memoir 评审共用可追溯证据;rubric/ judge 相关脚本与文档有配套调整。
app-eval-web:Memoir/实验详情里能展开看证据摘要与 evidence_trace(含对话轮次 id);Vite 代理与 development.sh 注入的 API 端口与当前默认内部评测端口一致,避免改端口后页面连错服务。
工程杂项:GitHub Actions / 仓库说明有更新;各适配器与支付/配额/plan 等多处为小改动或跟随主改动的收尾;新增/扩充了?
2026-04-08 15:37:09 +08:00

270 lines
9.7 KiB
Python

"""
支付订单门面:持有 db + 底层 payment 客户端,提供 create_order / 回调 / 查询。
"""
import asyncio
import time
import uuid
from datetime import timedelta
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import utc_now
from app.core.logging import get_logger
from app.features.payment.models import Order
from app.features.payment.schemas import (
CreateOrderResponse,
OrderListResponse,
OrderStatusResponse,
)
from app.features.plan.service import PlanService
from app.features.user.models import User
logger = get_logger(__name__)
ORDER_EXPIRE_MINUTES = 30
SUBSCRIPTION_DURATION_DAYS = {"pro": 365, "pro_plus": 365, "premium": 365, "test": 365}
PREPAY_TIMEOUT_SEC = 25
WECHAT_INIT_TIMEOUT_SEC = 35
def _generate_order_no() -> str:
timestamp = time.strftime("%Y%m%d%H%M%S")
short_uuid = uuid.uuid4().hex[:8].upper()
return f"LE{timestamp}{short_uuid}"
def _get_payment_service_client():
from app.features.payment.deps import get_payment_service
return get_payment_service()
class PaymentOrderService:
def __init__(self, db: AsyncSession, plan_service: PlanService):
self._db = db
self._plan_service = plan_service
async def create_order(
self,
user_id: str,
user_subscription_type: str,
plan_id: str,
plan_display_name: str,
plan_price: float,
plan_currency: str,
payment_method: str,
) -> CreateOrderResponse:
from app.features.payment.payment_exceptions import PaymentError
plans = self._plan_service.get_plans_for_api()
plan = next((p for p in plans if p.id == plan_id), None)
if plan is None:
raise HTTPException(status_code=400, detail="无效的套餐 ID")
if plan.price <= 0:
raise HTTPException(status_code=400, detail="免费套餐无需支付")
if payment_method not in ("wechat", "alipay"):
raise HTTPException(
status_code=400, detail="不支持的支付方式,仅支持 wechat / alipay"
)
client = _get_payment_service_client()
if not client.is_method_available(payment_method):
if payment_method == "alipay":
raise HTTPException(
status_code=503, detail="支付宝支付接口正在开发中,暂时不可用"
)
raise HTTPException(
status_code=503,
detail=f"{payment_method} 支付暂不可用,请选择其他支付方式",
)
amount_fen = int(plan_price * 100)
order_no = _generate_order_no()
now = utc_now()
order = Order(
id=order_no,
user_id=user_id,
plan_id=plan_id,
plan_name=plan_display_name,
amount=amount_fen,
currency=plan_currency,
payment_method=payment_method,
status="pending",
created_at=now,
expired_at=now + timedelta(minutes=ORDER_EXPIRE_MINUTES),
)
self._db.add(order)
await self._db.flush()
if payment_method == "wechat":
try:
await asyncio.wait_for(
asyncio.to_thread(client.wechat_client.ensure_client),
timeout=WECHAT_INIT_TIMEOUT_SEC,
)
except asyncio.TimeoutError:
order.status = "failed"
await self._db.flush()
raise HTTPException(
status_code=504, detail="微信支付初始化超时,请稍后重试。"
)
except Exception as e:
order.status = "failed"
await self._db.flush()
logger.exception("微信支付客户端初始化失败: {}", e)
raise HTTPException(status_code=503, detail=f"微信支付暂不可用: {e!s}")
try:
payment_result = await asyncio.wait_for(
asyncio.to_thread(
client.create_payment,
payment_method,
order_no,
amount_fen,
f"岁月时书 - {plan_display_name}",
),
timeout=PREPAY_TIMEOUT_SEC,
)
except asyncio.TimeoutError:
order.status = "failed"
await self._db.flush()
raise HTTPException(
status_code=504,
detail="创建预支付超时,请检查网络或稍后重试。若为微信支付,请确认商户配置与网络可达微信服务器。",
)
except PaymentError as e:
order.status = "failed"
await self._db.flush()
raise HTTPException(
status_code=500, detail=f"创建支付订单失败: {e.message}"
)
except Exception as e:
order.status = "failed"
await self._db.flush()
logger.exception("创建支付订单异常: {}", e)
raise HTTPException(
status_code=500, detail=f"创建支付订单异常: {type(e).__name__}: {e!s}"
)
await self._db.commit()
logger.info(
"订单创建成功: order_no={}, payment_method={}, amount_fen={}",
order_no,
payment_method,
amount_fen,
)
return CreateOrderResponse(
order_id=order_no,
payment_method=payment_method,
wechat_params=payment_result.wechat_params,
alipay_order_string=payment_result.alipay_order_string,
)
async def handle_payment_success(self, out_trade_no: str, trade_no: str) -> None:
result = await self._db.execute(select(Order).where(Order.id == out_trade_no))
order = result.scalar_one_or_none()
if order is None:
logger.warning("支付回调: 订单不存在 {}", out_trade_no)
return
if order.status == "paid":
logger.info("支付回调: 订单已处理过 {}", out_trade_no)
return
now = utc_now()
order.status = "paid"
order.trade_no = trade_no
order.paid_at = now
user_result = await self._db.execute(
select(User).where(User.id == order.user_id)
)
user = user_result.scalar_one_or_none()
if user:
duration_days = SUBSCRIPTION_DURATION_DAYS.get(order.plan_id, 365)
if user.subscription_expires_at and user.subscription_expires_at > now:
user.subscription_expires_at = user.subscription_expires_at + timedelta(
days=duration_days
)
else:
user.subscription_expires_at = now + timedelta(days=duration_days)
user.subscription_type = order.plan_id
logger.info(
"用户 {} 订阅已升级为 {},到期: {}",
user.id,
order.plan_id,
user.subscription_expires_at,
)
await self._db.commit()
logger.info(
"支付成功处理完成: 订单 {}, 第三方交易号 {}", out_trade_no, trade_no
)
async def handle_wechat_notify(self, headers: dict, body: str) -> dict:
client = _get_payment_service_client()
notify_result = client.handle_wechat_notify(headers=headers, body=body)
if notify_result.success and notify_result.trade_status == "SUCCESS":
await self.handle_payment_success(
notify_result.out_trade_no,
notify_result.trade_no,
)
return {"code": "SUCCESS", "message": "成功"}
async def handle_alipay_notify(self, params: dict) -> str:
client = _get_payment_service_client()
notify_result = client.handle_alipay_notify(params=params)
if notify_result.success and notify_result.trade_status in (
"TRADE_SUCCESS",
"TRADE_FINISHED",
"SUCCESS",
):
await self.handle_payment_success(
notify_result.out_trade_no,
notify_result.trade_no,
)
return "success"
async def get_order_status(
self, order_id: str, user_id: str
) -> OrderStatusResponse:
result = await self._db.execute(
select(Order).where(Order.id == order_id, Order.user_id == user_id)
)
order = result.scalar_one_or_none()
if order is None:
raise HTTPException(status_code=404, detail="订单不存在")
return OrderStatusResponse(
order_id=order.id,
plan_id=order.plan_id,
plan_name=order.plan_name,
amount=order.amount,
currency=order.currency,
payment_method=order.payment_method,
status=order.status,
trade_no=order.trade_no,
created_at=order.created_at.isoformat() if order.created_at else "",
paid_at=order.paid_at.isoformat() if order.paid_at else None,
)
async def list_orders(self, user_id: str) -> list[OrderListResponse]:
result = await self._db.execute(
select(Order)
.where(Order.user_id == user_id)
.order_by(Order.created_at.desc())
)
orders = result.scalars().all()
return [
OrderListResponse(
id=o.id,
plan_id=o.plan_id,
plan_name=o.plan_name,
amount=o.amount,
currency=o.currency,
status=o.status,
payment_method=o.payment_method,
created_at=o.created_at.isoformat() if o.created_at else "",
paid_at=o.paid_at.isoformat() if o.paid_at else None,
)
for o in orders
]