by Lazy Sloth
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=["*"],
Frequently Asked Questions
What are the main business benefits of using this Stripe Subscription API template?
The Stripe Subscription API template offers several key business advantages: - Flexible pricing: It's compatible with any price point set up in Stripe, allowing for easy adjustment of subscription tiers. - UTM tracking: The template captures UTM parameters, enabling better tracking of marketing campaigns and their effectiveness in driving subscriptions. - Scalability: Built on FastAPI, the template can handle high volumes of subscription requests efficiently. - Easy integration: The template provides front-end integration instructions, making it simple to implement in various web applications.
How can this template help with subscription management for SaaS businesses?
For SaaS businesses, the Stripe Subscription API template streamlines subscription management by: - Automating the subscription creation process - Handling secure payment processing through Stripe - Providing a standardized way to create subscriptions across different products or tiers - Offering flexibility in subscription duration (through the 'months' parameter) - Enabling easy tracking of subscription sources through UTM parameters
Can this template be used for one-time purchases as well as subscriptions?
While the Stripe Subscription API template is primarily designed for recurring subscriptions, it can be adapted for one-time purchases. However, this would require modifications to the code. The current implementation creates a Stripe Subscription object, which is intended for recurring payments. For one-time purchases, you would need to implement a separate endpoint that creates a Stripe PaymentIntent or Charge instead of a Subscription.
How can I modify the template to include additional customer information in the subscription creation process?
To include additional customer information, you can modify the Data
class in the template. For example, to add a customer's name and email, you could update the class like this:
python
class Data(BaseModel):
months: int = Field(..., gt=0)
utm_source: str = ''
utm_medium: str = ''
utm_campaign: str = ''
utm_term: str = ''
utm_content: str = ''
price: str = Field(..., min_length=3)
customer_id: str = Field(..., min_length=3)
payment_method: str = Field(..., min_length=3)
customer_name: str = Field(..., min_length=1)
customer_email: str = Field(..., min_length=5)
Then, in the create_subscription
function, you can use this information when creating the subscription or updating the customer:
python
stripe.Customer.modify(
data.customer_id,
name=data.customer_name,
email=data.customer_email
)
How can I implement error handling for failed subscription creations in the front-end?
To handle errors in the front-end when using the Stripe Subscription API template, you can modify the create_subscription
function in the provided JavaScript. Here's an example of how you could implement error handling:
```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., display an error message to the user)
throw error;
}
} ```
This implementation checks if the response is successful, and if not, it throws an error with the details provided by the server. It also includes a try-catch block to handle any other errors that might occur during the process.
Created: | Last Updated:
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:
`
` By following these steps, you can seamlessly integrate the Stripe Subscription API into your front-end application and start creating subscriptions with Stripe.
Template Benefits
-
Streamlined Subscription Management: This template provides a ready-to-use solution for businesses to easily set up and manage subscription-based services, reducing development time and costs.
-
Flexible Pricing Strategy: The integration with Stripe's API allows businesses to implement various pricing models and quickly adjust them based on market demands or business needs.
-
Enhanced User Tracking: The inclusion of UTM parameters enables businesses to track the effectiveness of their marketing campaigns and understand which channels are driving subscriptions.
-
Scalable and Secure Payments: By leveraging Stripe's robust payment infrastructure, businesses can ensure secure transactions and easily scale their subscription services as they grow.
-
Cross-Platform Compatibility: The use of FastAPI for the backend and the provided front-end integration script makes this template versatile and easy to implement across different web platforms and frameworks.