Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 77 ยท Projects

Taking Payments with Stripe-Style Checkout and Webhooks

Build a safe payment flow in Django: hosted checkout sessions, signed webhooks, order status, idempotent handlers and test mode, with a runnable gateway stand-in and real signature code.

Taking money looks like a big feature, but the part you write is small, because a payment provider such as Stripe (or Razorpay, PayPal, Paddle and others) does the hard parts: card entry, 3-D Secure, fraud checks and PCI compliance. Your Django app has three jobs: create an order, send the customer to the provider's hosted checkout page, and listen for the provider's confirmation to mark the order paid.

The most important lesson in this chapter is a rule: never mark an order as paid because the browser says so. The customer returns to your "thank you" page by following a URL, and anyone can type that URL. The only trustworthy signal is a message from the provider's server to yours, called a webhook, whose signature you verify.

This lesson shows the real signature algorithm and a complete, runnable order flow. The provider itself is replaced by a tiny stand-in, since a payment service cannot run inside a web page. The real Stripe SDK calls are shown read-only, and the flow is identical for other providers.

The flow

sequenceDiagram
    participant C as Customer
    participant D as Django
    participant S as Stripe
    C->>D: POST /checkout/ (cart)
    D->>D: Create Order(status=pending), price from DB
    D->>S: Create Checkout Session (items, order id, success URL)
    S-->>D: session id + URL
    D-->>C: Redirect to Stripe's page
    C->>S: Pays
    S-->>C: Redirect to /thanks/ (do not trust)
    S->>D: POST /webhooks/stripe/ (signed event)
    D->>D: Verify signature, mark Order paid once
    D-->>S: 200 OK

The redirect to the thank-you page and the webhook happen independently, and the webhook may arrive before or after the customer lands back on your site.

Step 1: create the order and a checkout session

Price and quantity come from your database, never from form fields the customer can edit. Store the order first (status pending), then ask the provider for a hosted payment page that remembers your order id:

Python
# views.py (read-only; needs: pip install stripe)
import stripe
from django.conf import settings
from django.shortcuts import redirect, get_object_or_404

stripe.api_key = settings.STRIPE_SECRET_KEY        # "sk_test_..." while developing


def start_checkout(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    order = Order.objects.create(user=request.user, product=product, amount_cents=product.price_cents)

    session = stripe.checkout.Session.create(
        mode="payment",
        line_items=[{
            "price_data": {
                "currency": "usd",
                "unit_amount": order.amount_cents,
                "product_data": {"name": product.name},
            },
            "quantity": 1,
        }],
        client_reference_id=str(order.pk),
        metadata={"order_id": str(order.pk)},
        success_url=request.build_absolute_uri("/thanks/") + "?order=" + str(order.pk),
        cancel_url=request.build_absolute_uri("/cart/"),
        idempotency_key=f"order-{order.pk}",       # a retry creates no second session
    )
    order.provider_session_id = session.id
    order.save(update_fields=["provider_session_id"])
    return redirect(session.url, permanent=False)

Note the idempotency_key. If your server sends the request, the network drops and your code retries, the key tells Stripe "this is the same operation," so you do not create two sessions. Many payment APIs support the same idea.

Test mode. Stripe gives you separate test keys (sk_test_...) and published test card numbers, so you can run the whole flow with no real money. Switch to live keys only in production settings, loaded from environment variables. Keep keys out of the repository; see Security in Django.

Step 2: how a webhook is signed

A webhook is a plain HTTP POST to a URL you publish, so anyone could send one that claims "order 42 is paid." Stripe prevents forgery with a shared secret (the signing secret, whsec_..., shown in its dashboard). It sends a header like Stripe-Signature: t=1700000000,v1=ab12..., where v1 is an HMAC-SHA256 of the timestamp, a dot, and the raw request body, keyed with your secret. You recompute it and compare.

Three details matter, and each is a classic bug:

  1. Use the raw bytes of the body (request.body). Parsing and re-serializing the JSON changes whitespace and breaks the signature.
  2. Compare with hmac.compare_digest, which takes constant time.
  3. Reject old timestamps (five minutes is Stripe's default tolerance), so a captured request cannot be replayed later.
Python Verify a webhook signature (HMAC-SHA256)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In production you do not write this yourself: stripe.Webhook.construct_event(request.body, sig_header, endpoint_secret) does the same check and raises SignatureVerificationError. Writing it once by hand shows that there is no magic, and the same recipe (HMAC over the raw body) is used by GitHub, Razorpay, Shopify and many others, with slightly different header formats.

Step 3: the webhook view, order status and idempotency

Providers deliver webhooks at least once. If your server was slow or returned an error, the same event arrives again, sometimes minutes later and out of order. Your handler must therefore be idempotent: processing the same event twice must have the same effect as processing it once. The standard technique is to record each event id in a table with a unique constraint inside the same transaction that changes the order.

Rules for a good webhook view:

  • @csrf_exempt (the provider has no CSRF token; the signature is the protection) and POST only.
  • Verify the signature first, then parse.
  • Look up the order by your id (client_reference_id/metadata), and check that the amount paid equals the amount you expected.
  • Change state only in allowed directions (pending to paid, never paid back to pending).
  • Return 2xx quickly for events you do not care about, so the provider stops retrying; return 4xx for a bad signature; let genuine failures return 5xx so it retries.
  • Do slow work (emails, fulfilment) outside the request, for example in a task queue (see Docker, Celery and CI).

The next example is a complete mini shop in one script. FakeGateway plays the provider: it creates sessions, and when the "customer pays" it POSTs a signed event to the webhook URL, exactly as a real provider would. Everything on the Django side (the models, the view, the verification and the idempotency table) is the code you would ship.

Python An order flow with signed, idempotent webhooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the five outcomes as the checklist for your own handler. The forgery got 400 and changed nothing. The real event moved the order to paid. The redelivery returned 200 but processed nothing, because inserting the same event_id violates the unique constraint. The wrong amount returned 422 and its transaction rolled back, so the event was not recorded and can be investigated, and the old replay was rejected by the timestamp check.

The thank-you page

After payment, the customer lands on your success_url. Show a friendly message, but read the order's status from your database:

  • If it is paid, show the receipt.
  • If it is still pending, show "We are confirming your payment" and refresh after a moment. The webhook is usually a second or two behind the redirect.

Never grant downloads, credits or access based on the ?order= value in that URL alone.

Other providers and regions

The shape is the same everywhere: server-side order, hosted checkout (or a client-side widget that returns a payment id your server verifies), signed callback, idempotent handler. Razorpay, widely used in India, creates an order on the server, opens its checkout in the browser, then returns a payment id and a signature that your server verifies with HMAC-SHA256 of order_id|payment_id, plus optional webhooks. Read your provider's documentation for the exact header and signing format, and use its SDK's verify helper in production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must you not mark an order paid on the thank-you (success_url) page?

    The success URL is just a link a customer's browser follows. A signed server-to-server webhook is the trustworthy confirmation.
  2. 2. Which value do you verify a webhook signature against?

    HMAC is computed over the exact bytes the provider sent. Re-serializing parsed JSON can change whitespace and break the match.
  3. 3. What makes a webhook handler idempotent?

    Providers deliver at least once. A unique event id (checked inside the same transaction as the order change) makes duplicates harmless.
  4. 4. Where should the amount to charge come from?

    Anything the browser sends can be edited. Read prices from your database and compare the paid amount in the webhook.

Summary

  • Create the order and price on the server, send the customer to the provider's hosted checkout, and keep your order id in client_reference_id or metadata.
  • Trust only a verified webhook: HMAC-SHA256 over the raw body, constant-time compare, timestamp tolerance.
  • Make handlers idempotent with a unique event table, check the paid amount, only allow forward status changes, and answer quickly.
  • Use test keys and test cards in development, load keys from the environment, and use an idempotency key for API calls that must not run twice.
  • The same pattern fits Stripe, Razorpay, PayPal and others; only headers and SDK calls differ.

Next: Project: Weather App.