Stripe Subscription API

 import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import stripe
import uvicorn

# Constants
STRIPE_SECRET_KEY = os.environ['STRIPE_SECRET_KEY']

# 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,
    allow_credentials=True,
    allow_methods=["*"],

About this template

This app integrates a custom Stripe subscription API. It includes a backend service set up using FastAPI and is compatible with any price point established through the Stripe API. The backend service creates a Stripe subscription and allows all CORS. It also logs sent requests and subscription statuses. The price ID, customer ID, and payment method are fetched during the request from the user. After adding the Stripe API key, the backend service can be activated by clicking the test button. The required environment secrets for this app are STRIPE_SECRET_KEY.

Introduction to the Stripe Subscription API Template

Welcome to the Stripe Subscription API Template! This template is designed to help you integrate a custom Stripe subscription API into your software applications with ease. The backend service is set up using FastAPI and is compatible with any price point established through the Stripe API. It handles the creation of Stripe subscriptions and allows all CORS, ensuring that you can easily connect it with your front-end applications. Additionally, it logs requests and subscription statuses for better monitoring.

Getting Started

To begin using this template, simply 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, paste, or delete any code manually.

Initial Setup

Before you can test and use the application, you'll need to set up an environment secret within the Lazy Builder:

  • Go to the Environment Secrets tab within the Lazy Builder.
  • Add a new secret with the key STRIPE_SECRET_KEY.
  • Enter your Stripe secret key as the value for this secret. You can find your Stripe secret key in your Stripe Dashboard under Developers > API keys.

Make sure to save the secret key securely, as it allows your application to communicate with Stripe's API.

Test: Pressing the Test Button

Once you have set up the environment secret, press the "Test" button on the Lazy platform. This will begin the deployment of your application and launch the Lazy CLI. If the application requires any user input, you will be prompted to provide it through the Lazy CLI interface.

Entering Input

After pressing the "Test" button, if the application requires user input, the Lazy CLI will prompt you to provide the necessary information. Follow the instructions in the CLI to enter the required details.

Using the App

After the application has been successfully deployed, Lazy will provide you with a dedicated server link. You can use this link to interact with the API. Additionally, since the code uses FastAPI, Lazy will also provide a link to the FastAPI documentation, which you can use to explore the available endpoints and their specifications.

Integrating the App

To integrate the Stripe Subscription API with your front-end application, you'll need to follow these steps:

  • Include the provided front-end integration script in your HTML page, just before the </body> tag.
  • Replace "PUBLISHABLE STRIPE API KEY" with your actual publishable API key from Stripe.
  • Replace "YOUR SERVER LINK" with the server link provided by Lazy after deployment.
  • Replace "PRICE_ID", "CUSTOMER_ID", and "PAYMENT_METHOD_ID" with the actual IDs you want to use for the transaction.

Here is the sample front-end integration script:


<script src="https://js.stripe.com/v3/"></script>
<script>
    const stripe = Stripe("PUBLISHABLE STRIPE API KEY");

    function getUTMParameters() {
        const params = new URLSearchParams(window.location.search);
        return {
            utm_source: params.get('utm_source') || '',
            utm_medium: params.get('utm_medium') || '',
            utm_campaign: params.get('utm_campaign') || '',
            utm_term: params.get('utm_term') || '',
            utm_content: params.get('utm_content') || ''
        };
    }

    async function create_subscription() {
        const months = 1;
        const utmParams = getUTMParameters();

        const response = await fetch("YOUR SERVER LINK/create-subscription", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                months,
                price: 'PRICE_ID',
                customer_id: 'CUSTOMER_ID',
                payment_method: 'PAYMENT_METHOD_ID',
            ...utmParams
            })
        });

        const { subscriptionId } = await response.json();
        return subscriptionId;
    }
</script>

By following these steps, you can seamlessly integrate the Stripe Subscription API into your front-end application and start creating subscriptions with Stripe.

Category
Last published
May 18, 2024

More templates like this

CSV Deduper

A webpage that dedupes a CSV based on the values in the first column and allows for downloading.

Python
Flask

Versatile Input Form

Develop a versatile input form for users.

Streamlit
Python

AI Specific Website Scraper

Provide a url and the information you need to extract . It will provide you the extracted information from that url

Selenium
Python
Home
/
Stripe Subscription API