nomadro/apps/api/app/main.py
eric 56b29205e7 Integrate four verticals into nomadro portal with shared packages and API gateway.
Mount /vip with nomadvip+payjsapi, add @nomadro/pay|pb|sdk, apps/api, /admin shell, and backup/rollback scripts under git.nomadro.cn workflow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:16:44 -05:00

214 lines
5.7 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.

"""
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, 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/pay/proxy/health")
async def pay_proxy_health() -> dict[str, Any]:
return await _probe(PAYJSAPI_URL, "/")
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)