by Lazy Sloth
Stripe Checkout Page in Python & FastAPI
import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import stripe
import uvicorn
from flask import Flask, render_template, request
# Constants
STRIPE_SECRET_KEY = os.environ['STRIPE_SECRET_KEY']
YOUR_DOMAIN = os.environ['YOUR_DOMAIN']
# Configure Stripe API key
stripe.api_key = STRIPE_SECRET_KEY
# FastAPI app initialization
app = FastAPI()
# CORS configuration
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
Frequently Asked Questions
How can this Custom Stripe Checkout Page template benefit my business?
The Custom Stripe Checkout Page template offers several benefits for businesses: - Seamless integration of Stripe payments into your Python application - Flexibility to handle various payment types, including one-time payments and subscriptions - Ability to track UTM parameters for marketing attribution - Customizable checkout experience to match your brand - Secure handling of payment information through Stripe's trusted infrastructure
Can I use this template for both physical and digital products?
Yes, the Custom Stripe Checkout Page template is versatile and can be used for both physical and digital products. Whether you're selling tangible goods, digital downloads, or subscription services, this template can be adapted to suit your needs. The key is to configure the appropriate Stripe product and price IDs in your backend to match your offerings.
How does this template help with marketing attribution?
The Custom Stripe Checkout Page template includes functionality to capture and pass UTM parameters (utm_source, utm_medium, utm_campaign, utm_term, utm_content) throughout the checkout process. This allows you to track the effectiveness of your marketing campaigns by attributing sales to specific channels or campaigns. The UTM parameters are captured in the frontend, sent to the backend, and then stored as metadata in the Stripe checkout session.
How can I modify the template to include custom fields in the checkout process?
To include custom fields in the checkout process using this template, you'll need to modify both the backend and frontend code. Here's an example of how you might add a "customer_name" field:
Backend (main.py): ```python class Data(BaseModel): # ... existing fields ... customer_name: str = Field(..., min_length=1)
@app.post('/create-checkout-session') def create_checkout_session(data: Data): # ... existing code ... session = stripe.checkout.Session.create( # ... existing parameters ... metadata={utm_params, 'customer_name': data.customer_name}, ) # ... rest of the function ... ```
Frontend (JavaScript):
javascript
async function initialize() {
// ... existing code ...
const customerName = document.getElementById('customer-name').value;
const response = await fetch("LAZY SERVER LINK/create-checkout-session", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
months,
price: 'PRICE_ID',
...utmParams,
customer_name: customerName
})
});
// ... rest of the function ...
}
Remember to add an input field for the customer name in your HTML as well.
How can I handle different subscription durations with this template?
To handle different subscription durations, you can modify the template to accept a duration parameter and use different Stripe price IDs based on the selected duration. Here's an example of how you might implement this:
Backend (main.py): ```python class Data(BaseModel): # ... existing fields ... duration: str = Field(..., regex='^(monthly|yearly)$')
@app.post('/create-checkout-session') def create_checkout_session(data: Data): price_id = 'PRICE_ID_MONTHLY' if data.duration == 'monthly' else 'PRICE_ID_YEARLY' # ... existing code ... session = stripe.checkout.Session.create( # ... existing parameters ... line_items=[{'price': price_id, 'quantity': 1}], ) # ... rest of the function ... ```
Frontend (JavaScript):
javascript
async function initialize() {
// ... existing code ...
const duration = document.querySelector('input[name="duration"]:checked').value;
const response = await fetch("LAZY SERVER LINK/create-checkout-session", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
months,
price: 'PRICE_ID', // This will be overridden in the backend
duration: duration,
...utmParams
})
});
// ... rest of the function ...
}
In this example, you would need to set up different price IDs in your Stripe account for monthly and yearly subscriptions, and replace 'PRICE_ID_MONTHLY' and 'PRICE_ID_YEARLY' with the actual IDs.
Created: | Last Updated:
Introduction to the Stripe Integration Template
Welcome to the guide on how to implement Stripe in your Python application using a Lazy template. This template is designed to help you integrate a custom Stripe payment page into your application with ease. It includes a backend service set up using FastAPI, which handles the creation and retrieval of Stripe checkout sessions, and a frontend script that you can embed into your Python application to initiate the payment process.
Getting Started
To begin using this template, click on "Start with this Template" on the Lazy platform. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy or paste any code manually.
Initial Setup
Before testing the application, you need to set up the required environment secrets:
- STRIPE_SECRET_KEY: This is your Stripe secret API key, which you can find in your Stripe dashboard under Developers > API keys.
- YOUR_DOMAIN: This is the domain where your application is hosted. It is used to construct the return URL after a successful payment.
To add these environment secrets, navigate to the Environment Secrets tab within the Lazy Builder and enter the values for each secret.
Test: Pressing the Test Button
Once you have set up the environment secrets, press the "Test" button to deploy the app. Lazy will handle the deployment, and you won't need to worry about installing libraries or setting up your environment.
Entering Input
If the template requires user input through the CLI, you will be prompted to provide it after pressing the "Test" button. Follow the instructions in the Lazy CLI to enter the necessary information.
Using the App
After deployment, Lazy will provide you with a dedicated server link to use the API. If the template uses FastAPI, you will also receive a link to the API documentation. Use these links to interact with your deployed backend service.
Integrating the App
To integrate the Stripe payment functionality into your frontend, you will need to add the provided frontend script to your application. Here's how:
- Locate the `` tag in your HTML file.
- Insert the provided frontend script just before the closing `` tag.
- Replace `"PUBLISHABLE STRIPE API KEY"` with your actual publishable API key from Stripe.
- Replace `"LAZY SERVER LINK"` with the endpoint URL of your published app that you received after deployment.
- Replace `"PRICE_ID"` with the actual price ID you want to use for the transaction.
Here is the script you need to add to your frontend:
`
` By following these steps, you will have successfully integrated a Stripe payment page into your Python application using the Lazy template. If you encounter any issues or need further assistance, refer to the Stripe API documentation or reach out to Lazy's customer support.
Here are 5 key business benefits for this template:
Template Benefits
-
Seamless Payment Integration: This template allows businesses to easily integrate Stripe's secure payment processing into their Python applications, enabling smooth and reliable transactions for customers.
-
Customizable Checkout Experience: By providing a custom checkout page, businesses can maintain brand consistency and tailor the payment process to their specific needs, potentially increasing conversion rates.
-
Subscription Management: The template supports subscription-based payments, allowing businesses to easily set up and manage recurring revenue streams.
-
UTM Tracking: Built-in UTM parameter handling enables businesses to track the effectiveness of their marketing campaigns and attribute sales to specific channels or initiatives.
-
Scalability and Performance: Utilizing FastAPI for the backend ensures high performance and scalability, allowing the payment system to handle increased traffic as the business grows.