Could Integrating Stripe with FastAPI Really Be This Simple?

Weaving FastAPI and Stripe for Effortless Payment Processing

Could Integrating Stripe with FastAPI Really Be This Simple?

Integrating third-party services like Stripe into a FastAPI application can really step up your game, especially when you need to handle payments. So let’s dive into how we can make this happen smoothly.

First things first, you need to get yourself a Stripe account. Just head over to the Stripe website and sign up. Once you’re in, go to your dashboard and find your API keys. These keys are like the secret sauce for making API requests to Stripe. You’ll have both test and live API keys; stick with the test keys while you’re in development mode to dodge any real transactions.

Alright, next up, we need some packages to get this integration rolling. You can snag them using pip:

pip install fastapi uvicorn python-dotenv stripe

These packages include FastAPI for your backend, Uvicorn for running the server, Python-dotenv for managing environment variables, and the Stripe library for interacting with the Stripe API.

Now, it’s smart to keep your API keys and other sensitive info in environment variables. Create a .env file in your project directory and add your Stripe API keys like this:

STRIPE_PUBLISHABLE_KEY=pk_test_PUBLIC_KEY_HERE
STRIPE_SECRET_KEY=pk_test_SECRET_KEY_HERE
YOUR_DOMAIN=http://localhost:8000

Then, load these environment variables in your FastAPI application:

from dotenv import load_dotenv
import os

load_dotenv()

STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
STRIPE_PUBLISHABLE_KEY = os.getenv('STRIPE_PUBLISHABLE_KEY')
YOUR_DOMAIN = os.getenv('YOUR_DOMAIN')

Next up, let’s initialize the Stripe API with your secret key:

import stripe

stripe.api_key = STRIPE_SECRET_KEY

Now, let’s set up your FastAPI application. Here’s a basic example to get you going:

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

For handling payments, we need to create a checkout session. Check this out:

from pydantic import BaseModel

class Item(BaseModel):
    price_id: str

@app.post("/create-checkout-session")
async def create_checkout_session(item: Item):
    try:
        checkout_session = stripe.checkout.Session.create(
            payment_method_types=["card"],
            line_items=[
                {
                    "price": item.price_id,
                    "quantity": 1,
                },
            ],
            mode="payment",
            success_url=YOUR_DOMAIN + "/success",
            cancel_url=YOUR_DOMAIN + "/cancel",
        )
        return {"url": checkout_session.url}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

This endpoint creates a Stripe checkout session and returns the URL to redirect the user to the Stripe checkout page.

Integrating this payment functionality into your frontend is pretty straightforward. You need a script that redirects the user to the Stripe checkout page. Here’s an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Page</title>
</head>
<body>
    <button id="checkout-button">Checkout</button>

    <script>
        const checkoutButton = document.getElementById('checkout-button');
        checkoutButton.addEventListener('click', async () => {
            const response = await fetch('/create-checkout-session', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    price_id: 'your-price-id-here',
                }),
            });

            const session = await response.json();
            window.location.href = session.url;
        });
    </script>
</body>
</html>

Just replace "your-price-id-here" with the actual price ID you want to use for the transaction.

We also need to handle the success and cancel routes that Stripe will redirect to after the payment process:

@app.get("/success")
async def success():
    return {"message": "Payment successful"}

@app.get("/cancel")
async def cancel():
    return {"message": "Payment cancelled"}

These routes will handle the redirects from Stripe after the user completes or cancels the payment.

Finally, run your FastAPI application using Uvicorn:

uvicorn main:app --reload

This command will kickstart your server, and you can test the payment flow by navigating to your application’s URL and clicking the checkout button.

So, when you’re integrating Stripe, you have two main options: a prebuilt checkout page or a custom payment flow. The prebuilt checkout page is a breeze to set up but doesn’t offer as much customization. It supports multiple payment methods like Apple Pay and Google Pay right out of the box and handles input validation and error handling for you. On the other hand, a custom payment flow gives you full control over the UI and functionality but needs more code and effort to implement.

Always remember to use environment variables for storing sensitive info like API keys. Make sure your .env file is not committed to your version control system to keep your keys safe. Use HTTPS for your application to secure the data transmitted between the client and server. And during development, stick with test API keys to avoid real transactions.

By following these steps, you can integrate Stripe into your FastAPI application efficiently, enabling robust payment processing capabilities. This integration not only enhances your application’s functionality but also offers a smooth payment experience for your users.