nomadro/apps/api/services/ebook_svc/routers/pay.py
Eric 3f7528f824 Add VIP knowledge community and device shop with native weapp UX.
Document memo/shop admin routes, deploy scripts, and cache-first feed performance in README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 16:58:17 +08:00

494 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import json
from typing import Any
import xmltodict
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, Field
from ebook_svc.config import settings
from ebook_svc.core.deps import get_current_openid
from ebook_svc.domains.books import is_book_free
from ebook_svc.domains.books.products import PRODUCT_OFFERS
from ebook_svc.schemas.pay import DevConfirmBody, OrderBody, StatusBody
from ebook_svc.services.shop_store import shop_store
from ebook_svc.services.store import store
from ebook_svc.services.vip_config import read_vip_config
from ebook_svc.services.wxpay import build_sign_data, calc_pay_sig, calc_signature, query_order
router = APIRouter(prefix="/pay", tags=["pay"])
# VIP 订单在 unlocks / orders 里用的哨兵 book_id(不是真实小册)
VIP_BOOK_ID = "__vip__"
SHOP_BOOK_ID = "__shop__"
class ShopOrderBody(BaseModel):
productId: str = Field(..., min_length=1)
qty: int = Field(default=1, ge=1, le=20)
email: str = ""
address: dict[str, Any] | None = None
def _vip_product_ids() -> set[str]:
return {
str(o["product_id"])
for o in PRODUCT_OFFERS
if not o.get("free") and str(o.get("product_id") or "").strip()
}
def _build_vip_order_payload(openid: str) -> dict[str, Any]:
"""按远程 VIP 方案下单(与小册无关)。"""
cfg = read_vip_config()
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0 or not str(
cfg.get("vipProductId") or ""
).strip():
raise HTTPException(400, "当前为免费会员,无需购买")
product_id = str(cfg["vipProductId"]).strip()
price_fen = int(cfg["vipPriceFen"])
if store.is_unlocked(openid, VIP_BOOK_ID):
raise HTTPException(400, "已是会员,无需重复购买")
user = store.get_user(openid)
if not user or not user.get("session_key"):
raise HTTPException(401, "session_key 缺失,请重新登录")
attach = json.dumps(
{"type": "vip", "book_id": VIP_BOOK_ID, "openid": openid},
ensure_ascii=False,
separators=(",", ":"),
)
out_trade_no = store.create_order(
openid=openid,
book_id=VIP_BOOK_ID,
product_id=product_id,
amount_fen=price_fen,
attach=attach,
)
sign_data = build_sign_data(
offer_id=settings.wx_offer_id,
product_id=product_id,
goods_price=price_fen,
out_trade_no=out_trade_no,
attach=attach,
)
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
signature = calc_signature(sign_data, user["session_key"])
return {
"signData": sign_data,
"mode": "short_series_goods",
"paySig": pay_sig,
"signature": signature,
"outTradeNo": out_trade_no,
"productId": product_id,
"goodsPrice": price_fen,
"kind": "vip",
}
async def _track_vip_order(openid: str, payload: dict[str, Any]) -> None:
try:
from ebook_svc.services.track import ingest_events
await ingest_events(
[
{
"name": "pay_order_created",
"page": "api",
"label": payload.get("productId"),
"props": {
"kind": "vip",
"book_id": VIP_BOOK_ID,
"out_trade_no": payload.get("outTradeNo"),
"price_fen": payload.get("goodsPrice"),
},
"ts": None,
}
],
openid=openid,
client="api",
)
except Exception:
pass
@router.post("/vip-order")
async def create_vip_pay_order(openid: str = Depends(get_current_openid)):
"""VIP 会员虚拟支付下单 — 读 remote-config 道具,不查 books。"""
payload = _build_vip_order_payload(openid)
await _track_vip_order(openid, payload)
return payload
@router.get("/vip-status")
async def vip_status(openid: str = Depends(get_current_openid)):
return {
"ok": True,
"isVip": store.is_unlocked(openid, VIP_BOOK_ID),
"vipBookId": VIP_BOOK_ID,
}
def _require_shop_vip(openid: str) -> None:
cfg = read_vip_config()
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
return
if not store.is_unlocked(openid, VIP_BOOK_ID):
raise HTTPException(403, "开通 VIP 后可使用设备商城")
@router.post("/shop-order")
async def create_shop_pay_order(
body: ShopOrderBody,
openid: str = Depends(get_current_openid),
):
"""电商虚拟支付下单:虚拟发卡 / 实体待发货。"""
_require_shop_vip(openid)
product = shop_store.get_product(body.productId)
if not product:
raise HTTPException(404, "商品不存在")
if int(product.get("stock") or 0) < body.qty:
raise HTTPException(400, "库存不足")
wx_pid = str(product.get("wxProductId") or "").strip()
price_fen = int(product["priceFen"]) * body.qty
if price_fen <= 0:
raise HTTPException(400, "商品价格无效")
if not wx_pid and not settings.debug:
raise HTTPException(400, "商品未配置虚拟支付道具 ID")
if product["goodsType"] == "physical":
addr = body.address or {}
if not (addr.get("userName") and addr.get("telNumber") and addr.get("detailInfo")):
raise HTTPException(400, "实体商品请选择收货地址")
else:
if not (body.email or "").strip():
raise HTTPException(400, "虚拟商品请填写邮箱")
user = store.get_user(openid)
if not user or not user.get("session_key"):
raise HTTPException(401, "session_key 缺失,请重新登录")
# debug 且无道具:用占位 product_id,前端可走 /pay/dev-confirm
pay_product_id = wx_pid or "shop_dev"
attach = json.dumps(
{
"type": "shop",
"book_id": SHOP_BOOK_ID,
"openid": openid,
"product_id": product["id"],
"qty": body.qty,
"goods_type": product["goodsType"],
},
ensure_ascii=False,
separators=(",", ":"),
)
out_trade_no = store.create_order(
openid=openid,
book_id=SHOP_BOOK_ID,
product_id=pay_product_id,
amount_fen=price_fen,
attach=attach,
)
shop_store.create_shop_order(
openid=openid,
product=product,
qty=body.qty,
email=(body.email or "").strip(),
address=body.address,
out_trade_no=out_trade_no,
)
if not wx_pid and settings.debug:
return {
"signData": "",
"mode": "short_series_goods",
"paySig": "",
"signature": "",
"outTradeNo": out_trade_no,
"productId": pay_product_id,
"goodsPrice": price_fen,
"kind": "shop",
"devPay": True,
}
sign_data = build_sign_data(
offer_id=settings.wx_offer_id,
product_id=pay_product_id,
goods_price=price_fen,
out_trade_no=out_trade_no,
attach=attach,
)
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
signature = calc_signature(sign_data, user["session_key"])
return {
"signData": sign_data,
"mode": "short_series_goods",
"paySig": pay_sig,
"signature": signature,
"outTradeNo": out_trade_no,
"productId": pay_product_id,
"goodsPrice": price_fen,
"kind": "shop",
}
@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:
# 兼容旧 VIP 客户端:把 product_id 误当成 book_id 传来 → 走会员单
hint = str(body.book_id or "").strip()
cfg = read_vip_config()
vip_pid = str(cfg.get("vipProductId") or "").strip()
if hint and (hint in _vip_product_ids() or hint == vip_pid or hint == "vip_membership"):
payload = _build_vip_order_payload(openid)
await _track_vip_order(openid, payload)
return payload
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 or not user.get("session_key"):
raise HTTPException(401, "session_key 缺失,请重新登录")
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,
)
sign_data = build_sign_data(
offer_id=settings.wx_offer_id,
product_id=book["product_id"],
goods_price=book["price_fen"],
out_trade_no=out_trade_no,
attach=attach,
)
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
signature = calc_signature(sign_data, user["session_key"])
try:
from ebook_svc.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"],
},
"ts": None,
}
],
openid=openid,
client="api",
)
except Exception:
pass
return {
"signData": sign_data,
"mode": "short_series_goods",
"paySig": pay_sig,
"signature": signature,
"outTradeNo": out_trade_no,
"productId": book["product_id"],
"goodsPrice": book["price_fen"],
"kind": "book",
}
@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")
async def dev_confirm(body: DevConfirmBody, openid: str = Depends(get_current_openid)):
"""仅本地调试:开发者工具无虚拟支付时模拟发货。"""
if not settings.debug:
raise HTTPException(403, "仅 debug 可用")
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"DEV{body.out_trade_no}")
return {"ok": True, "unlocked": True}
@router.post("/query")
async def pay_query(body: StatusBody, openid: str = Depends(get_current_openid)):
data = await query_order(openid, body.out_trade_no)
# 若查单显示已支付则补发货(字段因平台版本可能不同,做宽松判断)
status = str(data.get("status") or data.get("order_state") or "")
if any(x in status.lower() for x in ["success", "paid", "2", "pay"]):
wx_id = str(data.get("wx_order_id") or data.get("order_id") or body.out_trade_no)
store.mark_delivered(body.out_trade_no, wx_order_id=wx_id, raw_notify=json.dumps(data))
return data
def _dig(d: Any, *keys: str) -> Any:
cur = d
for k in keys:
if not isinstance(cur, dict):
return None
cur = cur.get(k)
return cur
SUCCESS_XML = "<xml><ErrCode>0</ErrCode><ErrMsg><![CDATA[success]]></ErrMsg></xml>"
@router.api_route("/notify", methods=["GET", "POST"])
async def pay_notify(request: Request):
"""
微信消息推送 / 虚拟支付发货推送。
MP 后台配置 URL: https://api.nomadro.cn/api/pay/notify
Token / EncodingAESKey 见环境变量 WX_PUSH_*。
"""
from ebook_svc.services.wxmsg import (
build_encrypted_response,
check_signature,
parse_notify_body,
)
qp = {k: v for k, v in request.query_params.items()}
signature = qp.get("signature", "")
timestamp = qp.get("timestamp", "")
nonce = qp.get("nonce", "")
echostr = qp.get("echostr", "")
# 接入校验(GET)
if request.method == "GET":
if check_signature(signature, timestamp, nonce):
return Response(content=echostr, media_type="text/plain")
return Response(content="invalid signature", status_code=403, media_type="text/plain")
# POST:先读 body
raw = await request.body()
text = raw.decode("utf-8", errors="ignore")
# 明文模式验签
if signature and "Encrypt>" not in text and '"Encrypt"' not in text:
if not check_signature(signature, timestamp, nonce):
return Response(content="invalid signature", status_code=403, media_type="text/plain")
try:
root = parse_notify_body(text, qp)
except Exception:
return Response(
content="<xml><ErrCode>1</ErrCode><ErrMsg><![CDATA[decrypt fail]]></ErrMsg></xml>",
media_type="application/xml",
)
# 入库 track_events + 推 ntfy(失败不影响给微信的成功回执)
event = root.get("Event") or root.get("event")
is_pay_event = event == "xpay_goods_deliver_notify" or bool(
_dig(root, "GoodsInfo", "ProductId")
)
if is_pay_event:
openid = root.get("OpenId") or root.get("openid")
out_trade_no = root.get("OutTradeNo") or root.get("out_trade_no")
wx_order_id = _dig(root, "WeChatPayInfo", "MchOrderNo") or root.get("wx_order_id") or out_trade_no
attach = root.get("Attach") or root.get("attach") or "{}"
book_id = "default"
try:
attach_obj = json.loads(attach) if isinstance(attach, str) else attach
if isinstance(attach_obj, dict):
book_id = attach_obj.get("book_id") or book_id
openid = attach_obj.get("openid") or openid
except Exception:
pass
delivered = False
if out_trade_no and store.get_order(str(out_trade_no)):
delivered = store.mark_delivered(
str(out_trade_no), wx_order_id=str(wx_order_id), raw_notify=text
)
elif openid:
store.grant_unlock(str(openid), book_id, source="pay")
delivered = True
try:
from ebook_svc.services.track import ingest_events
gi = root.get("GoodsInfo") or {}
product = ""
if isinstance(gi, dict):
product = str(gi.get("ProductId") or "")
await ingest_events(
[
{
"name": "pay_deliver",
"label": "已解锁" if delivered else "发货推送",
"props": {
"book_id": book_id,
"product": product or "-",
"out_trade_no": str(out_trade_no or "-"),
"delivered": delivered,
},
}
],
openid=str(openid) if openid else None,
client="wx_push",
)
except Exception:
pass
else:
try:
from ebook_svc.services.ntfy import summarize_wx_event
from ebook_svc.services.track import ingest_events
title, message, tags = summarize_wx_event(root if isinstance(root, dict) else {})
openid = root.get("FromUserName") or root.get("OpenId") or root.get("openid")
await ingest_events(
[
{
"name": "wx_push",
"label": title,
"props": {
"event": str(event or root.get("MsgType") or "")[:64],
"message": message[:200],
"tags": tags,
},
}
],
openid=str(openid) if openid else None,
client="wx_push",
)
except Exception:
pass
# 安全模式需加密回复;明文/兼容直接回 XML
if "Encrypt>" in text or '"Encrypt"' in text:
return Response(
content=build_encrypted_response(SUCCESS_XML, nonce or "nonce", timestamp or "0"),
media_type="application/xml",
)
return Response(content=SUCCESS_XML, media_type="application/xml")