Spaces:
Running
Running
File size: 11,067 Bytes
db5f035 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Stripe billing endpoints for credit purchases.
Flow:
1. POST /billing/credits-checkout β creates Stripe Checkout session for credit packs
2. Stripe redirects user back after payment
3. POST /billing/webhook β Stripe webhook fulfils credit purchase
"""
import logging
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.config import settings
from src.core.auth import get_current_user
from src.database import get_db
from src.models.user import User
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/billing", tags=["billing"])
def _get_stripe():
"""Lazy-import stripe to avoid ImportError if not installed."""
try:
import stripe
if not settings.stripe_secret_key:
raise HTTPException(status_code=503, detail="Stripe is not configured")
stripe.api_key = settings.stripe_secret_key
return stripe
except ImportError:
raise HTTPException(status_code=503, detail="Stripe SDK not installed")
async def _get_user(
db: AsyncSession, current_user: dict, *, for_update: bool = False
) -> User:
firebase_uid = current_user.get("firebase_uid")
if firebase_uid:
stmt = select(User).where(User.firebase_uid == firebase_uid)
else:
stmt = select(User).where(User.id == UUID(current_user["id"]))
if for_update:
stmt = stmt.with_for_update()
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
# ---------------------------------------------------------------------------
class CheckoutResponse(BaseModel):
checkout_url: str
# ---------------------------------------------------------------------------
# Credit packs (tiered pricing)
# ---------------------------------------------------------------------------
# Default packs when STRIPE_CREDIT_PACKS is not configured
_DEFAULT_PACKS = [
{"credits": 500, "price_cents": 500, "label": "500 Credits", "savings": None},
{"credits": 2000, "price_cents": 1800, "label": "2,000 Credits", "savings": "10% off"},
{"credits": 5000, "price_cents": 4000, "label": "5,000 Credits", "savings": "20% off"},
{"credits": 10000, "price_cents": 7000, "label": "10,000 Credits", "savings": "30% off"},
]
def _parse_credit_packs() -> dict[int, str]:
"""Parse STRIPE_CREDIT_PACKS env var into {credits: price_id} mapping."""
if not settings.stripe_credit_packs:
return {}
packs = {}
for pair in settings.stripe_credit_packs.split(","):
pair = pair.strip()
if ":" not in pair:
continue
credits_str, price_id = pair.split(":", 1)
packs[int(credits_str)] = price_id
return packs
class CreditPack(BaseModel):
credits: int
price_cents: int
label: str
savings: str | None = None
class CreditPacksResponse(BaseModel):
packs: list[CreditPack]
@router.get("/credit-packs", response_model=CreditPacksResponse)
async def get_credit_packs() -> CreditPacksResponse:
"""Get available credit pack tiers for purchase."""
return CreditPacksResponse(packs=[CreditPack(**p) for p in _DEFAULT_PACKS])
# ---------------------------------------------------------------------------
# Credits checkout (one-time payment)
# ---------------------------------------------------------------------------
class CreditsCheckoutRequest(BaseModel):
amount: int # Number of credits to purchase (must match a pack tier)
@router.post("/credits-checkout", response_model=CheckoutResponse)
async def create_credits_checkout(
data: CreditsCheckoutRequest,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
) -> CheckoutResponse:
"""Create a Stripe Checkout session for a one-time credit purchase."""
stripe = _get_stripe()
# Validate amount matches a known pack
valid_amounts = {p["credits"] for p in _DEFAULT_PACKS}
if data.amount not in valid_amounts:
raise HTTPException(
status_code=400,
detail=f"Invalid credit amount. Choose from: {sorted(valid_amounts)}",
)
user = await _get_user(db, current_user, for_update=True)
# Reuse existing Stripe customer or create new one
customer_id = user.stripe_customer_id
if not customer_id:
customer = stripe.Customer.create(
email=user.email,
name=user.name,
metadata={"crewhub_user_id": str(user.id)},
)
customer_id = customer.id
user.stripe_customer_id = customer_id
await db.commit()
# Use Stripe Price ID if configured, otherwise use dynamic price_data
price_id_map = _parse_credit_packs()
price_id = price_id_map.get(data.amount)
if price_id:
line_items = [{"price": price_id, "quantity": 1}]
else:
# Fallback: dynamic pricing (1 credit = 1 cent)
pack = next(p for p in _DEFAULT_PACKS if p["credits"] == data.amount)
line_items = [{
"price_data": {
"currency": "usd",
"unit_amount": pack["price_cents"],
"product_data": {
"name": f"{data.amount} CrewHub Credits",
"description": f"One-time purchase of {pack['label']}",
},
},
"quantity": 1,
}]
session = stripe.checkout.Session.create(
customer=customer_id,
mode="payment",
line_items=line_items,
success_url=f"{settings.frontend_url}/dashboard/credits?purchase=success",
cancel_url=f"{settings.frontend_url}/dashboard/credits?purchase=cancelled",
metadata={
"crewhub_user_id": str(user.id),
"type": "credits",
"credits_amount": str(data.amount),
},
)
return CheckoutResponse(checkout_url=session.url)
# ---------------------------------------------------------------------------
# Billing status
# ---------------------------------------------------------------------------
class BillingStatus(BaseModel):
account_tier: str
stripe_customer_id: str | None = None
@router.get("/status", response_model=BillingStatus)
async def get_billing_status(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
) -> BillingStatus:
"""Get current user's billing status."""
user = await _get_user(db, current_user)
return BillingStatus(
account_tier=user.account_tier,
stripe_customer_id=user.stripe_customer_id,
)
# ---------------------------------------------------------------------------
# Stripe webhook
# ---------------------------------------------------------------------------
@router.post("/webhook")
async def stripe_webhook(
request: Request,
db: AsyncSession = Depends(get_db),
):
"""Handle Stripe webhook events.
Events handled:
- checkout.session.completed β fulfil credit purchase
- account.updated β sync Connect onboarding status
"""
stripe = _get_stripe()
payload = await request.body()
sig_header = request.headers.get("stripe-signature", "")
if not settings.stripe_webhook_secret:
raise HTTPException(status_code=503, detail="Webhook secret not configured")
try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.stripe_webhook_secret
)
except (ValueError, stripe.SignatureVerificationError):
raise HTTPException(status_code=400, detail="Invalid webhook signature")
event_type = event["type"]
data = event["data"]["object"]
if event_type == "checkout.session.completed":
await _handle_checkout_completed(db, data)
elif event_type == "account.updated":
await _handle_account_updated(db, data)
else:
logger.debug("Unhandled Stripe event: %s", event_type)
return {"status": "ok"}
async def _handle_checkout_completed(db: AsyncSession, session: dict) -> None:
"""Handle successful checkout β credit purchase fulfilment."""
metadata = session.get("metadata") or {}
customer_id = session.get("customer")
if not customer_id:
logger.warning("Checkout completed without customer ID")
return
result = await db.execute(
select(User).where(User.stripe_customer_id == customer_id)
)
user = result.scalar_one_or_none()
if not user:
# Try metadata fallback
user_id = metadata.get("crewhub_user_id")
if user_id:
result = await db.execute(select(User).where(User.id == UUID(user_id)))
user = result.scalar_one_or_none()
if not user:
logger.error("Could not find user for Stripe customer %s", customer_id)
return
if metadata.get("type") != "credits":
logger.warning("Unknown checkout type: %s", metadata.get("type"))
return
credits_amount = int(metadata.get("credits_amount", 0))
session_id = session.get("id", "")
if credits_amount <= 0:
return
# Idempotency: check if this checkout session was already processed
from src.models.transaction import Transaction
existing = await db.execute(
select(Transaction).where(
Transaction.description.contains(session_id)
)
)
if existing.scalar_one_or_none():
logger.info("Duplicate webhook for session %s, skipping", session_id)
return
from src.services.credit_ledger import CreditLedgerService
ledger = CreditLedgerService(db)
await ledger.purchase_credits(
owner_id=user.id,
amount=credits_amount,
description=f"Credit purchase of {credits_amount} (session: {session_id})",
)
logger.info("User %s purchased %d credits via Stripe (session: %s)", user.id, credits_amount, session_id)
async def _handle_account_updated(db: AsyncSession, account_data: dict) -> None:
"""Handle account.updated β sync Connect onboarding status."""
connect_account_id = account_data.get("id")
if not connect_account_id:
return
result = await db.execute(
select(User).where(User.stripe_connect_account_id == connect_account_id)
)
user = result.scalar_one_or_none()
if not user:
logger.debug("No user found for Connect account %s", connect_account_id)
return
payouts_enabled = account_data.get("payouts_enabled", False)
details_submitted = account_data.get("details_submitted", False)
user.stripe_connect_onboarded = details_submitted
user.stripe_connect_payouts_enabled = payouts_enabled
await db.commit()
logger.info(
"Connect account %s updated: onboarded=%s payouts_enabled=%s",
connect_account_id, details_submitted, payouts_enabled,
)
|