Skip to main content

Secure Online Store Payment Integration: Stripe Checkout, Webhooks and UK Rules

In this article

The secure way to take payments in an online store is to never let a card number touch your server. Use Stripe Checkout or Stripe Elements so the card goes straight from the shopper's browser to Stripe. Treat the webhook from Stripe as the only proof that an order is paid. And make every handler idempotent so a retried event cannot ship a parcel twice or refund an order twice.

Do that and the hard part of PCI DSS falls away. Strong customer authentication is handled for you. What is left is genuinely yours: the order state machine, the stock, the emails, and the UK rules no payment provider meets on your behalf.

This is how we wire payments into every Django shop we build.

Never touch card data: what PCI DSS scope reduction means

PCI DSS applies to any business that accepts cards. Its scope is every system that stores, processes or transmits cardholder data. The amount of work you have to do depends on how much of your estate is in scope. If your server receives a card number, even briefly before forwarding it, your logs, backups and hosting are all in scope.

Stripe Checkout (a hosted payment page) and Stripe Elements (card fields in iframes that Stripe serves inside your page) both keep card data out of your systems entirely. The browser talks to Stripe; your server receives a token or a session reference, never a PAN. That makes the shop eligible for the shortest self-assessment questionnaire, SAQ A. The practical burden comes down to this: serve the whole site over HTTPS, keep card numbers out of support tickets and admin forms, and never build your own card input. The guide to SSL certificates and HTTPS covers the certificate side, and the website security checklist covers the rest of the server.

How Stripe Checkout works in a Django shop

  1. The shopper clicks pay. Your view loads the basket, recalculates every price and the postage on the server, and creates a pending order.
  2. Your server creates a Checkout Session with the line items, currency, postage options, a success URL and a cancel URL, and your order reference in the metadata.
  3. The shopper is sent to Stripe's hosted page. Apple Pay and Google Pay appear automatically on devices that support them. If the bank requires 3-D Secure, Stripe runs it.
  4. Stripe sends the shopper back to your success URL. That page says "thanks, we are confirming your order". It does not mark anything as paid.
  5. Stripe posts a checkout.session.completed event to your webhook. That handler marks the order paid, takes the stock, and sends the confirmation email.

The session creation is a few lines:

session = stripe.checkout.Session.create(
    mode="payment",
    line_items=[
        {
            "price_data": {
                "currency": "gbp",
                "unit_amount": item.unit_price_pence,
                "product_data": {"name": item.product.name},
            },
            "quantity": item.quantity,
        }
        for item in basket.items.all()
    ],
    shipping_address_collection={"allowed_countries": ["GB", "IE"]},
    shipping_options=[{"shipping_rate": settings.STRIPE_RATE_TRACKED48}],
    success_url=f"https://example.com/order/{order.token}/",
    cancel_url="https://example.com/basket/",
    metadata={"order": str(order.pk)},
)
return redirect(session.url, permanent=False)

Prices go to Stripe in pence as integers, and every line is recalculated from your database. The order token in the success URL is a random string rather than the sequential order number, so nobody can guess their way into another shopper's confirmation page.

Webhooks: the only trustworthy "paid" signal

Shoppers close tabs, lose signal and pay from apps that never return them to your site. Mark orders paid on the success page and you will have paid orders you never fulfil. Stripe's webhook is delivered server to server, retried for days if your server does not answer with a 2xx, and signed so that you can prove it came from Stripe. The plain-English explanation of webhooks covers the general idea; the shop-specific handler looks like this:

@csrf_exempt
@require_POST
def stripe_webhook(request):
    signature = request.headers.get("Stripe-Signature", "")
    try:
        event = stripe.Webhook.construct_event(
            request.body, signature, settings.STRIPE_WEBHOOK_SECRET
        )
    except (ValueError, stripe.SignatureVerificationError):
        return HttpResponseBadRequest()

    _, created = ProcessedEvent.objects.get_or_create(stripe_event=event["id"])
    if not created:
        return HttpResponse(status=200)

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        if session["payment_status"] == "paid":
            confirm_order.delay(session["metadata"]["order"])
    return HttpResponse(status=200)

Three things in that handler matter more than they look. The signature is checked before anything else, with the raw request body, because any reformatting breaks the check. The event ID is recorded before the work is done, so a duplicate delivery is answered with a 200 and ignored. And the real work is handed to a background task, so Stripe gets its answer quickly even if your email provider is slow. Events can arrive out of order, so the task reads the current state of the order rather than assuming it.

Idempotency in both directions

Idempotent means that doing the same thing twice has the same result as doing it once. A payment system needs it on both sides of the Stripe API.

Inbound events

The ProcessedEvent table above handles exact duplicates, but you also need the order itself to refuse a second transition. The confirming task locks the order row with select_for_update() and checks it is still pending. Only then does it mark the order paid, decrement stock and queue the email, all inside one database transaction. A second task for the same order finds it already paid and stops.

Outbound calls

Stripe accepts an idempotency key on every create request. Use one on session creation and on refunds, built from your own order reference, so that a timeout and a retry cannot create two sessions or two refunds:

stripe.Refund.create(
    payment_intent=order.payment_intent,
    amount=refund_pence,
    idempotency_key=f"refund-{order.pk}-{order.refund_count}",
)

Our own deed poll service, UK Name Change, runs on exactly this pattern. A customer pays through Stripe, and webhooks with idempotent handlers confirm the order so nothing is missed or charged twice. The legally formatted deed poll is then generated automatically, ready for us to print and post. The same handlers sit under the Django online shops we build, and under subscription renewals, which the post on selling products and subscriptions together goes into.

Strong customer authentication and saved cards

UK and European banks can demand that the shopper authenticates a payment in their banking app (3-D Secure). With Checkout and Payment Intents, Stripe decides when the bank requires it, runs the challenge, and applies exemptions for low-risk transactions, so the shop needs no logic of its own.

Two cases do need thought. If you will charge a saved card later, for a pre-order balance or a renewal, the first payment must be set up for future use so the bank has authenticated it for off-session charges. And a renewal can still be challenged, in which case the right response is an email with a hosted payment link, not a silent failure. A holiday deposit with the balance taken weeks later is the same off-session case, which our guide to travel agency websites with online bookings goes into.

The UK rules Stripe does not meet for you

A payment provider takes the money securely. The law about how you sell is yours, and the checkout is where most of it bites.

  • Cancellation rights. Under the Consumer Contracts Regulations, a consumer buying at a distance can cancel for any reason within 14 days of receiving the goods. They must be refunded, including the basic delivery charge, within 14 days of the goods coming back. If you fail to tell them about the right, the cancellation period extends by up to a year. Personalised and perishable goods are among the exceptions, which matters for a shop like Stamp and Bake that makes custom cookie cutters to order through a quote-and-approve flow.
  • Pre-contract information and the pay button. Before the shopper commits you must show the main characteristics, the total price including taxes, delivery costs and how to cancel. The button that places the order must make the obligation to pay explicit, "Pay now" or "Place order and pay"; a button labelled "Continue" does not.
  • Confirmation on a durable medium. The order confirmation email is a legal requirement, not a nicety, and it should repeat the price, the items and the cancellation information.
  • VAT display. Prices shown to consumers must include VAT. The checkout total must be the price the shopper saw, and a VAT-registered shop should show its VAT number and the VAT amount on the receipt.
  • Who you are. Your business name, geographic address, email address, and company and VAT numbers where you have them, must be easy to find on the site.
  • Faulty goods. The Consumer Rights Act gives a short-term right to reject faulty goods for a full refund and longer rights to repair or replacement.

Fraud, refunds and disputes

Stripe Radar blocks the obvious fraud before it reaches you. A manual-review hold is worth adding on top. An order goes to a review queue when the billing and shipping countries differ, when it is the shopper's first order above a value you choose, or when several cards were tried in quick succession. Keep the tracking reference on every dispatched order, because proof of delivery is the evidence that wins a chargeback.

Refunds should be issued from your own admin, not by logging in to Stripe. That way the stock adjustment, the accounting entry and the customer email happen in the same action. The charge.refunded and charge.dispute.created events then come back through the same webhook and update the order so that the record on your side always matches Stripe's. If the checkout page itself is the thing losing you orders rather than the payment plumbing, the checkout flow optimisation checklist is the companion to this post.

Questions people ask

Do I need PCI compliance if I use Stripe?

Yes, but with Checkout or Elements the card data never reaches you, so the shop qualifies for the simplest self-assessment, SAQ A. The practical obligations are HTTPS everywhere, no card numbers in your systems, and an annual confirmation that nothing has changed.

Should I use Stripe Checkout or Stripe Elements?

Checkout is a hosted page maintained by Stripe that already handles wallets, authentication and address collection. Elements embeds the card fields in your own page for full control of the layout. For most shops Checkout is the right call; Elements earns its extra work when the checkout is one step of a larger flow.

Does a small shop really need a webhook?

Yes. Without it, an order is only marked paid when the shopper lands on your success page, and a share of shoppers never do. The handler above is about twenty lines.

Can I show prices without VAT?

Not to consumers. A trade-only site selling to businesses can show ex-VAT prices if that is clear, but a shop open to the public must show the VAT-inclusive price everywhere the price appears.

A checklist before launch

Before a shop goes live, check it has all of this:

  • Hosted Checkout or Elements, no card fields of our own.
  • Signature-verified webhooks with an event table and row locks.
  • Idempotency keys on every outbound create.
  • A review queue for odd orders.
  • The cancellation, pricing and confirmation rules built into the templates rather than bolted on.