str_pay / app.py
junaidkhattak252's picture
fix stripe
b71905f
Raw
History Blame Contribute Delete
2.05 kB
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))