File size: 2,050 Bytes
5ef1a7b b71905f 5ef1a7b | 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 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import stripe
import os
from dotenv import load_dotenv
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
# Initialize Stripe
stripe.api_key = os.getenv("STRIPE_SECRET","").strip()
logger.info("Stripe API initialized")
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
logger.info("🚀 FastAPI application starting up...")
logger.info(f"Stripe API Key configured: {bool(stripe.api_key)}")
@app.get("/")
def home():
logger.info("Home endpoint hit")
return {"message": "Stripe FastAPI backend is running ✅", "status": "healthy"}
@app.get("/health")
def health():
logger.info("Health check endpoint hit")
return {"status": "healthy"}
@app.post("/create-payment-intent")
async def create_payment_intent(data: dict):
try:
logger.info(f"Creating payment intent with data: {data}")
amount = data.get("amount")
currency = data.get("currency", "usd")
if not amount:
raise HTTPException(status_code=400, detail="Amount is required")
intent = stripe.PaymentIntent.create(
amount=int(amount),
currency=currency,
automatic_payment_methods={"enabled": True},
)
logger.info(f"Payment intent created successfully: {intent.id}")
return {"client_secret": intent.client_secret}
except stripe.error.StripeError as e:
logger.error(f"Stripe error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e)) |