Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API. Co-authored-by: Cursor <cursoragent@cursor.com>
312 lines
9.2 KiB
Python
312 lines
9.2 KiB
Python
"""
|
||
Nomadro unified API gateway (FastAPI).
|
||
|
||
Vertical backends stay in apps/*/backend and apps/payjsapi.
|
||
This service is the stable public surface for docs/SDK + module registry + ops hooks.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from datetime import datetime, timezone
|
||
from typing import Any
|
||
|
||
import httpx
|
||
from fastapi import FastAPI, Header, HTTPException
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from pydantic import BaseModel, Field
|
||
|
||
APP_NAME = "nomadro-api"
|
||
APP_VERSION = "0.1.0"
|
||
|
||
PAYJSAPI_URL = os.getenv("PAYJSAPI_URL", "http://127.0.0.1:8007").rstrip("/")
|
||
COMMUNITY_API_URL = os.getenv("COMMUNITY_API_URL", "http://127.0.0.1:8055").rstrip("/")
|
||
EBOOK_API_URL = os.getenv("EBOOK_API_URL", "http://127.0.0.1:8010").rstrip("/")
|
||
POCKETBASE_URL = os.getenv("POCKETBASE_URL", "http://127.0.0.1:8090").rstrip("/")
|
||
|
||
app = FastAPI(
|
||
title="Nomadro API",
|
||
description=(
|
||
"统一 API/SDK 出口。支付:海外 creem/nowpayments,国内 zpay/xpay。"
|
||
"垂直业务经模块注册表转发,详见 /v1/modules。"
|
||
),
|
||
version=APP_VERSION,
|
||
docs_url="/docs",
|
||
redoc_url="/redoc",
|
||
openapi_url="/openapi.json",
|
||
)
|
||
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=os.getenv("CORS_ORIGINS", "*").split(","),
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
|
||
class ModuleInfo(BaseModel):
|
||
id: str
|
||
name: str
|
||
mount: str
|
||
backend: str
|
||
payment: list[str] = Field(default_factory=list)
|
||
status: str = "active"
|
||
|
||
|
||
class HealthBody(BaseModel):
|
||
ok: bool
|
||
service: str
|
||
version: str
|
||
ts: str
|
||
upstreams: dict[str, Any]
|
||
|
||
|
||
MODULES: list[ModuleInfo] = [
|
||
ModuleInfo(
|
||
id="nav",
|
||
name="出海导航",
|
||
mount="/nav",
|
||
backend="static",
|
||
payment=[],
|
||
),
|
||
ModuleInfo(
|
||
id="book",
|
||
name="数字游民小册",
|
||
mount="/book",
|
||
backend=EBOOK_API_URL,
|
||
payment=["creem", "nowpayments"],
|
||
),
|
||
ModuleInfo(
|
||
id="community",
|
||
name="旅居社群",
|
||
mount="/community",
|
||
backend=COMMUNITY_API_URL,
|
||
payment=["zpay", "xpay"],
|
||
),
|
||
ModuleInfo(
|
||
id="vip",
|
||
name="私域会员",
|
||
mount="/vip",
|
||
backend=PAYJSAPI_URL,
|
||
payment=["zpay", "xpay", "creem"],
|
||
),
|
||
ModuleInfo(
|
||
id="pay",
|
||
name="支付网关 payjsapi",
|
||
mount="/pay",
|
||
backend=PAYJSAPI_URL,
|
||
payment=["creem", "nowpayments", "zpay", "xpay"],
|
||
),
|
||
]
|
||
|
||
|
||
async def _probe(url: str, path: str = "/") -> dict[str, Any]:
|
||
target = f"{url}{path}"
|
||
try:
|
||
async with httpx.AsyncClient(timeout=3.0) as client:
|
||
res = await client.get(target)
|
||
return {"ok": res.status_code < 500, "status": res.status_code, "url": target}
|
||
except Exception as exc: # noqa: BLE001
|
||
return {"ok": False, "error": str(exc), "url": target}
|
||
|
||
|
||
@app.get("/")
|
||
async def root() -> dict[str, str]:
|
||
return {
|
||
"name": APP_NAME,
|
||
"version": APP_VERSION,
|
||
"docs": "/docs",
|
||
"openapi": "/openapi.json",
|
||
"health": "/v1/health",
|
||
"modules": "/v1/modules",
|
||
"sdk": "packages/@nomadro/sdk",
|
||
}
|
||
|
||
|
||
@app.get("/v1/health", response_model=HealthBody)
|
||
async def health() -> HealthBody:
|
||
upstreams = {
|
||
"payjsapi": await _probe(PAYJSAPI_URL, "/"),
|
||
"community": await _probe(COMMUNITY_API_URL, "/api/v1/health"),
|
||
"ebook": await _probe(EBOOK_API_URL, "/"),
|
||
"pocketbase": await _probe(POCKETBASE_URL, "/api/health"),
|
||
}
|
||
return HealthBody(
|
||
ok=True,
|
||
service=APP_NAME,
|
||
version=APP_VERSION,
|
||
ts=datetime.now(timezone.utc).isoformat(),
|
||
upstreams=upstreams,
|
||
)
|
||
|
||
|
||
@app.get("/v1/modules", response_model=list[ModuleInfo])
|
||
async def list_modules() -> list[ModuleInfo]:
|
||
return MODULES
|
||
|
||
|
||
@app.get("/v1/modules/{module_id}", response_model=ModuleInfo)
|
||
async def get_module(module_id: str) -> ModuleInfo:
|
||
for m in MODULES:
|
||
if m.id == module_id:
|
||
return m
|
||
raise HTTPException(status_code=404, detail=f"unknown module: {module_id}")
|
||
|
||
|
||
class PayRouteRequest(BaseModel):
|
||
region: str = Field(default="auto", description="cn | overseas | auto")
|
||
is_china_user: bool | None = None
|
||
user_agent: str | None = None
|
||
|
||
|
||
class PayRouteResponse(BaseModel):
|
||
env: str
|
||
provider: str
|
||
channel: str
|
||
note: str
|
||
|
||
|
||
@app.post("/v1/pay/resolve", response_model=PayRouteResponse)
|
||
async def resolve_pay(body: PayRouteRequest) -> PayRouteResponse:
|
||
"""Mirror @nomadro/pay.resolvePayProvider for non-TS clients."""
|
||
ua = (body.user_agent or "").lower()
|
||
is_wechat = "micromessenger" in ua
|
||
is_mobile = any(x in ua for x in ("mobile", "android", "iphone", "ipad"))
|
||
env = "wechat" if is_wechat else ("h5" if is_mobile else "pc")
|
||
|
||
region = body.region
|
||
if region == "auto":
|
||
region = "overseas" if body.is_china_user is False else "cn"
|
||
|
||
if region == "overseas":
|
||
return PayRouteResponse(
|
||
env=env,
|
||
provider="creem",
|
||
channel="wxpay",
|
||
note="overseas → creem (fallback nowpayments in vertical backends)",
|
||
)
|
||
if env == "wechat":
|
||
return PayRouteResponse(
|
||
env=env,
|
||
provider="xpay",
|
||
channel="wxpay",
|
||
note="CN WeChat in-app → xpay/xorpay",
|
||
)
|
||
return PayRouteResponse(
|
||
env=env,
|
||
provider="zpay",
|
||
channel="wxpay",
|
||
note="CN PC/H5 browser → zpay",
|
||
)
|
||
|
||
|
||
@app.get("/v1/config")
|
||
async def get_remote_config() -> dict[str, Any]:
|
||
"""前端远程配置;文件缺失时返回内置默认(离线客户端也有同结构兜底)。"""
|
||
import json
|
||
from pathlib import Path
|
||
|
||
candidates = [
|
||
Path(__file__).resolve().parents[3] / "data" / "remote-config.json",
|
||
Path.cwd() / "data" / "remote-config.json",
|
||
]
|
||
for path in candidates:
|
||
try:
|
||
if path.is_file():
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
return {"ok": True, "source": "file", "config": data}
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
return {
|
||
"ok": True,
|
||
"source": "default",
|
||
"config": {
|
||
"version": 1,
|
||
"updatedAt": datetime.now(timezone.utc).isoformat(),
|
||
"modules": {
|
||
"home": {"enabled": True, "title": "首页", "tabLabel": "首页"},
|
||
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
|
||
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
|
||
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
|
||
"destinations": {"enabled": True, "title": "目的地"},
|
||
"meetups": {"enabled": True, "title": "活动"},
|
||
"vip": {"enabled": True, "title": "私域会员"},
|
||
},
|
||
"flags": {
|
||
"payEnabled": True,
|
||
"socialFollow": True,
|
||
"offlineBadge": True,
|
||
},
|
||
"copy": {
|
||
"homeBrand": "nomadro",
|
||
"homeTagline": "三端完整整合",
|
||
"homeLead": "导航 + 小册 + 社群 + VIP",
|
||
"vipPriceFen": 8800,
|
||
"vipProductId": "vip_membership",
|
||
"vipCta": "立即开通",
|
||
},
|
||
},
|
||
}
|
||
|
||
|
||
@app.get("/v1/pay/proxy/health")
|
||
async def pay_proxy_health() -> dict[str, Any]:
|
||
return await _probe(PAYJSAPI_URL, "/")
|
||
|
||
|
||
class WxLoginBody(BaseModel):
|
||
code: str
|
||
|
||
|
||
class WxPayOrderBody(BaseModel):
|
||
product_id: str = Field(default="vip_membership")
|
||
goods_price: int = Field(default=8800, description="价格(分)")
|
||
|
||
|
||
@app.post("/v1/miniprogram/wx/login")
|
||
async def wx_mini_login(body: WxLoginBody) -> dict[str, Any]:
|
||
"""微信小程序 code2session → token(内存会话;生产应换 PB/Redis)。"""
|
||
from .wx_virtual_pay import code2session, store_session
|
||
|
||
try:
|
||
data = await code2session(body.code)
|
||
except Exception as exc: # noqa: BLE001
|
||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||
token = store_session(data["openid"], data["session_key"])
|
||
return {"token": token, "openid": data["openid"]}
|
||
|
||
|
||
@app.post("/v1/miniprogram/wx/pay/order")
|
||
async def wx_mini_pay_order(
|
||
body: WxPayOrderBody,
|
||
authorization: str | None = Header(default=None),
|
||
) -> dict[str, str]:
|
||
"""签发 requestVirtualPayment 所需签名参数。"""
|
||
import secrets
|
||
import time
|
||
|
||
from .wx_virtual_pay import get_session, make_pay_payload
|
||
|
||
token = (authorization or "").replace("Bearer", "").strip()
|
||
sess = get_session(token)
|
||
if not sess:
|
||
raise HTTPException(status_code=401, detail="未登录或会话失效,请重新登录")
|
||
out_trade_no = f"vip_{int(time.time())}_{secrets.token_hex(4)}"
|
||
try:
|
||
return make_pay_payload(
|
||
session_key=sess["session_key"],
|
||
product_id=body.product_id,
|
||
goods_price=body.goods_price,
|
||
out_trade_no=out_trade_no,
|
||
)
|
||
except Exception as exc: # noqa: BLE001
|
||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import uvicorn
|
||
|
||
port = int(os.getenv("PORT", "8000"))
|
||
uvicorn.run("app.main:app", host="0.0.0.0", port=port, reload=False)
|