This commit is contained in:
eric
2026-03-10 04:42:05 -05:00
parent d77f90cb8c
commit adeb111282
47 changed files with 1154 additions and 460 deletions

23
app/routers/__init__.py Normal file
View File

@@ -0,0 +1,23 @@
"""
项目路由模块
- nomadvip: /nomadvip/*
- digital: /digital/*
- cnomadcna: /cnomadcna/*
- nomadlms: /nomadlms/*
- legacy: /payh5, /zpay_notify 等(向后兼容 digital/cnomadcna
"""
from .nomadvip import router as nomadvip_router
from .digital import router as digital_router
from .cnomadcna import router as cnomadcna_router
from .nomadlms import router as nomadlms_router
from .legacy import router as legacy_router
from .common import router as common_router
__all__ = [
"nomadvip_router",
"digital_router",
"cnomadcna_router",
"nomadlms_router",
"legacy_router",
"common_router",
]

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,213 @@
"""
digital/cnomadcna/nomadlms 共享的支付逻辑
根据 prefix 生成对应 notify_path业务互不影响
"""
import logging
import random
import string
import time
import requests
from fastapi import APIRouter, Request, HTTPException
from ..config import BASE_URL, ZPAY_PID, ZPAY_KEY
from ..payment import get_payment_provider
from ..payment.zpay import ZPayProvider
from ..services import handle_payment_success, processed_orders
def create_digital_router(prefix: str, project_name: str) -> APIRouter:
"""
创建 digital/cnomadcna/nomadlms 的支付路由
prefix: 如 "/digital", "/cnomadcna", "/nomadlms"""legacy
project_name: 用于日志,如 "digital", "cnomadcna", "nomadlms", "legacy"
"""
router = APIRouter(prefix=prefix, tags=[project_name])
def _notify_path(path: str) -> str:
base = BASE_URL.rstrip("/")
if prefix:
return f"{base}{prefix}{path}"
return f"{base}{path}"
@router.post("/payh5")
async def payh5(item: dict):
"""创建 H5 支付订单"""
print(f"{project_name}/payh5 item:", item)
total_fee_yuan = f"{item['total_fee'] / 100:.2f}"
user_id = item.get("user_id", "unknown")
pay_type = item.get("type", "unknown").lower()
random_suffix = "".join(random.choices(string.hexdigits.lower(), k=8))
timestamp = int(time.time())
order_id = f"{user_id}_{pay_type}_order_{timestamp}_{random_suffix}"
type_map = {
"book": "购买书籍",
"meetup": "数字游民社区报名",
"video": "视频解锁",
"vip": "VIP会员充值",
}
name = type_map.get(pay_type, "商品支付")
provider = get_payment_provider()
notify_path = "/xorpay_notify" if provider.name == "xorpay" else "/zpay_notify"
notify_url = _notify_path(notify_path)
channel = item.get("channel", "alipay")
result = provider.create_order(
order_id=order_id,
name=name,
total_fee_yuan=total_fee_yuan,
pay_type=channel,
notify_url=notify_url,
return_url=item.get("return_url"),
client_ip=item.get("client_ip"),
)
if provider.name == "xorpay":
return {
"status": "ok",
"xorpay_params": result.get("params", {}),
"xorpay_url": result.get("pay_url", ""),
"provider": provider.name,
}
params = result.get("params", {})
params_str = {k: str(v) for k, v in params.items() if v is not None and str(v).strip() != ""}
return {
"status": "ok",
"params": params_str,
"pay_url": result.get("pay_url", ""),
"provider": provider.name,
"submit_method": "POST",
}
@router.post("/payh5/redirect")
async def payh5_redirect(item: dict, request: Request):
"""ZPAY mapi 接口,返回 302 或二维码"""
from fastapi.responses import RedirectResponse, JSONResponse
provider = get_payment_provider()
if provider.name != "zpay":
raise HTTPException(status_code=400, detail="payh5/redirect 仅支持 zpay 渠道")
total_fee = float(item.get("total_fee", 80))
total_fee_yuan = f"{total_fee / 100:.2f}"
user_id = item.get("user_id", "unknown")
pay_type = item.get("type", "unknown").lower()
channel = item.get("channel", "alipay")
return_url = item.get("return_url")
device = item.get("device", "pc")
client_ip = item.get("client_ip") or (request.client.host if request.client else "127.0.0.1")
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
client_ip = forwarded.split(",")[0].strip()
random_suffix = "".join(random.choices(string.hexdigits.lower(), k=8))
timestamp = int(time.time())
order_id = f"{user_id}_{pay_type}_order_{timestamp}_{random_suffix}"
type_map = {
"book": "购买书籍",
"meetup": "数字游民社区报名",
"video": "视频解锁",
"vip": "VIP会员充值",
}
name = type_map.get(pay_type, "商品支付")
notify_url = _notify_path("/zpay_notify")
if not isinstance(provider, ZPayProvider):
raise HTTPException(status_code=400, detail="payh5/redirect 仅支持 zpay")
result = provider.create_order_api(
order_id=order_id,
name=name,
total_fee_yuan=total_fee_yuan,
pay_type=channel,
notify_url=notify_url,
return_url=return_url,
client_ip=client_ip,
device=device,
)
if result.get("status") != "ok":
raise HTTPException(status_code=500, detail=result.get("msg", "ZPAY mapi 创建订单失败"))
payurl = result.get("payurl")
payurl2 = result.get("payurl2")
img = result.get("img")
if device == "pc" and img:
return JSONResponse(status_code=200, content={
"status": "ok", "qrcode_mode": True, "order_id": order_id,
"img": img, "payurl": payurl, "return_url": return_url, "channel": channel,
})
if device == "wechat" and channel.lower() in ("wxpay", "wx", "wechat"):
return JSONResponse(status_code=200, content={"use_form": True, "order_id": order_id})
headers = {"X-Pay-Order-Id": order_id}
if device == "h5" and channel.lower() in ("wxpay", "wx", "wechat") and payurl2:
return RedirectResponse(url=payurl2, status_code=302, headers=headers)
if payurl:
return RedirectResponse(url=payurl, status_code=302, headers=headers)
raise HTTPException(status_code=500, detail="ZPAY 未返回支付链接")
@router.get("/zpay_order_status")
async def zpay_order_status(out_trade_no: str):
"""查询 ZPAY 订单支付状态"""
provider = get_payment_provider()
if provider.name != "zpay":
raise HTTPException(status_code=400, detail="仅 zpay 渠道支持")
url = f"https://zpayz.cn/api.php?act=order&pid={ZPAY_PID}&key={ZPAY_KEY}&out_trade_no={out_trade_no}"
try:
resp = requests.get(url, timeout=10)
result = resp.json() if resp.ok else {}
except Exception as e:
logging.warning(f"ZPAY 订单查询失败: {e}")
return {"paid": False, "error": str(e)}
try:
code = result.get("code", 0)
code = int(code) if isinstance(code, (int, float)) or str(code).isdigit() else 0
except (ValueError, TypeError):
code = 0
if code != 1:
return {"paid": False, "msg": result.get("msg", "查询失败")}
try:
status = int(result.get("status", 0))
except (ValueError, TypeError):
status = 0
return {"paid": status == 1, "status": status}
@router.post("/xorpay_notify")
async def xorpay_notify(request: Request):
"""XorPay 异步通知"""
form_data = await request.form()
data = {k: v for k, v in form_data.items()}
logging.info(f"{project_name} XorPay 异步通知: {data}")
order_id = data.get("order_id", "")
if order_id in processed_orders:
return "ok"
provider = get_payment_provider()
if provider.name != "xorpay":
raise HTTPException(status_code=400, detail="xorpay_notify only for xorpay")
if not provider.verify_notify(data):
logging.error(f"{project_name} XorPay 验签失败: {data}")
raise HTTPException(status_code=400, detail="sign error")
parsed = provider.parse_notify(data)
if parsed.get("trade_status") != "success":
return "ok"
handle_payment_success(order_id, parsed.get("pay_price", data.get("pay_price", "")), f"{project_name}-xorpay", use_memos=False)
return provider.success_response()
@router.get("/zpay_notify")
@router.post("/zpay_notify")
async def zpay_notify(request: Request):
"""ZPAY 异步通知"""
if request.method == "GET":
data = dict(request.query_params)
else:
form_data = await request.form()
data = {k: v for k, v in form_data.items()}
logging.info(f"{project_name} ZPAY 异步通知: {data}")
order_id = data.get("out_trade_no", "")
if order_id in processed_orders:
return "success"
provider = get_payment_provider()
if provider.name != "zpay":
raise HTTPException(status_code=400, detail="zpay_notify only for zpay")
if not provider.verify_notify(data):
logging.error(f"{project_name} ZPAY 验签失败: {data}")
raise HTTPException(status_code=400, detail="sign error")
parsed = provider.parse_notify(data)
if parsed.get("trade_status") != "success":
return "success"
handle_payment_success(order_id, parsed.get("pay_price", data.get("money", "")), f"{project_name}-zpay", use_memos=False)
return provider.success_response()
return router

4
app/routers/cnomadcna.py Normal file
View File

@@ -0,0 +1,4 @@
"""cnomadcna 项目支付接口:/cnomadcna/*"""
from ._digital_base import create_digital_router
router = create_digital_router(prefix="/cnomadcna", project_name="cnomadcna")

65
app/routers/common.py Normal file
View File

@@ -0,0 +1,65 @@
"""共享接口meetup 申请、create_user 等"""
import logging
import time
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from ..services import get_pb_client
from ..sdk.memos import MemosSDK
from ..config import MEMOS_API, MEMOS_TOKEN
router = APIRouter(tags=["common"])
@router.post("/submit_meetup_application")
async def submit_meetup_application(item: dict):
"""数字游民社区报名表单"""
print("submit_meetup_application item:", item)
user_id = item.get("user_id")
if not user_id:
raise HTTPException(status_code=400, detail="missing user_id")
try:
pb_client = get_pb_client()
solan = pb_client.collection("solan")
pb_data = {
"user_id": user_id,
"nickname": item.get("nickname", ""),
"occupation": item.get("occupation", ""),
"reason": item.get("reason", ""),
"wechatId": item.get("wechatId", ""),
"gender": item.get("gender", ""),
"education": item.get("education", ""),
"gradYear": item.get("gradYear", ""),
"phone": item.get("phone", ""),
"calculated_age": item.get("calculated_age", 0),
"type": "",
"order_id": "",
"amount": 0,
}
record = solan.create(pb_data)
logging.info(f"meetup 申请表单提交成功(待支付) - user_id: {user_id}, record_id: {record.id}")
return {"status": "ok", "record_id": record.id}
except Exception as e:
print(f"meetup 申请提交失败: {e}")
logging.error(f"meetup 申请提交失败 - user_id: {user_id}, error: {e}")
raise HTTPException(status_code=500, detail="submit failed")
class CreateUserRequest(BaseModel):
username: str | None = None
password: str | None = None
@router.post("/create_user")
async def create_user(item: CreateUserRequest):
"""创建 Memos 用户(基于 MemosSDK"""
sdk = MemosSDK(api_url=MEMOS_API, token=MEMOS_TOKEN, enabled=bool(MEMOS_API and MEMOS_TOKEN))
if not sdk.enabled:
return {"error": "Memos 未配置"}
timenew = str(int(time.time()))
username = item.username or f"user{timenew}"
password = item.password or "123456"
result = sdk.create_user_by_username(username=username, password=password)
print("memos_result-", result)
return result

4
app/routers/digital.py Normal file
View File

@@ -0,0 +1,4 @@
"""digital 项目支付接口:/digital/*"""
from ._digital_base import create_digital_router
router = create_digital_router(prefix="/digital", project_name="digital")

4
app/routers/legacy.py Normal file
View File

@@ -0,0 +1,4 @@
"""向后兼容:/payh5、/zpay_notify 等digital/cnomadcna/nomadlms 旧版调用)"""
from ._digital_base import create_digital_router
router = create_digital_router(prefix="", project_name="legacy")

4
app/routers/nomadlms.py Normal file
View File

@@ -0,0 +1,4 @@
"""nomadlms 项目支付接口:/nomadlms/*"""
from ._digital_base import create_digital_router
router = create_digital_router(prefix="/nomadlms", project_name="nomadlms")

163
app/routers/nomadvip.py Normal file
View File

@@ -0,0 +1,163 @@
"""nomadvip 项目支付接口:/nomadvip/*,固定 ZPAY"""
import logging
import random
import string
import time
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
import requests
from ..config import BASE_URL, ZPAY_PID, ZPAY_KEY
from ..payment.zpay import ZPayProvider
from ..services import handle_payment_success, processed_orders
router = APIRouter(prefix="/nomadvip", tags=["nomadvip"])
_nomadvip_zpay = ZPayProvider(pid=ZPAY_PID, key=ZPAY_KEY)
@router.post("/payh5")
async def nomadvip_payh5(item: dict):
"""nomadvip 专用:固定 ZPAY表单提交支付"""
print("nomadvip/payh5 item:", item)
total_fee = int(item.get("total_fee", 8800))
total_fee_yuan = f"{total_fee / 100:.2f}"
user_id = item.get("user_id", "unknown")
pay_type = (item.get("type") or "vip").lower()
random_suffix = "".join(random.choices(string.hexdigits.lower(), k=8))
timestamp = int(time.time())
order_id = f"{user_id}_{pay_type}_order_{timestamp}_{random_suffix}"
type_map = {
"book": "购买书籍",
"meetup": "数字游民社区报名",
"video": "视频解锁",
"vip": "VIP会员充值",
}
name = type_map.get(pay_type, "VIP会员充值")
notify_url = f"{BASE_URL.rstrip('/')}/nomadvip/zpay_notify"
channel = item.get("channel", "alipay")
result = _nomadvip_zpay.create_order(
order_id=order_id,
name=name,
total_fee_yuan=total_fee_yuan,
pay_type=channel,
notify_url=notify_url,
return_url=item.get("return_url"),
client_ip=item.get("client_ip"),
)
params = result.get("params", {})
params_str = {k: str(v) for k, v in params.items() if v is not None and str(v).strip() != ""}
return {
"status": "ok",
"params": params_str,
"pay_url": result.get("pay_url", ""),
"provider": "zpay",
"submit_method": "POST",
}
@router.post("/payh5/redirect")
async def nomadvip_payh5_redirect(item: dict, request: Request):
"""nomadvip 专用ZPAY mapi 接口"""
total_fee = float(item.get("total_fee", 8800))
total_fee_yuan = f"{total_fee / 100:.2f}"
user_id = item.get("user_id", "unknown")
pay_type = (item.get("type") or "vip").lower()
channel = item.get("channel", "alipay")
return_url = item.get("return_url")
device = item.get("device", "pc")
client_ip = item.get("client_ip") or (request.client.host if request.client else "127.0.0.1")
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
client_ip = forwarded.split(",")[0].strip()
random_suffix = "".join(random.choices(string.hexdigits.lower(), k=8))
timestamp = int(time.time())
order_id = f"{user_id}_{pay_type}_order_{timestamp}_{random_suffix}"
type_map = {"book": "购买书籍", "meetup": "数字游民社区报名", "video": "视频解锁", "vip": "VIP会员充值"}
name = type_map.get(pay_type, "VIP会员充值")
notify_url = f"{BASE_URL.rstrip('/')}/nomadvip/zpay_notify"
result = _nomadvip_zpay.create_order_api(
order_id=order_id,
name=name,
total_fee_yuan=total_fee_yuan,
pay_type=channel,
notify_url=notify_url,
return_url=return_url,
client_ip=client_ip,
device=device,
)
if result.get("status") != "ok":
raise HTTPException(status_code=500, detail=result.get("msg", "ZPAY mapi 创建订单失败"))
payurl = result.get("payurl")
payurl2 = result.get("payurl2")
img = result.get("img")
if device == "pc" and img:
return JSONResponse(status_code=200, content={
"status": "ok", "qrcode_mode": True, "order_id": order_id,
"img": img, "payurl": payurl, "return_url": return_url, "channel": channel,
})
if device == "wechat" and channel.lower() in ("wxpay", "wx", "wechat"):
return JSONResponse(status_code=200, content={"use_form": True, "order_id": order_id})
headers = {"X-Pay-Order-Id": order_id}
if device == "h5" and channel.lower() in ("wxpay", "wx", "wechat") and payurl2:
return RedirectResponse(url=payurl2, status_code=302, headers=headers)
if payurl:
return RedirectResponse(url=payurl, status_code=302, headers=headers)
raise HTTPException(status_code=500, detail="ZPAY 未返回支付链接")
@router.get("/zpay_order_status")
async def nomadvip_zpay_order_status(out_trade_no: str):
"""nomadvip 专用:查询 ZPAY 订单支付状态"""
url = f"https://zpayz.cn/api.php?act=order&pid={ZPAY_PID}&key={ZPAY_KEY}&out_trade_no={out_trade_no}"
try:
resp = requests.get(url, timeout=10)
result = resp.json() if resp.ok else {}
except Exception as e:
logging.warning(f"nomadvip ZPAY 订单查询失败: {e}")
return {"paid": False, "error": str(e)}
try:
code = result.get("code", 0)
code = int(code) if isinstance(code, (int, float)) or str(code).isdigit() else 0
except (ValueError, TypeError):
code = 0
if code != 1:
return {"paid": False, "msg": result.get("msg", "查询失败")}
try:
status = int(result.get("status", 0))
except (ValueError, TypeError):
status = 0
return {"paid": status == 1, "status": status}
@router.get("/zpay_notify")
@router.post("/zpay_notify")
async def nomadvip_zpay_notify(request: Request):
"""nomadvip 专用ZPAY 异步通知"""
if request.method == "GET":
data = dict(request.query_params)
else:
form_data = await request.form()
data = {k: v for k, v in form_data.items()}
logging.info(f"nomadvip ZPAY 异步通知: {data}")
order_id = data.get("out_trade_no", "")
if order_id in processed_orders:
logging.info(f"nomadvip 订单已处理,跳过: {order_id}")
return "success"
if not _nomadvip_zpay.verify_notify(data):
logging.error(f"nomadvip ZPAY 验签失败: {data}")
raise HTTPException(status_code=400, detail="sign error")
parsed = _nomadvip_zpay.parse_notify(data)
trade_status = parsed.get("trade_status") or data.get("trade_status", "")
if trade_status != "success" and trade_status != "TRADE_SUCCESS":
logging.info(f"nomadvip 非成功状态,跳过: trade_status={trade_status}")
return "success"
pay_price = parsed.get("pay_price") or data.get("money", "")
try:
handle_payment_success(order_id, pay_price, "nomadvip-zpay", use_memos=True)
logging.info(f"nomadvip 业务处理完成: order_id={order_id}")
except Exception as e:
logging.error(f"nomadvip PocketBase/Memos 处理异常: {e}", exc_info=True)
raise
return _nomadvip_zpay.success_response()