File size: 1,766 Bytes
2d521fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Payment endpoints – Stripe Checkout integration.
"""

import os
import stripe
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from typing import Optional

from app.core.config import settings
from app.core.usage_tracker import tracker, Tier

router = APIRouter(prefix="/payments", tags=["payments"])

# Set Stripe API key (from environment)
stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET")

class CheckoutRequest(BaseModel):
    api_key: str
    success_url: str
    cancel_url: str


@router.post("/create-checkout-session")
async def create_checkout_session(req: CheckoutRequest):
    """Create a Stripe Checkout session for the Pro tier."""
    if not stripe.api_key:
        raise HTTPException(status_code=500, detail="Stripe not configured")

    # Verify the API key exists and is free tier
    tier = tracker.get_tier(req.api_key) if tracker else None
    if tier != Tier.FREE:
        raise HTTPException(status_code=400, detail="Only free tier keys can be upgraded")

    try:
        checkout_session = stripe.checkout.Session.create(
            payment_method_types=["card"],
            line_items=[
                {
                    "price": os.getenv("STRIPE_PRO_PRICE_ID"),  # e.g., "price_123"
                    "quantity": 1,
                }
            ],
            mode="subscription",
            success_url=req.success_url,
            cancel_url=req.cancel_url,
            metadata={"api_key": req.api_key},
            client_reference_id=req.api_key,
        )
        return {"sessionId": checkout_session.id, "url": checkout_session.url}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))