nomadro/apps/ebook/dymini/backend/app/routers/pay.py
eric d93a355fd5 Migrate navmini/ebook/nomadweb into apps/ as same-origin portal subpaths.
Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:30:34 -05:00

142 lines
4.7 KiB
Python

from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from app.config import settings
from app.core.deps import get_current_openid
from app.domains.books import is_book_free
from app.schemas.pay import DevConfirmBody, OrderBody, StatusBody
from app.services.store import store
router = APIRouter(prefix="/api/pay", tags=["pay"])
@router.post("/order")
async def create_pay_order(body: OrderBody, openid: str = Depends(get_current_openid)):
book = store.get_book(body.book_id)
if not book:
raise HTTPException(404, "书籍不存在")
if is_book_free(book):
raise HTTPException(400, "当前为免费模式,无需购买")
if store.is_unlocked(openid, body.book_id):
raise HTTPException(400, "已解锁,无需重复购买")
if not book.get("product_id") or int(book.get("price_fen") or 0) <= 0:
raise HTTPException(400, "未配置付费道具")
user = store.get_user(openid)
if not user:
raise HTTPException(401, "请先登录")
attach = json.dumps({"book_id": body.book_id, "openid": openid}, ensure_ascii=False, separators=(",", ":"))
out_trade_no = store.create_order(
openid=openid,
book_id=body.book_id,
product_id=book["product_id"],
amount_fen=book["price_fen"],
attach=attach,
)
try:
from app.services.track import ingest_events
await ingest_events(
[
{
"name": "pay_order_created",
"page": "api",
"label": book["product_id"],
"props": {
"book_id": body.book_id,
"out_trade_no": out_trade_no,
"price_fen": book["price_fen"],
"mock": settings.tt_pay_mock,
},
}
],
openid=openid,
client="api",
)
except Exception:
pass
# 抖音真实支付接入前:返回模拟支付参数
return {
"outTradeNo": out_trade_no,
"productId": book["product_id"],
"goodsPrice": book["price_fen"],
"mock": True,
"mockTitle": book.get("title") or "解锁全书",
"mode": "mock",
}
@router.post("/status")
async def pay_status(body: StatusBody, openid: str = Depends(get_current_openid)):
order = store.get_order(body.out_trade_no)
unlocked = store.is_unlocked(openid, body.book_id)
return {
"unlocked": unlocked,
"status": (order or {}).get("status", "unknown"),
"delivered": bool((order or {}).get("delivered")),
}
@router.post("/dev-confirm")
@router.post("/mock-confirm")
async def mock_confirm(body: DevConfirmBody, openid: str = Depends(get_current_openid)):
"""模拟支付确认发货。TT_PAY_MOCK=true 或 DEBUG=true 时可用。"""
if not (settings.tt_pay_mock or settings.debug):
raise HTTPException(403, "模拟支付未开启")
order = store.get_order(body.out_trade_no)
if not order or order["openid"] != openid:
raise HTTPException(404, "订单不存在")
store.mark_delivered(body.out_trade_no, wx_order_id=f"MOCK{body.out_trade_no}")
try:
from app.services.track import ingest_events
await ingest_events(
[
{
"name": "pay_success",
"label": "mock",
"props": {"out_trade_no": body.out_trade_no, "book_id": order.get("book_id")},
}
],
openid=openid,
client="api",
)
except Exception:
pass
return {"ok": True, "unlocked": True, "mock": True}
@router.post("/query")
async def pay_query(body: StatusBody, openid: str = Depends(get_current_openid)):
order = store.get_order(body.out_trade_no)
if not order or order["openid"] != openid:
raise HTTPException(404, "订单不存在")
return {
"status": order.get("status"),
"delivered": bool(order.get("delivered")),
"mock": True,
}
@router.api_route("/notify", methods=["GET", "POST"])
async def pay_notify(request: Request):
"""预留抖音支付回调;当前模拟支付不依赖此接口。"""
try:
from app.services.track import ingest_events
text = (await request.body()).decode("utf-8", "replace")[:500]
await ingest_events(
[{"name": "wx_push", "label": "tt_notify", "props": {"body": text[:200]}}],
openid=None,
client="tt_push",
)
except Exception:
pass
return Response(content='{"err_no":0,"err_tips":"success"}', media_type="application/json")