Spaces:
Build error
Build error
| """ | |
| Payment endpoints – Stripe Checkout integration. | |
| """ | |
| import os | |
| import stripe | |
| from fastapi import APIRouter, HTTPException | |
| from pydantic import BaseModel | |
| 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 | |
| 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=[ | |
| { | |
| # e.g., "price_123" | |
| "price": os.getenv("STRIPE_PRO_PRICE_ID"), | |
| "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)) | |