Master Stripe payment processing integration for robust, PCI-compliant payment flows including checkout, subscriptions, webhooks, and refunds.
- Implementing payment processing in web/mobile applications
- Setting up subscription billing systems
- Handling one-time payments and recurring charges
- Processing refunds and disputes
- Managing customer payment methods
- Implementing SCA (Strong Customer Authentication) for European payments
- Building marketplace payment flows with Stripe Connect
Checkout Sessions
- Recommended for most integrations
- Supports all UI paths:
- Stripe-hosted checkout page
- Embedded checkout form
- Custom UI with Elements (Payment Element, Express Checkout Element) using
ui_mode='custom'
- Provides built-in checkout capabilities (line items, discounts, tax, shipping, address collection, saved payment methods, and checkout lifecycle events)
- Lower integration and maintenance burden than Payment Intents
Payment Intents (Bespoke control)
- You calculate the final amount with taxes, discounts, subscriptions, and currency conversion yourself.
- More complex implementation and long-term maintenance burden
- Requires Stripe.js for PCI compliance
- Compute the amount on the server from trusted records, and take price, amount, and currency only from server data.
- Collecting card data through Stripe Checkout, Elements, or the Stripe.js library reduces PCI scope but does not remove it. Keep raw card numbers off your servers and out of logs. The integrator still owns its own PCI self assessment duties.
Setup Intents (Save Payment Methods)
- Collect payment method without charging
- Used for subscriptions and future payments
- Requires customer confirmation
Critical Events:
payment_intent.succeeded: Payment completed
payment_intent.payment_failed: Payment failed
customer.subscription.updated: Subscription changed
customer.subscription.deleted: Subscription canceled
charge.refunded: Refund processed
invoice.payment_succeeded: Subscription payment successful
Verification and fulfillment:
- Verify every webhook event with the Stripe library signature check shown in the Secure Webhook Endpoint pattern in
references/details.md, using the raw request body and the Stripe signature header, and reject any request that fails the check.
- Keep the default timestamp tolerance so replayed events are rejected.
- Record each event id, process each event once, return a quick success response, and expect events to arrive in any order.
- Fetch the object again from the Stripe API and compare its state, amount, and metadata with your own records before granting access, fulfilling an order, or issuing a refund.
- For Checkout Sessions, fulfill from the checkout session completed event, and also handle the checkout session async payment succeeded and async payment failed events for delayed payment methods. For subscriptions, use the invoice paid and invoice payment failed events. For bespoke Payment Intents, use the payment intent succeeded event.
Components:
- Product: What you're selling
- Price: How much and how often
- Subscription: Customer's recurring payment
- Invoice: Generated for each billing cycle
- Create and manage customer records
- Store multiple payment methods
- Track customer metadata
- Manage billing details
import stripe
stripe.api_key = "sk_test_..."
# Create a checkout session
session = stripe.checkout.Session.create(
line_items=[{
'price_data': {
'currency': 'usd',
'product_data': {
'name': 'Premium Subscription',
},
'unit_amount': 2000, # $20.00
'recurring': {
'interval': 'month',
},
},
'quantity': 1,
}],
mode='subscription',
success_url='https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://yourdomain.com/cancel'
)
# Redirect user to session.url
Quick Start notes:
- Load the secret key from an environment variable or a secret manager at runtime, keep it on the server only, keep it out of source control and logs, and prefer restricted keys with the fewest permissions.
- Install the official Stripe Python library from the official package index, pin a tested version in a lockfile with hashes, and set an explicit Stripe API version.
- Compute amounts on the server from trusted catalog data, or use prices created in advance in Stripe. Take price, amount, and currency only from server records.
- A visit to the success page is not proof of payment, and the session id in that address is untrusted. Grant access or fulfill only from a verified webhook event, or after the server retrieves the session from Stripe and confirms it is paid and belongs to the current user.
- Send the user to the checkout session URL with a server redirect, and keep checkout session URLs out of logs and console output.
- Wrap Stripe calls in error handling as shown in the patterns in
references/details.md, show users only safe decline messages, and keep internal error details out of responses.
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
All examples here are for test mode only and use a test mode secret key. Before running any example, check that a test mode key is in use and stop if it is not. Default to test mode keys. Get explicit user confirmation before any charge, refund, dispute update, or subscription change against a live account, and pass an idempotency key on create and refund calls.
The raw test card numbers below are only for manual entry in Stripe hosted pages or Elements. Server code should use test payment method tokens, like the one in the confirm call below. Keep real card numbers off your servers and out of logs.
# Use test mode keys
stripe.api_key = "sk_test_..."
# Test card numbers
TEST_CARDS = {
'success': '4242424242424242',
'declined': '4000000000000002',
'3d_secure': '4000002500003155',
'insufficient_funds': '4000000000009995'
}
def test_payment_flow():
"""Test complete payment flow."""
# Create test customer
customer = stripe.Customer.create(
email="test@example.com"
)
# Create payment intent
intent = stripe.PaymentIntent.create(
amount=1000,
automatic_payment_methods={
'enabled': True
},
currency='usd',
customer=customer.id
)
# Confirm with test card
confirmed = stripe.PaymentIntent.confirm(
intent.id,
payment_method='pm_card_visa' # Test payment method
)
assert confirmed.status == 'succeeded'