| """ |
| 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"]) |
|
|
| |
| 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") |
|
|
| |
| 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"), |
| "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)) |
|
|