Create Stripe Checkout Session with API

Test this app for free
32
import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import stripe
import uvicorn

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

# 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

What is the main purpose of this Create Stripe Checkout Session with API template?

The main purpose of this template is to provide a FastAPI-based server that creates and manages Stripe checkout sessions for processing payments. It offers endpoints for creating a checkout session and retrieving its status, making it easy to integrate Stripe payments into your application or service.

How can this template benefit e-commerce businesses?

This Create Stripe Checkout Session with API template can greatly benefit e-commerce businesses by: - Simplifying the integration of secure payment processing - Allowing for easy tracking of UTM parameters for marketing analysis - Providing a seamless checkout experience with Stripe's embedded UI - Enabling automatic tax calculation for different regions - Offering subscription-based payment options

Can this template be used for both one-time and recurring payments?

Yes, the Create Stripe Checkout Session with API template is versatile and can be used for both one-time and recurring payments. In the current configuration, it's set up for subscription-based payments (mode='subscription'), but you can easily modify it to support one-time payments by changing the mode to 'payment'.

How can I customize the checkout session creation to include additional product information?

You can customize the checkout session creation by modifying the stripe.checkout.Session.create() call in the create_checkout_session function. For example, to include multiple products or more detailed product information:

python session = stripe.checkout.Session.create( ui_mode='embedded', line_items=[ {'price': 'price_1234', 'quantity': 1}, {'price': 'price_5678', 'quantity': 2} ], mode='payment', metadata=utm_params, return_url=return_url, automatic_tax={'enabled': True}, )

This example includes two different products with their respective quantities.

How can I handle webhook events to update my database after a successful payment?

To handle webhook events, you can add a new endpoint to the Create Stripe Checkout Session with API template. Here's an example of how you might implement this:

```python @app.post('/webhook') async def webhook_received(request: Request): payload = await request.body() sig_header = request.headers.get('Stripe-Signature')

   try:
       event = stripe.Webhook.construct_event(
           payload, sig_header, webhook_secret
       )
   except ValueError as e:
       raise HTTPException(status_code=400, detail='Invalid payload')
   except stripe.error.SignatureVerificationError as e:
       raise HTTPException(status_code=400, detail='Invalid signature')

   if event['type'] == 'checkout.session.completed':
       session = event['data']['object']
       # Update your database here
       print(f"Payment was successful for session: {session['id']}")

   return {"status": "success"}

```

This code adds a /webhook endpoint that verifies and processes Stripe webhook events, allowing you to update your database or perform other actions when a payment is successful.

Created: | Last Updated:

<p>This application serves as an API server that incorporates functionalities. It includes an endpoint that allows you to create a Stripe checkout session, for payment processing. Additionally it provides another endpoint to retrieve the status of a checkout session. The application allows for origin resource sharing (CORS) and generates logs with information level details regarding sent requests.</p><p>‍</p>

Introduction to the Stripe Checkout Session API Template

Welcome to the Stripe Checkout Session API Template! This template has been specifically designed to assist you in setting up an API server. Its primary purpose is to enable the creation of Stripe checkout sessions for processing payments. Alongside this functionality it features endpoints that facilitate the retrieval of checkout session statuses and ensures CORS integration. Moreover logging capabilities at the information level have been incorporated into this template. Follow this guide to easily deploy and run this template on the Lazy platform.

Starting with this Template

To commence using this template simply click on the "Start with this Template" button found within the Lazy Builder interface. By doing all necessary code will be automatically populated in the Lazy Builder without requiring any copying, pasting or deletion.

Setup; Adding Environment Secrets

Before conducting any testing or utilizing the APIs features there are an environment secrets that need to be set up within the Lazy Builder. These secrets play a role in establishing communication, between your application and Stripe while defining parameters for your checkout sessions.

To set up the necessary environment secrets, for your Stripe integration follow these steps;

1. Access your Stripe dashboard and navigate to Developers > API keys to find your Stripe key.

2. Determine the domain of your frontend application as this will be the domain for your customers after they complete a payment.

3. Create a price ID for the product or service you are selling in your Stripe dashboard under Products.

4. Open the Environment Secrets tab in the Lazy Builder. Add each of the keys as secrets entering their corresponding values.

5. Save all changes made.

6. To test the API simply click on the "Test" button, within the Lazy Builder. This will deploy the app. Launch the Lazy CLI.

Using the App;

Once you've clicked on "Test" Lazy will provide you with a server link to access and utilize the API. Additionally since this template utilizes FastAPI you will receive a link to access API documentation that outlines how to interact with endpoints and understand request and response formats.

To set up a Stripe checkout session you need to send a request, to the /create checkout session endpoint with all the required information. Below is an example of how the request should look;

`POST /create-checkout-session
Content-Type: application/json

{
  "months": 6,
  "utm_source": "newsletter",
  "utm_medium": "email",
  "utm_campaign": "spring_sale",
  "utm_term": "shoes",
  "utm_content": "ad_content"
}`

Upon completion you will receive a response that looks like this;

{   "clientSecret": "cs_test_a1b2c3d4e5f6g7h8i9j0kExample" }

The clientSecret is crucial for redirecting users to the Stripe Checkout page on your website.

To integrate this functionality into your frontend application you need to establish a connection with the API. Utilize the provided server link by Lazy to make API requests, from your frontend code. When a user decides to make a purchase initiate the /create checkout session endpoint from your frontend. Then use the received clientSecret to redirect them to the Stripe Checkout page.

An example of how you can make an API call

To initiate the checkout process you'll need to add the following code snippet to the section of your frontend application. Make sure to replace "YOUR_SERVER_LINK" with the server link provided by Lazy;

```javascript

fetch('YOUR_SERVER_LINK/create checkout session' {

method; 'POST'

headers; {

'Content Type'; 'application/json'

}

body; JSON.stringify({

months; 6

utm_source; 'newsletter'

utm_medium; 'email'

utm_campaign; 'spring_sale'

utm_term; 'shoes

utm_content; 'ad_content'

})

})

.then(response \=> response.json())

.then(data \=> {

// Redirect to Stripe Checkout using the clientSecret

stripe.redirectToCheckout({ session_id; data.clientSecret });

})

.catch(error \=> {

console.error('Error;' error);

});

```

By following these steps you'll be able to integrate the Stripe Checkout Session API into your application using the Lazy platform.



Template Benefits

  1. Streamlined Payment Processing: This template provides a ready-to-use API for creating Stripe checkout sessions, enabling businesses to quickly implement secure and efficient payment processing without building the infrastructure from scratch.

  2. Enhanced Analytics and Marketing: The inclusion of UTM parameters in the checkout process allows businesses to track the effectiveness of their marketing campaigns and understand which channels are driving the most conversions.

  3. Improved User Experience: By utilizing Stripe's embedded UI mode, businesses can offer a seamless checkout experience directly within their application or website, reducing friction in the payment process.

  4. Flexible Subscription Management: The template is set up for subscription-based payments, making it ideal for businesses offering recurring services or products, with the ability to easily adjust pricing and subscription terms.

  5. Robust Error Handling and Logging: With comprehensive error handling and logging implemented, businesses can quickly identify and resolve issues, leading to improved system reliability and easier maintenance.

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

We found some blogs you might like...