by Lazy Sloth
Create Subscription with Stripe 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
# 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=["*"],
Frequently Asked Questions
What are the main business benefits of using this Stripe subscription API integration?
The Create Subscription with Stripe API template offers several business advantages: - Flexibility in pricing: It's compatible with any price point set up in Stripe, allowing for easy adjustment of subscription tiers. - UTM parameter tracking: The integration captures UTM parameters, enabling better tracking of marketing campaigns and their effectiveness in driving subscriptions. - Seamless integration: The template provides both backend and frontend code, making it easier to implement subscription functionality into existing systems.
How can this template help with subscription management for SaaS businesses?
For SaaS businesses, the Create Subscription with Stripe API template streamlines the subscription process by: - Automating the creation of subscriptions directly through the Stripe API. - Allowing for easy customization of subscription details like duration and pricing. - Providing a health check endpoint to ensure the subscription service is running smoothly. - Offering detailed logging for better tracking and debugging of subscription-related issues.
Can this template be used for one-time payments as well as subscriptions?
While the Create Subscription with Stripe API template is primarily designed for creating subscriptions, it can be adapted for one-time payments. This would involve modifying the backend to use Stripe's one-time payment API instead of the subscription API. However, as-is, the template is optimized for recurring subscription models, which are common in SaaS and other subscription-based businesses.
How can I modify the template to include additional customer information in the subscription creation process?
To include additional customer information when creating a subscription, you can modify the Data
class in the backend and update the frontend accordingly. Here's an example:
```python class Data(BaseModel): # ... existing fields ... customer_name: str = Field(..., min_length=1) customer_email: str = Field(..., min_length=5)
@app.post('/create-subscription') def create_subscription(data: Data): try: # ... existing code ... subscription = stripe.Subscription.create( customer=data.customer_id, default_payment_method=data.payment_method, items=[{"price": data.price}], metadata={ "customer_name": data.customer_name, "customer_email": data.customer_email } ) # ... rest of the function ... ```
Then update the frontend create_subscription
function to include these new fields in the request body.
How can I implement error handling for failed subscription creations in the frontend?
To handle errors in the frontend when using the Create Subscription with Stripe API template, you can modify the create_subscription
function to catch and handle errors. Here's an example:
```javascript async function create_subscription() { try { 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
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Subscription creation failed');
}
const { subscriptionId } = await response.json();
console.log('Subscription created successfully:', subscriptionId);
return subscriptionId;
} catch (error) {
console.error('Error creating subscription:', error.message);
// Handle the error (e.g., show an error message to the user)
}
} ```
This modification adds error handling to catch and log any issues during the subscription creation process, allowing for better debugging and user feedback in case of failures.
Created: | Last Updated:
Introduction to the Create Subscription with Stripe API Template
Welcome to the Create Subscription with Stripe API template! This template is designed to help you integrate a custom Stripe subscription API into your software applications with ease. It includes a backend service set up using FastAPI, which is compatible with any price point established through the Stripe API. The backend service is responsible for creating a Stripe subscription and is configured to allow all CORS. It also logs requests and subscription statuses. The template is perfect for builders who want to add subscription functionality to their applications without delving into the complexities of backend development.
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.
Initial Setup
Before testing the app, you'll need to set up an environment secret for the Stripe secret key:
- Go to the Environment Secrets tab within the Lazy Builder.
- Create a new secret with the key
STRIPE_SECRET_KEY
. - Enter your Stripe secret key as the value. You can find this key in your Stripe dashboard under Developers > API keys.
Test: Pressing the Test Button
Once you have set up the environment secret, press the "Test" button. This will begin the deployment of the app and launch the Lazy CLI. The CLI will handle the deployment process, and you won't need to install any libraries or set up your environment.
Using the App
After pressing the "Test" button, Lazy will provide you with a dedicated server link. This link is where you can interact with the API to create Stripe subscriptions. Additionally, Lazy will provide a link to the FastAPI documentation, which you can use to explore the API endpoints and their specifications.
Integrating the App
To integrate the backend service with your front-end application, follow these steps:
- Insert the provided front-end integration script into your HTML page.
- 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 pressing the "Test" button. - Replace
"PRICE_ID"
,"CUSTOMER_ID"
, and"PAYMENT_METHOD_ID"
with the actual IDs you want to use for the transaction. - Call the
create_subscription()
function to initiate the creation of a Stripe subscription.
Here is the sample front-end integration script with placeholders for your specific values:
`
` By following these steps, you can seamlessly integrate the Create Subscription with Stripe API template into your application and start creating subscriptions for your customers.
Template Benefits
-
Streamlined Subscription Management: This template provides a ready-to-use solution for businesses to quickly implement and manage subscription-based services using Stripe's robust payment infrastructure.
-
Flexible Pricing Options: The template allows for easy integration with any price point set up in Stripe, giving businesses the flexibility to offer various subscription tiers or custom pricing models.
-
Enhanced Marketing Analytics: By incorporating UTM parameters in the subscription creation process, businesses can track the effectiveness of their marketing campaigns and understand which channels are driving subscriptions.
-
Scalable Backend Architecture: Built with FastAPI, the backend service is designed for high performance and can easily scale to handle a growing number of subscription requests as the business expands.
-
Improved Customer Insights: The template's integration with Stripe's customer and payment method IDs allows businesses to gather valuable data on their subscribers, enabling more personalized services and targeted retention strategies.