Stripe API
NotesTo work with the Stripe API, install the Stripe package:
pip install stripeAdd it to the non_ver_reqs.txt file:
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pillow
captcha
pwdlib[argon2]
pyjwt
stripeAnd freeze the requirements:
pip freeze > requirements.txtAdd the new settings. As always, never put real values in your source code:
CONF_STRIPE_SECRET_KEY: str = "" # NEW
CONF_STRIPE_PRICE: str = "" # NEW
CONF_STRIPE_WEBHOOK_SECRET: str = "" # NEW
CONF_STRIPE_API_BASE: str = "https://api.stripe.com" # NEWAnd set them in .env, with the values from the previous section:
CONF_STRIPE_SECRET_KEY=sk_test_...
CONF_STRIPE_PRICE=price_...
CONF_STRIPE_WEBHOOK_SECRET=whsec_...CONF_STRIPE_API_BASE is where the Stripe API lives. You won’t normally change it, but it can point at stripe-mock, Stripe’s official mock server, to try the code without an account:
podman run -d --rm --name stripe-mock -p 12111:12111 docker.io/stripe/stripe-mock:latestCONF_STRIPE_SECRET_KEY=sk_test_123
CONF_STRIPE_API_BASE=http://localhost:12111stripe-mock checks every request against Stripe’s API specification, but returns made-up responses (payments are never actually “paid”).
The Stripe code goes in a new file, starting with a function that creates a Stripe client:
import uuid
import stripe
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.concurrency import run_in_threadpool
from sqlmodel import Session
from config.settings import settings
from db.db import get_session_db
from db.schemas.user_schemas import User
router = APIRouter()
def stripe_client() -> stripe.StripeClient:
return stripe.StripeClient(settings.CONF_STRIPE_SECRET_KEY,
base_addresses={"api": settings.CONF_STRIPE_API_BASE})StripeClient is the current way to use the Stripe library. (Older examples set stripe.api_key and call stripe.checkout.Session.create(), which still works.)