Stripe Checkout Page in Python & FastAPI

Test this app for free
57
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,
Get full code

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:

This app integrates a custom Stripe checkout page in a Python application. It includes both a backend and a frontend. The backend service is set up using FastAPI and is compatible with any price point established through the Stripe API. The backend service creates a Stripe checkout session and retrieves the status of a checkout session. It also allows all CORS and logs sent requests and checkout session statuses. The price ID is fetched during the request from the user. After adding the Stripe API key and directing the backend service to the price ID, the backend service can be activated by clicking the test button. The frontend code can be integrated into a Python application to create a custom payment page. This method can be used to set up various types of payment pages, including one-time payments and subscriptions. The required environment secrets for this app are STRIPE_SECRET_KEY and YOUR_DOMAIN.

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:

  1. Locate the `` tag in your HTML file.
  2. Insert the provided frontend script just before the closing `` tag.
  3. Replace `"PUBLISHABLE STRIPE API KEY"` with your actual publishable API key from Stripe.
  4. Replace `"LAZY SERVER LINK"` with the endpoint URL of your published app that you received after deployment.
  5. 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

  1. 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.

  2. 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.

  3. Subscription Management: The template supports subscription-based payments, allowing businesses to easily set up and manage recurring revenue streams.

  4. 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.

  5. 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.


Technologies

Streamline Stripe Payments with Lazy AI Templates: Automate Billing, Invoices, Payments and More  Streamline Stripe Payments with Lazy AI Templates: Automate Billing, Invoices, Payments and More
FastAPI Templates and Webhooks FastAPI Templates and Webhooks

Similar templates

FastAPI endpoint for Text Classification using OpenAI GPT 4

This API will classify incoming text items into categories using the Open AI's GPT 4 model. If the model is unsure about the category of a text item, it will respond with an empty string. The categories are parameters that the API endpoint accepts. The GPT 4 model will classify the items on its own with a prompt like this: "Classify the following item {item} into one of these categories {categories}". There is no maximum number of categories a text item can belong to in the multiple categories classification. The API will use the llm_prompt ability to ask the LLM to classify the item and respond with the category. The API will take the LLM's response as is and will not handle situations where the model identifies multiple categories for a text item in the single category classification. If the model is unsure about the category of a text item in the multiple categories classification, it will respond with an empty string for that item. The API will use Python's concurrent.futures module to parallelize the classification of text items. The API will handle timeouts and exceptions by leaving the items unclassified. The API will parse the LLM's response for the multiple categories classification and match it to the list of categories provided in the API parameters. The API will convert the LLM's response and the categories to lowercase before matching them. The API will split the LLM's response on both ':' and ',' to remove the "Category" word from the response. The temperature of the GPT model is set to a minimal value to make the output more deterministic. The API will return all matching categories for a text item in the multiple categories classification. The API will strip any leading or trailing whitespace from the categories in the LLM's response before matching them to the list of categories provided in the API parameters. The API will accept lists as answers from the LLM. If the LLM responds with a string that's formatted like a list, the API will parse it and match it to the list of categories provided in the API parameters.

Icon 1 Icon 1
218

We found some blogs you might like...