@router.post("/create-checkout-session") async def createcheckoutsession(data:…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
@router.post("/create-checkout-session") async def create_checkout_session(data: CheckoutRequest): try: print(data) user_email = data.email user_name = data.name # Check for existing customer existing_customers = stripe.Customer.list(email=user_email) customer = existing_customers.data[0] if existing_customers.data else stripe.Customer.create( email=user_email, name=user_name ) metadata = { "credit_score": str(data.credit_point), "user_id": str(data.user_id), "amount": str(data.price), "customer_id": customer.id } if data.plan: metadata["plan"] = str(data.plan)
checkout_session = stripe.checkout.Session.create(
mode="payment",
locale="auto",
invoice_creation={
"enabled": True
},
customer_email=user_email,
payment_intent_data={
"description": f"Payment for {data.credit_point} Credit Points",
"metadata": metadata
},
line_items=[{
"quantity": 1,
"price_data": {
"currency": "usd",
"unit_amount": int(data.price * 100),
"product_data": {
"name": f"Payment for {data.credit_point} Credit Points"
}
}
}],
success_url="http://localhost:8000/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url="http://localhost:8000/cancel"
)
return {"checkout_url": checkout_session.url}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))#
@router.post("/webhook") async def stripe_webhook( request: Request, stripe_signature: str = Header(None) ): payload = await request.body()
try:
event = stripe.Webhook.construct_event(
payload=payload,
sig_header=stripe_signature,
secret=STRIPE_WEBHOOK_SECRET
)
except stripe.error.SignatureVerificationError:
raise HTTPException(status_code=400, detail="Invalid Stripe signature")
print("📦 Event type:", event["type"])
event_id = event["id"]
# === 1. Checkout Session Completed ===
if event["type"] == "checkout.session.completed":
session = event["data"]["object"]
try:
invoice_url = None
invoice_id = session.get("invoice")
if invoice_id:
invoice = stripe.Invoice.retrieve(invoice_id)
invoice_url = invoice.get("hosted_invoice_url")
print("📄 Invoice URL:", invoice_url)
payment_intent_id = session.get("payment_intent")
payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
metadata = payment_intent.get("metadata", {})
user_id = int(metadata.get("user_id", 0))
credit_score = int(metadata.get("credit_score", 0))
plan = metadata.get("plan")
amount = int(metadata.get("amount", 0))
currency = session.get("currency", "usd").lower()
customer_id = metadata.get("customer_id")
customer_email = session.get("customer_email", "N/A")
customer_name = session.get("customer_details", {}).get("name", "N/A")
checkout_session_id = session.get("id")
status = "pending"
created_at = updated_at = datetime.utcnow()
payment_doc = {
"user_id": user_id,
"plan": plan,
"credit_point": credit_score,
"amount": amount,
"transaction_id": payment_intent_id,
"customer_id": customer_id,
"checkout_session_id": checkout_session_id,
"paid_amount_currency": currency,
"created_at": created_at,
"updated_at": updated_at,
"invoice_url": invoice_url,
"email": customer_email,
"stripe_event": event_id
}
await payments_details_collection.update_one(
{"transaction_id": payment_intent_id},
{"$set": payment_doc},
upsert=True
)
print(f"📝 Stored pending checkout for user {user_id}, txn: {payment_intent_id}")
except Exception as e:
print(f"❌ Error in checkout.session.completed: {e}")
raise HTTPException(status_code=500, detail="Failed to process session")
# === 2. Charge Succeeded ===
elif event["type"] == "charge.succeeded":
print(f"📝 Charge succeeded for txn: {event_id}")
charge = event["data"]["object"]
try:
payment_intent_id = charge.get("payment_intent")
payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
metadata = payment_intent.get("metadata", {})
invoice_url = None
invoice_id = charge.get("invoice")
if invoice_id:
invoice = stripe.Invoice.retrieve(invoice_id)
invoice_url = invoice.get("hosted_invoice_url")
card = charge.get("payment_method_details", {}).get("card", {})
card_last4 = card.get("last4", "N/A")
card_brand = card.get("brand", "N/A")
card_exp_month = card.get("exp_month", "N/A")
card_exp_year = card.get("exp_year", "N/A")
user_id = int(metadata.get("user_id", 0))
credit_score = int(metadata.get("credit_score", 0))
plan = metadata.get("plan")
amount = int(charge.get("amount", 0))
currency = charge.get("currency", "usd").lower()
customer_id = charge.get("customer")
customer_email = metadata.get("customer_email", "N/A")
checkout_session_id = metadata.get("checkout_session_id", "N/A")
status = "payment_success"
created_at = updated_at = datetime.utcnow()
payment_doc = {
"user_id": user_id,
"plan": plan,
"credit_point": credit_score,
"amount": amount,
"transaction_id": payment_intent_id,
"customer_id": customer_id,
"checkout_session_id": checkout_session_id,
"payment_status": status,
"paid_amount_currency": currency,
"created_at": created_at,
"updated_at": updated_at,
"message": "Payment successful",
"invoice_url": invoice_url,
"email": customer_email,
"card_details": {
"last4": card_last4,
"brand": card_brand,
"exp_month": card_exp_month,
"exp_year": card_exp_year
},
"stripe_event": event_id
}
await payments_details_collection.update_one(
{"transaction_id": payment_intent_id},
{"$set": payment_doc},
upsert=True
)
print(f"✅ Payment success stored for {user_id}, amount: {amount/100:.2f} {currency}")
except Exception as e:
print(f"❌ Error in charge.succeeded: {e}")
raise HTTPException(status_code=500, detail="Failed to process charge")
# === 3. Payment Failed ===
elif event["type"] == "payment_intent.payment_failed":
intent = event["data"]["object"]
metadata = intent.get("metadata", {})
error_message = intent.get("last_payment_error", {}).get("message", "Unknown error")
try:
user_id = int(metadata.get("user_id", 0))
credit_score = int(metadata.get("credit_score", 0))
plan = metadata.get("plan")
amount = int(metadata.get("amount", 0))
transaction_id = intent["id"]
created_at = datetime.utcnow()
failed_doc = {
"user_id": user_id,
"plan": plan,
"credit_point": credit_score,
"amount": amount,
"transaction_id": transaction_id,
"payment_status": "failed",
"message": error_message,
"created_at": created_at,
"stripe_event": event_id
}
await payments_details_collection.insert_one(failed_doc)
print(f"❌ Payment failed: {transaction_id}, reason: {error_message}")
except Exception as e:
print(f"❌ Error in payment_intent.payment_failed: {e}")
raise HTTPException(status_code=500, detail="Failed to process failure")
return {"status": "ok"}
this is my code and here i want to separate the db logic and write that login in service.py and iport that functin here
Below is the refactored version of your code. I've separated the database logic into a new file called service.py (assuming it's in the same directory as your router file or in an appropriate module path). The service.py file contains functions that handle the MongoDB operations (e.g., upsert_payment_details for update/upsert operations and insert_failed_payment for the insert operation in the failure case). This keeps the router file focused on API logic, Stripe interactions, and building the data dictionaries, while delegating DB persistence to the service layer.
I've made the following changes:
update_one with upsert=True for "checkout.session.completed" and "charge.succeeded" events (consistent with your original code).insert_one for "payment_intent.payment_failed" (consistent with your original code).payments_details_collection is imported from a DB module (e.g., app.db). If not, adjust the import accordingly.service.pyfrom datetime import datetime # Import if not already available
from app.db import payments_details_collection # Adjust import based on your project structure (e.g., where your MongoDB collections are defined)
async def upsert_payment_details(payment_data: dict):
"""
Upserts payment details into the database based on transaction_id.
"""
transaction_id = payment_data.get("transaction_id")
if not transaction_id:
raise ValueError("Transaction ID is required for upsert operation")
# Add or update timestamps if not present
current_time = datetime.utcnow()
if "created_at" not in payment_data:
payment_data["created_at"] = current_time
payment_data["updated_at"] = current_time
result = await payments_details_collection.update_one(
{"transaction_id": transaction_id},
{"$set": payment_data},
upsert=True
)
return result
async def insert_failed_payment(failed_data: dict):
"""
Inserts a failed payment record into the database.
"""
# Add timestamp if not present
if "created_at" not in failed_data:
failed_data["created_at"] = datetime.utcnow()
result = await payments_details_collection.insert_one(failed_data)
return result
router.py or wherever your original code is)# Assuming your existing imports are here, e.g.:
# from fastapi import APIRouter, HTTPException, Request, Header
# import stripe
# from datetime import datetime
# from app.db import payments_details_collection # You can remove this if it's only used in service.py now
# from your_models import CheckoutRequest # Assuming you have this
# New imports for the service functions
from service import upsert_payment_details, insert_failed_payment # Adjust path if service.py is in a subdirectory
router = APIRouter() # Assuming this is already defined
@router.post("/create-checkout-session")
async def create_checkout_session(data: CheckoutRequest):
try:
print(data)
user_email = data.email
user_name = data.name
# Check for existing customer
existing_customers = stripe.Customer.list(email=user_email)
customer = existing_customers.data[0] if existing_customers.data else stripe.Customer.create(
email=user_email,
name=user_name
)
metadata = {
"credit_score": str(data.credit_point),
"user_id": str(data.user_id),
"amount": str(data.price),
"customer_id": customer.id
}
if data.plan:
metadata["plan"] = str(data.plan)
checkout_session = stripe.checkout.Session.create(
mode="payment",
locale="auto",
invoice_creation={
"enabled": True
},
customer_email=user_email,
payment_intent_data={
"description": f"Payment for {data.credit_point} Credit Points",
"metadata": metadata
},
line_items=[{
"quantity": 1,
"price_data": {
"currency": "usd",
"unit_amount": int(data.price * 100),
"product_data": {
"name": f"Payment for {data.credit_point} Credit Points"
}
}
}],
success_url="http://localhost:8000/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url="http://localhost:8000/cancel"
)
return {"checkout_url": checkout_session.url}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/webhook")
async def stripe_webhook(
request: Request,
stripe_signature: str = Header(None)
):
payload = await request.body()
try:
event = stripe.Webhook.construct_event(
payload=payload,
sig_header=stripe_signature,
secret=STRIPE_WEBHOOK_SECRET
)
except stripe.error.SignatureVerificationError:
raise HTTPException(status_code=400, detail="Invalid Stripe signature")
print("📦 Event type:", event["type"])
event_id = event["id"]
# === 1. Checkout Session Completed ===
if event["type"] == "checkout.session.completed":
session = event["data"]["object"]
try:
invoice_url = None
invoice_id = session.get("invoice")
if invoice_id:
invoice = stripe.Invoice.retrieve(invoice_id)
invoice_url = invoice.get("hosted_invoice_url")
print("📄 Invoice URL:", invoice_url)
payment_intent_id = session.get("payment_intent")
payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
metadata = payment_intent.get("metadata", {})
user_id = int(metadata.get("user_id", 0))
credit_score = int(metadata.get("credit_score", 0))
plan = metadata.get("plan")
amount = int(metadata.get("amount", 0))
currency = session.get("currency", "usd").lower()
customer_id = metadata.get("customer_id")
customer_email = session.get("customer_email", "N/A")
customer_name = session.get("customer_details", {}).get("name", "N/A")
checkout_session_id = session.get("id")
status = "pending"
created_at = updated_at = datetime.utcnow()
payment_doc = {
"user_id": user_id,
"plan": plan,
"credit_point": credit_score,
"amount": amount,
"transaction_id": payment_intent_id,
"customer_id": customer_id,
"checkout_session_id": checkout_session_id,
"paid_amount_currency": currency,
"created_at": created_at,
"updated_at": updated_at,
"invoice_url": invoice_url,
"email": customer_email,
"stripe_event": event_id
}
# Call service function instead of direct DB operation
await upsert_payment_details(payment_doc)
print(f"📝 Stored pending checkout for user {user_id}, txn: {payment_intent_id}")
except Exception as e:
print(f"❌ Error in checkout.session.completed: {e}")
raise HTTPException(status_code=500, detail="Failed to process session")
# === 2. Charge Succeeded ===
elif event["type"] == "charge.succeeded":
print(f"📝 Charge succeeded for txn: {event_id}")
charge = event["data"]["object"]
try:
payment_intent_id = charge.get("payment_intent")
payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
metadata = payment_intent.get("metadata", {})
invoice_url = None
invoice_id = charge.get("invoice")
if invoice_id:
invoice = stripe.Invoice.retrieve(invoice_id)
invoice_url = invoice.get("hosted_invoice_url")
card = charge.get("payment_method_details", {}).get("card", {})
card_last4 = card.get("last4", "N/A")
card_brand = card.get("brand", "N/A")
card_exp_month = card.get("exp_month", "N/A")
card_exp_year = card.get("exp_year", "N/A")
user_id = int(metadata.get("user_id", 0))
credit_score = int(metadata.get("credit_score", 0))
plan = metadata.get("plan")
amount = int(charge.get("amount", 0))
currency = charge.get("currency", "usd").lower()
customer_id = charge.get("customer")
customer_email = metadata.get("customer_email", "N/A")
checkout_session_id = metadata.get("checkout_session_id", "N/A")
status = "payment_success"
created_at = updated_at = datetime.utcnow()
payment_doc = {
"user_id": user_id,
"plan": plan,
"credit_point": credit_score,
"amount": amount,
"transaction_id": payment_intent_id,
"customer_id": customer_id,
"checkout_session_id": checkout_session_id,
"payment_status": status,
"paid_amount_currency": currency,
"created_at": created_at,
"updated_at": updated_at,
"message": "Payment successful",
"invoice_url": invoice_url,
"email": customer_email,
"card_details": {
"last4": card_last4,
"brand": card_brand,
"exp_month": card_exp_month,
"exp_year": card_exp_year
},
"stripe_event": event_id
}
# Call service function instead of direct DB operation
await upsert_payment_details(payment_doc)
print(f"✅ Payment success stored for {user_id}, amount: {amount/100:.2f} {currency}")
except Exception as e:
print(f"❌ Error in charge.succeeded: {e}")
raise HTTPException(status_code=500, detail="Failed to process charge")
# === 3. Payment Failed ===
elif event["type"] == "payment_intent.payment_failed":
intent = event["data"]["object"]
metadata = intent.get("metadata", {})
error_message = intent.get("last_payment_error", {}).get("message", "Unknown error")
try:
user_id = int(metadata.get("user_id", 0))
credit_score = int(metadata.get("credit_score", 0))
plan = metadata.get("plan")
amount = int(metadata.get("amount", 0))
transaction_id = intent["id"]
created_at = datetime.utcnow()
failed_doc = {
"user_id": user_id,
"plan": plan,
"credit_point": credit_score,
"amount": amount,
"transaction_id": transaction_id,
"payment_status": "failed",
"message": error_message,
"created_at": created_at,
"stripe_event": event_id
}
# Call service function instead of direct DB operation
await insert_failed_payment(failed_doc)
print(f"❌ Payment failed: {transaction_id}, reason: {error_message}")
except Exception as e:
print(f"❌ Error in payment_intent.payment_failed: {e}")
raise HTTPException(status_code=500, detail="Failed to process failure")
return {"status": "ok"}
upsert_payment_details: Handles update/upsert for pending and successful payments. It ensures timestamps are set/updated.insert_failed_payment: Handles insert for failed payments, adding a timestamp if missing.await payments_details_collection.update_one(...)) are replaced with calls to the service functions (e.g., await upsert_payment_details(payment_doc)). The data dictionaries are still built in the router for now, as they rely on Stripe event data.transaction_id). You can expand this as needed.service.py can access payments_details_collection (e.g., via from app.db import payments_details_collection). Remove any redundant imports from the router file.insert_failed_payment to use update_one with upsert and call it similarly.If your project structure is different (e.g., service.py in a subdirectory like app/services), adjust the import path accordingly (e.g., from app.services.service import upsert_payment_details). Test thoroughly, especially the webhook event flows, to ensure DB operations work as expected. If you need further adjustments, let me know!