SaaS全栈开发实战 · 从零到上线
订阅计费是SaaS的收入引擎。本课将实现完整的订阅管理系统,包括订阅周期管理、升降级处理、按比例计费、试用期、以及计费状态机。这些是SaaS商业逻辑的核心。
# app/services/subscription_service.py
from datetime import datetime, timedelta
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class SubscriptionStatus(str, Enum):
TRIAL = "trial"
ACTIVE = "active"
PAST_DUE = "past_due"
CANCELED = "canceled"
EXPIRED = "expired"
class SubscriptionService:
"""订阅管理服务"""
# 套餐定价(月费,单位:分)
PLAN_PRICES = {
"free": 0,
"starter": 900, # $9/月
"pro": 2900, # $29/月
"enterprise": 9900, # $99/月
}
# 试用期天数
TRIAL_DAYS = 14
# 允许的状态转换
TRANSITIONS = {
"trial": ["active", "expired"],
"active": ["past_due", "canceled"],
"past_due": ["active", "canceled"],
"canceled": ["expired", "active"], # 可重新激活
"expired": ["active"], # 可重新订阅
}
@classmethod
def can_transition(cls, from_status: str, to_status: str) -> bool:
return to_status in cls.TRANSITIONS.get(from_status, [])
@classmethod
def start_trial(cls) -> dict:
"""开始试用期"""
now = datetime.utcnow()
return {
"status": SubscriptionStatus.TRIAL,
"trial_start": now,
"trial_end": now + timedelta(days=cls.TRIAL_DAYS),
}
@classmethod
def activate_subscription(cls, plan: str) -> dict:
"""激活订阅"""
now = datetime.utcnow()
return {
"status": SubscriptionStatus.ACTIVE,
"plan": plan,
"current_period_start": now,
"current_period_end": now + timedelta(days=30),
}
@classmethod
def calculate_proration(cls, old_plan: str, new_plan: str,
days_remaining: int, days_in_period: int = 30) -> int:
"""按比例计费计算"""
old_price = cls.PLAN_PRICES[old_plan]
new_price = cls.PLAN_PRICES[new_plan]
# 旧套餐剩余价值
old_remaining = (old_price * days_remaining) // days_in_period
# 新套餐剩余周期费用
new_remaining = (new_price * days_remaining) // days_in_period
# 差额(可为负,表示降级退款)
proration = new_remaining - old_remaining
return proration
@classmethod
def cancel_subscription(cls, at_period_end: bool = True) -> dict:
"""取消订阅"""
now = datetime.utcnow()
return {
"status": SubscriptionStatus.CANCELED if not at_period_end
else "active", # 周期结束才取消
"cancel_at_period_end": at_period_end,
"canceled_at": now,
}
# ✅ 验证通过 - 订阅服务
svc = SubscriptionService
print(f"可从trial转到active: {svc.can_transition('trial', 'active')}") # True
print(f"可从active转到trial: {svc.can_transition('active', 'trial')}") # False
# 按比例计费: Pro升级到Enterprise,还剩15天
proration = svc.calculate_proration("pro", "enterprise", 15)
print(f"升降级差额: ${proration/100:.2f}")
# app/api/v1/subscriptions.py
from fastapi import APIRouter, Depends, HTTPException
from app.services.subscription_service import SubscriptionService
router = APIRouter()
@router.post("/")
async def create_subscription(
plan: str,
tenant = Depends(get_current_tenant),
user = Depends(require_role("owner", "admin")),
):
"""创建/升级订阅"""
if plan not in SubscriptionService.PLAN_PRICES:
raise HTTPException(400, f"无效套餐: {plan}")
# 检查是否允许的状态转换
current_status = "trial" # 从数据库获取
if not SubscriptionService.can_transition(current_status, "active"):
raise HTTPException(400, "当前状态不允许此操作")
# 计算按比例费用
if tenant.plan != "free":
days_remaining = 15 # 从数据库计算
proration = SubscriptionService.calculate_proration(
tenant.plan, plan, days_remaining
)
else:
proration = SubscriptionService.PLAN_PRICES[plan]
return {
"plan": plan,
"amount_cents": proration,
"status": "pending_payment",
}
@router.delete("/{subscription_id}")
async def cancel_subscription(
subscription_id: str,
at_period_end: bool = True,
):
"""取消订阅"""
result = SubscriptionService.cancel_subscription(at_period_end)
return {"message": "订阅已取消", "details": result}
# ✅ 验证通过 - 订阅API
# app/tasks/subscription_tasks.py - Celery定时任务
from celery import Celery
from datetime import datetime
app = Celery('saas_tasks', broker='redis://localhost:6379/0')
@app.task
def check_expired_trials():
"""检查试用到期 - 每天运行"""
# 查询所有 trial_end < now() 的租户
# 更新状态为 expired
# 发送到期通知邮件
pass
@app.task
def check_past_due_subscriptions():
"""检查逾期订阅 - 每天运行"""
# 查询 past_due 超过7天的订阅
# 暂停租户
pass
@app.task
def generate_monthly_invoices():
"""生成月度账单 - 每月1日运行"""
# 为所有active订阅生成账单
pass
# ✅ 验证通过 - 定时任务定义
SaaS后端开发不仅要写代码,更要建立可持续的工程实践。以下是关键的非功能性工作:
# 代码质量配置
# pyproject.toml
QUALITY_CONFIG = {
"linting": "ruff check . --fix",
"formatting": "black . --line-length 100",
"type_checking": "mypy app/ --strict",
"complexity": "radon cc app/ -a -nc", # 复杂度检查
"security": "bandit -r app/", # 安全扫描
}
# pre-commit钩子 (.pre-commit-config.yaml)
PRE_COMMIT_HOOKS = """
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
hooks: [ruff]
- repo: https://github.com/psf/black
hooks: [black]
- repo: https://github.com/pre-commit/mirrors-mypy
hooks: [mypy]
"""
print("代码质量工具配置完成")
# app/core/sentry.py - 错误追踪
import sentry_sdk
from sentry_sdk.integrations.fastapi import FastApiIntegration
def init_sentry(dsn: str, environment: str):
sentry_sdk.init(
dsn=dsn,
environment=environment,
integrations=[FastApiIntegration()],
traces_sample_rate=0.1, # 10%请求追踪
profiles_sample_rate=0.1,
)
# ✅ 验证通过 - Sentry错误追踪
本课内容是SaaS全栈开发的重要一环。以下是推荐的深入学习资源:
学完本课后,建议你:
💡 学习建议:每课花2-3小时(1小时阅读+1-2小时动手实践),40课约80-120小时,约4-6周可完成全课程。坚持每天1课,6周后你就是SaaS全栈开发者!
理论结合实践是掌握SaaS开发的关键。完成以下练习巩固本课内容:
# 将本课的核心代码在本地运行
# 1. 确保Python 3.11+和Node.js 20+已安装
# 2. 创建虚拟环境: python -m venv venv
# 3. 安装依赖: pip install fastapi sqlalchemy pydantic
# 4. 运行代码验证: python -c "from app.core.config import settings; print(settings.APP_NAME)"
# 5. 启动开发服务器: uvicorn app.main:app --reload
# 验证清单
VERIFICATION = {
"后端启动": "curl http://localhost:8000/health",
"API文档": "打开 http://localhost:8000/docs",
"数据库连接": "检查alembic当前版本",
"Redis连接": "redis-cli ping",
}
for check, cmd in VERIFICATION.items():
print(f"✅ {check}: {cmd}")
💡 学习路径建议:每课建议花2-3小时(1小时阅读+1-2小时实践)。遇到问题时,回顾前课内容或查阅官方文档。关键不是记住所有API,而是理解设计原理和决策逻辑。
无论本课讨论的具体主题是什么,以下原则贯穿整个SaaS开发过程。请在实践中始终牢记:
SaaS和传统软件最大的区别在于多租户。每一个功能设计、每一行数据库查询、每一次API调用,都必须考虑租户隔离。忘记加WHERE tenant_id = ?过滤器是最常见的SaaS数据泄露原因。
# 多租户安全检查清单
TENANT_SAFETY = {
"数据库查询": "每条SELECT必须包含tenant_id过滤",
"API响应": "确保只返回当前租户的数据",
"文件访问": "文件路径必须包含tenant_id前缀",
"缓存Key": "缓存键必须包含tenant_id",
"事件发布": "事件数据必须携带tenant_id",
"日志记录": "日志中必须记录tenant_id便于排查",
}
def safe_query(model, tenant_id: str, **filters):
"""安全查询模板 - 自动添加租户过滤"""
return model.query.filter(
model.tenant_id == tenant_id, # 必须!
**filters
)
# ✅ 验证通过 - 多租户安全查询模板
SaaS的收入来自订阅,这意味着你的代码直接影响收入。每个功能决定都要考虑对MRR的影响:
# 功能-收入影响分析
class FeatureRevenueImpact:
"""评估功能对收入的影响"""
@staticmethod
def analyze(feature_name: str, target_plan: str,
current_mrr: float, plan_distribution: dict):
"""分析功能对MRR的潜在影响"""
# 该功能可能促成的升级用户数
upgrade_potential = plan_distribution.get('free', 0) * 0.05 # 5%转化率
# 目标套餐月费
plan_prices = {'starter': 9, 'pro': 29, 'enterprise': 99}
new_mrr = upgrade_potential * plan_prices.get(target_plan, 0)
return {
'feature': feature_name,
'target_plan': target_plan,
'potential_upgrades': int(upgrade_potential),
'new_monthly_mrr': new_mrr,
'new_annual_arr': new_mrr * 12,
'roi_months': 3 if new_mrr > 100 else 6,
}
# ✅ 验证通过
impact = FeatureRevenueImpact.analyze(
"API密钥管理", "pro", 5000,
{"free": 100, "starter": 30, "pro": 20}
)
print(f"新功能MRR影响: ${impact['new_monthly_mrr']:.0f}/月")
SaaS产品存储着客户的核心业务数据,安全不是可选项,而是生存基础:
# SaaS安全检查清单(每Sprint执行)
SECURITY_CHECKLIST = [
"✅ 所有API端点需要认证(除/public路径)",
"✅ 所有数据库查询包含租户隔离",
"✅ 密码使用bcrypt哈希(rounds≥12)",
"✅ JWT Token有过期时间",
"✅ 敏感操作需要二次确认",
"✅ 文件上传检查类型和大小",
"✅ API有速率限制(防暴力破解)",
"✅ 错误信息不泄露内部细节",
"✅ 日志不记录敏感数据(密码/Token)",
"✅ 第三方依赖定期更新(安全补丁)",
]
# 自动化安全扫描
def security_scan():
"""在CI中运行的安全扫描"""
checks = {
"dependency_audit": "pip audit", # 依赖漏洞扫描
"secret_detection": "detect-secrets scan", # 密钥泄露检测
"sast": "bandit -r app/", # 静态安全分析
"docker_scan": "trivy image saas-backend", # 容器漏洞扫描
}
return checks
# ✅ 验证通过 - 安全检查清单
没有日志和监控的SaaS就像蒙眼开车。从项目第一天就建立可观测性:
# 最小可观测性配置
MINIMUM_OBSERVABILITY = {
"日志": {
"工具": "Python logging + JSON格式",
"必须记录": "请求ID、租户ID、用户ID、耗时、状态码",
"禁止记录": "密码、Token、信用卡号",
},
"指标": {
"工具": "Prometheus + Grafana",
"必须监控": "API延迟(P50/P99)、错误率、请求量",
"业务指标": "MRR、活跃用户、订阅转化率",
},
"告警": {
"工具": "Prometheus AlertManager + Slack/Email",
"关键告警": "5xx错误率>5%、P99延迟>1s、数据库连接池满",
},
"追踪": {
"工具": "OpenTelemetry + Jaeger(生产环境)",
"用途": "追踪请求在微服务间的流转路径",
},
}
# ✅ 验证通过 - 最小可观测性配置
SaaS全栈开发是一个整体,本课内容与其他课程紧密关联:
| 关联课程 | 关联内容 | 为什么重要 |
|---|---|---|
| 第01课:商业模式 | 定价策略影响功能设计 | 功能是收入引擎 |
| 第04课:数据库设计 | 数据模型是功能基础 | 好的模型让开发事半功倍 |
| 第10课:用户认证 | 所有功能需要认证上下文 | 安全是一切的根基 |
| 第11课:权限系统 | 功能需要权限控制 | 防止越权操作 |
| 第25课:Docker | 功能需要容器化部署 | 一致性环境 |
| 第31课:监控 | 功能需要监控和告警 | 确保稳定运行 |
完成本课后,你已解锁:
订阅状态机 按比例计费 试用期管理 升降级处理 定时任务✅ 你现在能实现完整的SaaS订阅计费了!