Skip to main content

Cloudsoft Zone Build, deploy and scale with practical guides to PHP, Node.js, React, DevOps and AI automation. Explore the guides

Cloudsoft Zone
Business TechnologyTutorial

Stripe Checkout in Node.js: verified webhooks and fulfilling each order once

Build a Stripe Checkout integration with stripe-node 23 and Express 5: create sessions on the server, verify webhook signatures against the raw body, and fulfil every order exactly once with a MySQL constraint.

Nilesh Kushvaha

Updated 12 min read

Cloudsoft Zone cover: Stripe Checkout in Node.js: verified webhooks and fulfilling each order once
Image: Cloudsoft Zone
In this article

A safe Stripe Checkout integration fulfils orders from a verified webhook, not the thank-you page: create the session on the server, verify the webhook signature against the raw request body, and let a primary key on the fulfilments table stop an order being fulfilled twice.

Taking card payments looks simple until the first customer pays and never receives what they bought. The usual cause is not the payment form: it is the code that runs after the payment. Many first integrations mark an order as paid when the browser lands on a "thank you" page, which fails as soon as a customer closes the tab, loses their connection or uses a payment method that settles later.

This tutorial builds a small, production-shaped Stripe Checkout integration in Node.js. You will create a Checkout Session on the server, redirect the customer to the Stripe-hosted payment page, verify webhook signatures correctly, and fulfil each order exactly once, even when Stripe delivers the same event twice or the webhook and the success page race each other.

The code targets stripe-node 23.0.0 (released 30 September 2026, pinned to API version 2026-09-30.endive, Node.js 20 or newer), Express 5 and MySQL through mysql2. Everything here was checked against Stripe's own documentation in October 2026.

What you will build

The flow has four parts, and each one has a single job:

  1. Create session: your server creates a Checkout Session with the price and quantity, then redirects the browser to the session URL. Prices stay on the server, so a customer cannot edit them.
  2. Pay on Stripe: the customer pays on the Stripe-hosted page. Stripe handles card entry, authentication challenges such as 3D Secure, and the payment methods you enable in the Dashboard.
  3. Webhook: Stripe sends a signed checkout.session.completed event to your server. This is the reliable signal that a payment happened.
  4. Landing page: Stripe redirects the customer to your success_url. The page also attempts fulfilment so the customer sees the result immediately, but it is never the only trigger.

Stripe's fulfilment guide is explicit on the last point: you "can't rely on triggering fulfilment only from your Checkout landing page, because your customers aren't guaranteed to visit that page." Webhooks are required.

Prerequisites and project setup

You need a Stripe account in test mode, the Stripe CLI, Node.js 20 or later (stripe-node 23 dropped Node 18), and a MySQL database you control. Before you start, check that Stripe supports businesses in your country; availability and payment methods differ by country, so confirm them on Stripe's site rather than assuming.

Create a product and a one-time price in the Stripe Dashboard and copy the price ID (it starts with price_). Then create the project:

Shell
mkdir shop && cd shop
npm init -y
npm pkg set type=module
npm install stripe@23 express@5 mysql2

Create a .env file that is ignored by Git. The values below are placeholders; never commit real keys. Node.js has had a built-in --env-file flag since 20.6.0 (no longer experimental from 22.21.0 and 24.10.0), so you do not need an extra package.

Shell
STRIPE_SECRET_KEY=sk_test_your_key_here
STRIPE_WEBHOOK_SECRET=whsec_from_stripe_listen
STRIPE_PRICE_ID=price_your_price_id
PUBLIC_URL=http://localhost:4242
DATABASE_URL=mysql://shop:your_password@127.0.0.1:3306/shop

Create the two tables. The primary key on fulfilments is what makes fulfilment idempotent, as you will see shortly.

SQL
CREATE TABLE fulfilments (
  checkout_session_id VARCHAR(255) NOT NULL PRIMARY KEY,
  fulfilled_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE order_items (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  checkout_session_id VARCHAR(255) NOT NULL,
  price_id VARCHAR(255) NULL,
  quantity INT UNSIGNED NOT NULL,
  amount_total BIGINT NOT NULL,          -- smallest currency unit, e.g. cents
  currency CHAR(3) NOT NULL,
  KEY idx_order_items_session (checkout_session_id)
);

Step 1: create the Stripe Checkout Session

A Checkout Session describes what the customer sees on the payment page: line items, amounts, currency and allowed payment methods. Stripe's quickstart notes that cards and other common payment methods are enabled by default, and that you can switch payment methods on or off in the Dashboard without code changes.

Three parameters matter for a one-time payment:

  • mode: 'payment' for a one-time charge. Use subscription for recurring billing or setup to save a payment method for later.
  • line_items with a price ID from your account. Keep prices on the server; Stripe's guide warns to keep "sensitive information about your product inventory, such as price and availability, on your server to prevent customer manipulation from the client."
  • success_url containing the literal placeholder {CHECKOUT_SESSION_ID}. Stripe replaces it with the real session ID when it redirects, which lets your landing page look the session up.

The redirect uses HTTP 303 so the browser follows it with a GET request after the form POST. The full server is shown in Step 3; the relevant route is:

JavaScript
// 3. Create a Checkout Session and redirect the customer to Stripe.
app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    mode: 'payment',
    line_items: [{ price: PRICE_ID, quantity: 1 }],
    success_url: `${DOMAIN}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${DOMAIN}/cart.html`,
  });
  res.redirect(303, session.url);
});

Express 5 forwards rejected promises from async handlers to the error handler automatically, so an API error here produces a 500 response instead of an unhandled rejection. Add your own error handler if you want a friendlier page.

The page that starts checkout is a plain form, which works without JavaScript:

HTML
<!-- public/index.html -->
<form action="/create-checkout-session" method="POST">
  <button type="submit">Buy the starter kit</button>
</form>

Step 2: verify webhook signatures with the raw body

Anyone who knows your webhook URL can send it a fake "payment succeeded" request. Stripe signs every event with the Stripe-Signature header, an HMAC-SHA256 signature over a timestamp and the exact request body, using your endpoint's whsec_ secret. The official library checks the signature and, by default, rejects events whose timestamp is more than five minutes old, which protects against replayed requests.

The most common integration bug is parsing the body before verifying it. Stripe's documentation says it "requires the raw body of the request to perform signature verification" and that any manipulation causes verification to fail. In Express, that means two rules:

  • Use express.raw({ type: 'application/json' }) on the webhook route so req.body is a Buffer.
  • Register the webhook route before any global express.json() middleware, or the JSON parser consumes the body first.

Respond with 400 when verification fails, and with a 2xx status quickly when it succeeds. Stripe treats redirects and non-2xx responses as failed deliveries and retries them: for up to three days with exponential backoff in live mode, and three times over a few hours in a sandbox.

Step 3: the complete server

Here is the whole server.js. It handles both checkout.session.completed and checkout.session.async_payment_succeeded. The second event matters for payment methods that are not instant, such as bank debits: the session completes first, and the money arrives later.

JavaScript
// server.js
import express from 'express';
import Stripe from 'stripe';
import { fulfillCheckout } from './fulfil.js';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
const DOMAIN = process.env.PUBLIC_URL ?? 'http://localhost:4242';
const PRICE_ID = process.env.STRIPE_PRICE_ID;

const app = express();

// 1. The webhook route comes first and receives the raw, unparsed body.
app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,                          // Buffer, exactly as Stripe sent it
      req.headers['stripe-signature'],
      endpointSecret,
    );
  } catch (err) {
    console.warn(`Webhook signature verification failed: ${err.message}`);
    return res.sendStatus(400);
  }

  if (
    event.type === 'checkout.session.completed' ||
    event.type === 'checkout.session.async_payment_succeeded'
  ) {
    try {
      await fulfillCheckout(event.data.object.id);
    } catch (err) {
      console.error('Fulfilment failed', err);
      return res.sendStatus(500); // Stripe will retry the delivery
    }
  }

  res.sendStatus(200);
});

// 2. Everything else can use the usual parsers.
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));

// 3. Create a Checkout Session and redirect the customer to Stripe.
app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    mode: 'payment',
    line_items: [{ price: PRICE_ID, quantity: 1 }],
    success_url: `${DOMAIN}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${DOMAIN}/cart.html`,
  });
  res.redirect(303, session.url);
});

// 4. Landing page: try fulfilment immediately, but never rely on it alone.
app.get('/success', async (req, res) => {
  const sessionId = String(req.query.session_id ?? '');
  if (!sessionId.startsWith('cs_')) {
    return res.status(400).send('Missing or invalid session ID.');
  }
  const result = await fulfillCheckout(sessionId);
  res.send(
    result.paid
      ? 'Thank you. Your order is confirmed.'
      : 'Your payment is still processing. We will email you when it completes.',
  );
});

app.listen(4242, () => console.log('Listening on http://localhost:4242'));

Returning 500 when fulfilment throws is deliberate. Stripe will retry the event, and because the fulfilment function is idempotent, a retry after a partial failure is safe. If your fulfilment does slow work, such as generating files or calling other APIs, put that work on a job queue and keep the webhook response fast. Stripe's best-practice section recommends processing events asynchronously for exactly this reason.

Step 4: fulfil each order exactly once

Stripe's fulfilment guide states that your fulfilment function "might be called multiple times, possibly concurrently, for the same Checkout Session." In this design it is called from two places (the webhook and the landing page), and webhook endpoints "might occasionally receive the same event more than once." The function therefore has to:

  1. Accept a Checkout Session ID.
  2. Retrieve the session from the API with line_items expanded, rather than trusting the event payload alone.
  3. Check payment_status: paid and no_payment_required can be fulfilled, unpaid cannot.
  4. Fulfil the line items and record that the session has been fulfilled, in a way that two concurrent calls cannot both win.
JavaScript
// fulfil.js
import Stripe from 'stripe';
import mysql from 'mysql2/promise';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const pool = mysql.createPool(process.env.DATABASE_URL);

export async function fulfillCheckout(sessionId) {
  const session = await stripe.checkout.sessions.retrieve(sessionId, {
    expand: ['line_items'],
  });

  // 'paid' or 'no_payment_required' can be fulfilled; 'unpaid' cannot (yet).
  if (session.payment_status === 'unpaid') {
    return { paid: false };
  }

  const conn = await pool.getConnection();
  try {
    await conn.beginTransaction();

    // The primary key makes this the single "claim" for the session.
    const [claim] = await conn.execute(
      'INSERT IGNORE INTO fulfilments (checkout_session_id) VALUES (?)',
      [session.id],
    );
    if (claim.affectedRows === 0) {
      await conn.commit();
      return { paid: true, alreadyFulfilled: true };
    }

    for (const item of session.line_items.data) {
      await conn.execute(
        `INSERT INTO order_items
           (checkout_session_id, price_id, quantity, amount_total, currency)
         VALUES (?, ?, ?, ?, ?)`,
        [session.id, item.price?.id ?? null, item.quantity, item.amount_total, item.currency],
      );
    }

    await conn.commit();
  } catch (err) {
    await conn.rollback();
    throw err;
  } finally {
    conn.release();
  }

  // Side effects outside the database (emails, licence keys) go here,
  // after the commit, ideally through a job queue.
  return { paid: true, alreadyFulfilled: false };
}

The key line is INSERT IGNORE on the primary key, inside a transaction. If two requests arrive at the same moment, InnoDB makes the second insert wait until the first transaction commits or rolls back. If the first commits, the second sees a duplicate key, affectedRows is 0, and it returns without doing anything. If the first rolls back because fulfilment failed, the claim disappears with it, and the next retry can try again. That is why the claim and the order rows are written in the same transaction.

If a Checkout Session can contain many line items, Stripe recommends using auto-pagination with the Checkout line items API to retrieve all of them.

Woman looking closely at a credit card while working on her laptop
Test cards let you rehearse success, authentication and decline paths before going live.

Step 5: test locally with the Stripe CLI

You do not need a public URL to test webhooks. The Stripe CLI forwards events from your test account to your local server:

Shell
stripe login
stripe listen --forward-to localhost:4242/webhook
# copy the whsec_... value it prints into STRIPE_WEBHOOK_SECRET

# in a second terminal
node --env-file=.env server.js

Open http://localhost:4242, click the button and pay with Stripe's test cards:

ScenarioTest card numberWhat to check
Payment succeeds4242 4242 4242 4242One row in fulfilments; the webhook and the success page both run, but only one fulfils.
3D Secure authentication required4000 0025 0000 3155The authentication challenge appears on the Stripe page; fulfilment happens after it is completed.
Payment declined4000 0000 0000 9995No fulfilment row; the customer stays on the payment page with an error.

Use any future expiry date and any CVC. Then test the failure paths on purpose: change the webhook secret to a wrong value and confirm you get 400 responses, and resend a completed event (the Resend button on the event in the Dashboard, or stripe events resend <event_id> --webhook-endpoint=<endpoint_id> for a registered endpoint) to confirm the duplicate is ignored.

Production checklist

ItemWhy it matters
Register a live webhook endpoint (HTTPS, TLS 1.2 or 1.3) and use its own whsec_ secretTest and live endpoints have different secrets; the CLI secret only works locally.
Subscribe only to the events you handleStripe advises against listening to all events because of unnecessary load.
Keep the server clock synchronised with NTPSignature verification checks the timestamp against a five-minute tolerance. Never set the tolerance to 0.
Exempt the webhook route from CSRF middlewareCSRF checks will reject Stripe's legitimate POST requests.
Track processed event IDs or session IDsStripe does not guarantee event order or single delivery.
Roll the signing secret periodicallyThe Dashboard lets you keep the old secret valid for up to 24 hours while you deploy the new one.
Store secret keys in a secrets manager, not in codeA leaked secret key can create charges and refunds on your account.

If you sell in several countries, also review tax collection. Stripe Tax can be added to Checkout with automatic_tax: { enabled: true }, but whether you must register and collect tax is a legal question for your accountant, not a code setting.

Summary

A reliable Checkout integration rests on three habits: keep prices on the server, verify every webhook against the raw body, and make fulfilment idempotent with a database constraint rather than an in-memory flag. The webhook is the source of truth; the success page is a convenience that makes the customer experience faster. With those in place, retries, duplicate events and delayed payment methods stop being incidents and become normal traffic.

Next steps: add checkout.session.async_payment_failed handling to email customers whose delayed payment fails, move side effects such as emails onto a job queue, and read Stripe's guide to refunds before your first support request arrives.

Frequently asked questions

  • Why does Stripe webhook signature verification fail in Express?

    Usually because the body was parsed before verification. Use express.raw({ type: 'application/json' }) on the webhook route and register it before any global express.json() middleware, so constructEvent receives the exact bytes Stripe signed.

  • Can I fulfil orders from the success page instead of a webhook?

    Not on its own. Stripe states that customers are not guaranteed to reach the landing page. Use the webhook as the reliable trigger and call the same idempotent function from the success page for a faster customer experience.

  • How long does Stripe retry a failed webhook?

    In live mode, Stripe attempts delivery for up to three days with exponential backoff. In a sandbox it retries three times over a few hours.

  • Which Node.js version does stripe-node 23 need?

    Node.js 20 or newer. Version 23.0.0, released on 30 September 2026, dropped support for Node.js 18 and pins API version 2026-09-30.endive.

Sources

  1. Receive Stripe events in your webhook endpoint — Stripe
  2. Fulfil orders (Stripe-hosted Checkout) — Stripe
  3. Build a Stripe-hosted checkout page — Stripe
  4. stripe-node CHANGELOG, 23.0.0 — Stripe, 2026-09-30
  5. Node.js command-line options: --env-file — OpenJS Foundation

Comments

No comments yet. Be the first to join the conversation.

Leave a comment

Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.

Never published. Used only to contact you about this comment.

Loading the security check…

Comments are moderated before publication.