I recently finished integrating Stripe into a legacy codebase with a FastAPI backend and a TypeScript frontend. I went in thinking it would be "just an API call". It turned out to be a lesson in system design, security, and how money actually moves between banks.
This blog covers how card payments works, how a payment gateway fits in, the difference between Stripe's Payment Intents and Checkout Sessions, hosted vs custom UI, webhooks, and a handful of things that will bite you if nobody warns you first.
How card payments actually work
Before touching any API, it helps to know who is involved when a customer pays by card:
- Cardholder: the customer.
- Merchant: the busines selling something.
- Payment gateway: the service that securely captures payment details from the customer and transmits them onward.
- Payment processor: the company that routes the transaction to the card networks and banks.
- Acquiring bank (acquirer): the merchant's bank, which receives the money on the merchant's behalf.
- Card network: Visa, Mastercard, RuPay, and so on. They carry messages between the acquirer and the issuer.
- Issuing bank (issuer): the customer's bank, which decides whether to approve the payment.
A single card payment has 4 stages:
- Authorization - The issuer checks that the card is valid, if there are sufficient funds, and that the transaction does not look fraudulent. If everything checks out, it places a hold on those funds and sends back an approval. No money has moved yet.
- Capture - The merchant confirms it wants the held funds.
- Clearing - The card network and banks reconcile the transaction details
- Settlement - The money is transferred from the issuer to the acquirer, and then paid out to the merchant, usually after a delay of a few days.
Stripe is technically a payment service provider (PSP). It bundles the gateway, processor connections, the merchant account, fraud detection, and payouts into one product.
What a payment gateway does
A payment gateway sits between an application and the bank. It is usually responsible for
- Collecting payment details securely.
- Tokenization: tokens or IDs are the only thing that are stored in the system, not raw card details.
- Encryption during transmission of card details.
- Authentication: Sometimes an extra verifciation step where the customer confirms the payment with their bank, for example via an OTP.
- Fraud detection: Stripe Radar, for example, scores each payment for risk.
- Returning the status of the payment.
You technically could talk to banks directly. In practice, almost nobody should. The advantages of a gateway:
- Reduced PCI DSS scope. PCI DSS is the security standard for anyone who handles card data. If card numbers are stored on your application's servers, you take on a heavy compliance burden. With a gateway's hosted fields or hosted page, the card data goes straight to the gateway, and your compliance obligations shrink considerably.
- Many payment methods, one integration. Cards, wallets, bank debits, UPI, and others can often be enabled without a separate integration for each.
- Authentication flows, retries, currency handling, refunds, disputes (chargebacks), and receipts are all provided.
- Dashboards, test mode, logs, event history, and reporting are included.
General Architecture of gateway integration
Most modern integrations look like this:
Browser (TypeScript) Your backend (FastAPI) Stripe
| | |
|-- 1. "I want to pay" ------->| |
| |-- 2. Create payment -->|
| |<-- 3. client_secret ---|
|<-- 4. client_secret ---------| |
| |
|-- 5. Card details go DIRECTLY to Stripe ------------->|
|<-- 6. Result (success / needs action / failure) ------|
| |
| |<-- 7. Webhook event ---|
| |-- 8. Mark order paid |
Some important ideas here are:
- The backend decides the price. The frontend never tells the server how much to charge. The server looks up the order and computes the amount itself. Otherwise anyone with browser dev tools can change the price to 1 rupee.
- Sensitive data bypasses your servers. Card details go from the browser straight to Stripe.
- Secrets stay on the server. The secret key never appears in frontend code. The frontend only gets a publishable key, which is designed to be public.
- The source of truth for "was this paid?" is the webhook, not the browser. More on this shortly.
Payment Intents vs Checkout Sessions
A PaymentIntent represents your intention to collect a specific amount from a customer, and it tracks that payment through its entire lifecycle. You create one on your server, hand its client_secret to the frontend, and the frontend uses it to confirm the payment.
A PaymentIntent moves through statuses such as:
• requires_payment_method: created, but no payment details attached yet.
• requires_confirmation: details attached, waiting to be confirmed.
• requires_action: the customer must do something, for example complete 3D Secure.
• processing: submitted, awaiting a result (common with bank debits).
• requires_capture: authorized, but you chose to capture later.
• succeeded: the payment went through.
• canceled: you or Stripe canceled it.
The PaymentIntent is the lower-level building block. It gives you full control, but you are responsible for the surrounding pieces: the checkout UI, cart and line items, tax logic, success and failure handling, and so on.
A Checkout Session is a higher-level object that represents an entire checkout experience. You describe what the customer is buying (line items, currency, success and cancel URLs), and Stripe provides the payment page, collects the details, handles authentication, and shows the result. Under the hood, a Checkout Session in payment mode creates and manages a PaymentIntent for you. It can also handle things like subscriptions, promotion codes, shipping address collection, and tax calculation, depending on how sessions are configured.
Which one to use depends on your usecase and business requirements. Generally, Checkout Sessions are used unless there's need for more granular control.
Hosted Page UI vs Custom UI
When defining a checkoutSession or PaymentIntent, you can choose from a bunch of ui_modes:
ui_mode="hosted_page"
The customer is redirected to a page on Stripe's domain, pays there, and is redirected back to your site.
Pros
• Fastest to build and the smallest security surface.
• Stripe maintains the page: new payment methods, localization, accessibility, and compliance updates arrive without you changing code.
• Well tested across devices.
Cons
• Limited visual customization (logo, colors, and some layout options).
• The customer leaves your site, which some brands do not want.
ui_mode="embedded_page
Displays the Checkout Session as an embedded container directly on your website without redirecting away
ui_mode="elements"
You render the payment form inside your own page using Stripe.js and Stripe Elements (such as the Payment Element). The form fields are iframes served by Stripe, so card data still never touches your servers, but they sit inside your page and design.
Pros
• Full control of layout and user experience.
• The customer never leaves your site.
Cons
• More frontend code to write and maintain.
• You must handle the states yourself: loading, validation errors, declined cards, authentication redirects.
Webhooks
After the customer pays, Stripe redirects them back to the success page as defined. Can you mark the order as paid after this? No. The browser redirect is not reliable.
The customer may close the tab right after paying, or their network may drop before the redirect completes, or the payment result (success or fail) may arrive minutes later, or a malicious user can simply visit a success URL without paying.
Webhooks fix this by flipping the direction of communication. Instead of the application asking Stripe for the status of a payment, Stripe sends a response to the application server when an action(payment) is triggered.
How they work?
- In the Stripe dashboard (or Stripe CLI for local development), you register an endpoint URL, for example
https://yourapp.com/stripe-webhook(orstripe listen --all-snapshot --forward-to localhost:8001/api/v1/payments/stripe-webhookusing Stripe CLI), and choose which event types to receive. - When an event is triggered, Stripe sends an HTTP
POSTrequest to that URL. The body is JSON describing an Event objectm with atype(likecheckout.session.completed) and the relevant data. - The application's backend server verifies if the request really came from Stripe (signature verification), processes the event, and returns a
200status code. - If the server does not respond with success, Stripe retries with backoff. In live mode, retries continue for up to three days.
Verifying the signature
Since the endpoint is a public URL, anyone could send fake requests to it. Stripe includes a Stripe-Signature header containing a timestamp and an HMAC-SHA256 signature computed with a webhook signing secret. Application's server recomputes the signature over the raw request body and compares.
Note: signature verification must use the exact raw bytes of the body. If a framework parses and re-serializes the JSON before verification, the signature will not match. In FastAPI, read the raw body with await request.body().
Events I found useful for one-time payments:
-
checkout.session.completed(if using Checkout) payment_intent.succeededpayment_intent.payment.failedcharge.refunded
The Code
The webhook endpoint in FastAPI:
stripe.api_key = settings.stripe_api_key
STRIPE_WEBHOOK_SECRET = settings.stripe_webhook_secret
@router.post("/stripe-webhook")
async def stripe_webhook(request: Request, db: Session = Depends(get_db), stripe_signature: str = Header(None)):
payload = await request.body()
try:
event = stripe.Webhook.construct_event(
payload=payload, sig_header=stripe_signature, secret=STRIPE_WEBHOOK_SECRET
)
except ValueError:
# Invalid payload
raise HTTPException(status_code=400, detail="Invalid payload")
except stripe.error.SignatureVerificationError:
# Invalid signature
raise HTTPException(status_code=400, detail="Invalid signature")
event_type = event["type"]
data_object = event["data"]["object"]
if event_type == "checkout.session.completed":
# Handle completed checkout session (e.g., fulfill order, update database)
print(f"Checkout session completed for session ID: {data_object['id']}")
elif event_type == "payment_intent.succeeded":
# Handle successful payment intent
print(
f"Payment intent succeeded: {data_object['id']} for amount"
f" {data_object['amount']}"
)
elif event_type == "payment_intent.payment_failed":
# Handle failed payment
print(f"Payment failed: {data_object['id']}")
else:
print(f"Unhandled event type: {event_type}")
print(event)
return JSONResponse({"status": "success"}, status_code=200)
Sample Checkout session implementation:
# Stripe demands integers in sub-units (cents), so define a function format_stripe_amount() to handle this.
stripe_amount = format_stripe_amount(charge_amount, currency)
session = stripe.checkout.Session.create(
mode="payment",
line_items=[{ # used only necessary data here. refer to official stripe documentation to see
"price_data": {
"currency": currency.lower(),
"product_data": {
"name": f"Wallet Topup - {amount} INR",
},
"unit_amount": stripe_amount,
},
"quantity": 1,
}],
success_url=f"{redirect_url}&session_id={{CHECKOUT_SESSION_ID}}",
cancel_url=f"{origin}/checkout/cancelled",
metadata={
"kind": "wallet_topup",
"user_id": actor.subject_id,
"amount": str(amount),
"credit_amount": str(amount),
"charge_amount": str(charge_amount),
"transaction_fee": str(fee),
"currency": currency,
},
)
except stripe.error.StripeError as e:
logger.error(f"Stripe wallet session creation failed: {e}")
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e)) from e
Other Things worth knowing
- Stripe provides separate test keys and test card numbers (such as 4242 4242 4242 4242) so you can simulate successes, declines, and authentication challenges without real money. Stripe also provides test cards for 3D Secure and various failure scenarios.
- Test webhooks locally with the Stripe CLI. Running
stripe listen --forward-to localhost:8000/stripe-webhook/forwards events to your local server and prints a temporary signing secret to use in development. You can also trigger sample events withstripe trigger. - Amounts are integers in the smallest currency unit. 499 rupees is 49900 paise. Never use floating-point numbers for money anywhere in your system.
- Idempotency keys protect against double charges. If a network timeout makes you retry a request, an idempotency key tells Stripe that this is the same operation.
- Publishable keys go in the frontend. Secret keys stay server-side in environment variables or a secrets manager and never get committed to Git. Restricted keys let you limit what a key can do. Webhook signing secrets are separate again, one per endpoint.
- Store Stripe's IDs. Save the PaymentIntent ID, Checkout Session ID, and customer ID against your own orders. When something goes wrong, those IDs are how you connect your database to the Stripe dashboard.
Top comments (0)