返回首页

FastAPI + Marzban:VPN 服务的自动化

服务自动化颁发 VPN 密钥:注册、支付、来自 Marzban 的 vless。使用 FastAPI async、PostgreSQL、幂等的 YUKassa webhooks、Cloudflare。代码细节:模型、缓存、试用、后台任务。

构建 VPN 服务:FastAPI、Marzban、异步 SQLAlchemy
Advertisement 728x90

基于FastAPI、Marzban与Docker集成的自动化VPN保护服务

FastAPI后端与Marzban集成,用于创建VPN用户,集成YooKassa处理支付,Resend发送邮件。用户注册、验证邮箱、支付后,即可即时获取vless密钥。异步SQLAlchemy架构支持并行处理Webhook、Marzban API请求和邮件发送,避免阻塞。

技术栈:Python 3.11、FastAPI、PostgreSQL、React 18 + Vite + Tailwind、通过Marzban使用XRay-core、Docker Compose + Nginx + Cloudflare。

系统架构

流量流向:Cloudflare → Nginx:静态React运行在:3000端口,API运行在:8080端口。FastAPI路由(/auth、/configs、/payment)与PostgreSQL、Marzban REST API、Resend和YooKassa/Plisio交互。

Google AdInline article slot

Marzban在Docker外部的主机上运行;容器通过桥接接口通信。

用户
    ↓ HTTPS
Cloudflare
    ↓
Nginx
  / → 前端:3000
  /api/ → 后端:8080
    ↓
FastAPI → PostgreSQL | Marzban | Resend | YooKassa

数据库模型

关键实体:

class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(unique=True, index=True)
    hashed_password: Mapped[str]
    is_verified: Mapped[bool] = mapped_column(default=False)
    marzban_username: Mapped[str | None] = mapped_column(unique=True, nullable=True)
    referral_code: Mapped[str] = mapped_column(unique=True, default=lambda: secrets.token_urlsafe(8))
    trial_used: Mapped[bool] = mapped_column(default=False)
    email_verify_token: Mapped[str | None] = mapped_column(nullable=True, index=True)

class Subscription(Base):
    __tablename__ = "subscriptions"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    plan: Mapped[str]
    status: Mapped[str]  # active | expired | pending
    devices: Mapped[int] = mapped_column(default=1)
    started_at: Mapped[datetime] = mapped_column(server_default=func.now())
    expires_at: Mapped[datetime]
    marzban_expire_ts: Mapped[int]

class Payment(Base):
    __tablename__ = "payments"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    provider: Mapped[str]  # yookassa | plisio
    external_id: Mapped[str]
    amount: Mapped[float]
    status: Mapped[str]  # pending | paid | failed
    plan: Mapped[str]
    months: Mapped[int]

Marzban集成

API令牌缓存

Marzban令牌一小时后过期。使用asyncio.Lock实现55分钟缓存,防止竞态条件:

Google AdInline article slot
class MarzbanService:
    def __init__(self):
        self._token: str | None = None
        self._token_expires_at: float = 0
        self._lock = asyncio.Lock()

    async def get_token(self) -> str:
        async with self._lock:
            if self._token and time.time() < self._token_expires_at:
                return self._token
            self._token = await self._fetch_token()
            self._token_expires_at = time.time() + 55 * 60
            return self._token

创建VPN用户

async def create_user(self, username: str, months: int, days: int = 0) -> dict:
    expire_ts = _months_to_timestamp(months)
    if days:
        expire_ts = int(datetime.now(timezone.utc).timestamp()) + days * 86400

    payload = {
        "username": username,
        "proxies": {"vless": {"flow": "xtls-rprx-vision"}},
        "inbounds": {"vless": ["VLESS Reality"]},
        "expire": expire_ts,
        "data_limit": 0,
        "data_limit_reset_strategy": "no_reset",
    }
    async with httpx.AsyncClient(timeout=15) as client:
        resp = await client.post(
            f"{settings.MARZBAN_URL}/api/user",
            json=payload,
            headers=await self._headers(),
        )
        resp.raise_for_status()
        return resp.json()

Marzban在links字段中返回一个可用的vless://...链接。

订阅续订

对于已过期的订阅,续订从当前时间开始:

async def extend_subscription(self, username: str, months: int) -> dict:
    user = await self.get_user(username)
    current_expire = user.get("expire") or 0
    base = max(current_expire, int(time.time()))
    base_dt = datetime.fromtimestamp(base, tz=timezone.utc)
    # PUT /api/user/{username} 更新过期时间

YooKassa Webhook处理

幂等性至关重要:如果延迟超过10秒,YooKassa会重复发送Webhook。

Google AdInline article slot
async def activate_subscription(payment: Payment) -> None:
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(Payment).where(Payment.id == payment.id))
        fresh_payment = result.scalar_one()
        if fresh_payment.status == "paid":
            logger.info(f"支付 {payment.id} 已激活,跳过")
            return
        try:
            await _do_activate(fresh_payment, session)
        except Exception as e:
            await session.rollback()
            logger.error(f"激活失败: {e}", exc_info=True)
            raise

使用独立于Webhook的新数据库会话。

Cloudflare的IP白名单:

client_ip = request.headers.get("CF-Connecting-IP") or request.headers.get("X-Forwarded-For", "").split(",")[0].strip() or request.client.host
allowed_prefixes = ("185.71.76.", "185.71.77.", "77.75.153.", "77.75.154.", "77.75.156.")
if client_ip not in {"77.75.156.11", "77.75.156.35"} and not any(client_ip.startswith(p) for p in allowed_prefixes):
    raise HTTPException(403)

试用与验证

邮箱确认后提供3天VPN试用:

  • 用户注册,通过邮件接收令牌。
  • GET /verify-email/{token} 激活is_verified=True
  • 后台任务创建Marzban用户,设置days=3,标记trial_used=True

检查:无活跃订阅且未使用过试用。

动态订阅与设备管理

额外设备购买(每个+99₽)在续订时保留:

extra_devices = max(0, existing_sub.devices - plan_cfg["devices"])
existing_sub.devices = plan_cfg["devices"] + extra_devices

价格:基础价格 + 额外设备数 * DEVICE_ADD_PRICE。

后台任务

使用APScheduler实现自动化:

  • 每日报告(8:00)。
  • 过期提醒(9:00)。
  • 待处理支付检查(每5分钟)。
scheduler = AsyncIOScheduler(timezone="Europe/Moscow")
scheduler.add_job(send_daily_report, CronTrigger(hour=8, minute=0), id="daily_report")

Docker Compose问题

Ubuntu 22.04上的v1.29版本在重建时崩溃:KeyError: 'ContainerConfig'。解决方案:

docker-compose stop service
docker-compose rm -f service
docker-compose up -d service

关键要点

  • 异步FastAPI + SQLAlchemy确保并发性,避免GIL问题。
  • Webhook幂等性防止重复订阅。
  • 带锁的Marzban令牌缓存最小化API请求。
  • Cloudflare需要显式验证CF-Connecting-IP以用于YooKassa。
  • 通过邮箱验证的试用限制滥用。

— Editorial Team

Advertisement 728x90

继续阅读