nomadro/apps/ebook/wemini/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

262 lines
9.3 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 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
from app.services.wxpay import build_sign_data, calc_pay_sig, calc_signature, query_order
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 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 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"],
},
"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"],
}
@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 app.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 app.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 app.services.ntfy import summarize_wx_event
from app.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")