Business tech · Intermediate · 28 min
How to Take Payments on Your Website with Stripe Checkout
By Padding · Updated 16 Nov 2026
Stripe Checkout · stripe-node 23.1 · API 2026-10-28.endive · Node.js 26 · Express 5.3
You will add a Buy button to a Node.js 26 and Express 5 site that sends customers to Stripe's hosted Checkout page, using stripe-node 23 and API version 2026-10-28.endive with sandbox keys, and you will fulfil the order from a signed webhook, never from the success page alone.
On this page
Stripe Checkout is a payment page that Stripe hosts. Your site sends the customer there with the details of what they are buying, Stripe collects the card (and wallets such as Apple Pay where available), handles 3-D Secure and tax fields, and sends the customer back. Your server never sees a card number, which keeps most of the legal and security burden with Stripe.
The flow has four moving parts, and the order matters:
- Your server creates a Checkout Session, a record on Stripe that describes the purchase, and redirects the customer to its URL.
- The customer pays on Stripe's page.
- Stripe redirects the browser back to your success URL.
- Stripe also sends a webhook to your server, a signed request saying the payment completed. This is what you act on. You fulfil the order, which means sending the product, granting access or marking it paid, from the webhook, and not from the success page.
You cannot rely on the success page by itself. A customer can pay and then close the tab before it loads, so the order is never fulfilled. Anyone can type the success URL into a browser without paying. Stripe's own guide says fulfilment cannot be triggered only from the landing page, and that webhooks are required for subscriptions and for payment methods that confirm later (https://docs.stripe.com/checkout/fulfillment).
Everything here uses your Stripe sandbox: an isolated test environment whose keys start with sk_test_ and where no real money moves. Do not use live keys until the final step.
Step 1 · Set up Stripe and the project
In the Stripe Dashboard, open your sandbox, then:
- Under the API keys page, copy the secret key. It starts with
sk_test_. This key can do anything in the sandbox, so treat it as a password. Never put it in your code, in Git or on a command line. Stripe's key guidance, https://docs.stripe.com/keys-best-practices, says the same. - In the product catalogue, create a product, for example "Sticker pack", with a one-time price, for example 9.00 USD. Copy the price's ID, which starts with
price_.
Create the project and install the packages. stripe is Stripe's official Node library, version 23.1.0 when this was written. It is pinned to API version 2026-10-28.endive, so the API behaves as the code expects even after Stripe ships newer versions:
mkdir -p ~/checkout-demo
cd ~/checkout-demo
npm init -y > /dev/null
npm pkg set type=module
npm install express@^5.3.0 stripe@^23.1.0Put the settings in a file that only you can read, which umask 077 makes private from the start. Edit the three values with your own. The webhook secret comes in a later step, so leave it for now:
(umask 077; cat > .env <<'ENV'
STRIPE_SECRET_KEY=sk_test_replace_me
STRIPE_PRICE_ID=price_replace_me
STRIPE_WEBHOOK_SECRET=whsec_set_later
BASE_URL=http://localhost:3000
ENV
)
ls -l .envThe listing shows -rw-------. Open .env in your editor and paste the real key and price ID. If the project is in Git, add .env to .gitignore first: see keep secrets out of Git.
Step 2 · Create the Checkout Session
Write the server. This first version has the shop page and the route that creates the session. Each part is explained below the code:
// server.js
import express from 'express';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const BASE_URL = process.env.BASE_URL;
const app = express();
app.get('/', (req, res) => {
res.type('html').send(`
<h1>Sticker pack</h1>
<form action="/create-checkout-session" method="POST">
<button type="submit">Buy for $9.00</button>
</form>`);
});
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items: [{ price: process.env.STRIPE_PRICE_ID, quantity: 1 }],
client_reference_id: 'order-1001', // your own order id
success_url: `${BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${BASE_URL}/cancel`,
});
res.redirect(303, session.url);
});
app.get('/success', (req, res) => {
res.type('html').send('<h1>Thank you</h1><p>We are confirming your payment.</p>');
});
app.get('/cancel', (req, res) => {
res.type('html').send('<h1>Payment cancelled</h1><p>You have not been charged.</p>');
});
app.listen(3000, '127.0.0.1', () => console.log('http://127.0.0.1:3000'));mode: 'payment'is a one-time payment. The other modes aresubscriptionandsetup(save a card for later).line_itemsnames the price you made in the Dashboard, and the quantity. The price comes from your server and your catalogue, never from the browser, so a customer cannot edit it. If you put the amount in a form field instead, anyone could change it to one cent.client_reference_idis your own reference. Create the order in your database before you call Stripe, and put its ID here. The webhook hands it back, so you know which order was paid.{CHECKOUT_SESSION_ID}is a marker that Stripe replaces with the real session ID when it redirects the customer to your success URL.res.redirect(303, session.url)sends the browser to Stripe's hosted page. 303 is the correct code after aPOST.- Express 5 passes errors from
asyncroute handlers to its error handler by itself, so notry/catchis needed to avoid a hung request. A real app should still show a friendly error page.
Start it with the variables loaded:
node --env-file=.env server.jsOpen http://127.0.0.1:3000 in a browser and press the button. You land on a Stripe-hosted page that shows your product and price. Pay with the test card 4242 4242 4242 4242, any future expiry date, any three digits for the security code and any name or postcode (https://docs.stripe.com/testing). You are redirected to /success?session_id=cs_test_....
At this point, do not ship anything. The payment happened, but your server has not been told, and the success page proves nothing. The next two steps do it properly.
Step 3 · Receive the webhook
Stripe notifies your server with a POST to a URL you register. The request is signed, and you must verify the signature on the raw body before you believe it, as covered in receive and verify webhooks in Node.js. Stripe's library does it for you with constructEvent. Add this above the express.urlencoded or any other body parser, because the signature covers the exact bytes Stripe sent and a parsed body no longer matches:
// add near the top of server.js, before other body parsers
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
req.get('Stripe-Signature'),
endpointSecret,
);
} catch {
return res.status(400).send('invalid signature');
}
if (
event.type === 'checkout.session.completed' ||
event.type === 'checkout.session.async_payment_succeeded'
) {
await fulfillCheckout(event.data.object.id);
}
res.sendStatus(200);
});Two event types lead to fulfilment. checkout.session.completed fires when the customer finishes Checkout. For payment methods that confirm later, such as some bank debits, that event can arrive before the money does, and checkout.session.async_payment_succeeded fires when it finally succeeds. The function below checks the payment status, so handling both is safe. Subscribe to checkout.session.async_payment_failed as well if you accept delayed methods, so you can tell the customer.
Now the function that does the work. It must be safe to run more than once for the same session, because the webhook can be delivered several times, and the success page may call it too:
// fulfilment, in server.js
const fulfilled = new Set(); // stand-in: use a database table with a unique session_id
async function fulfillCheckout(sessionId) {
const session = await stripe.checkout.sessions.retrieve(sessionId, {
expand: ['line_items'],
});
if (session.payment_status === 'unpaid') return; // not paid (yet)
if (fulfilled.has(session.id)) return; // already done
fulfilled.add(session.id);
// Do the real work here, using session.client_reference_id to find your order:
// mark it paid, send the download link, grant access, update stock.
console.log(`fulfil ${session.client_reference_id}: ${session.amount_total} ${session.currency}`);
}The function does what Stripe's guide lists: it takes the session ID, retrieves the session from the API with line_items expanded, checks payment_status, and records that it has fulfilled it. Fetching the session from the API means you act on what Stripe holds, and not on what arrived in the request. In production the in-memory Set is a database table with a unique constraint on the session ID, and you insert in the same database transaction as the work (or claim the row before doing the work and undo it on failure), so two requests at the same moment cannot both fulfil it. Compare session.amount_total with what you expected for that order as a last safety check.
Make the success page use the same function, so the customer sees the result at once, and a visit with a made-up ID does nothing:
app.get('/success', async (req, res) => {
const sessionId = String(req.query.session_id ?? '');
if (!sessionId.startsWith('cs_')) return res.status(400).send('Missing session');
let session;
try {
session = await stripe.checkout.sessions.retrieve(sessionId);
} catch {
return res.status(400).send('Unknown session');
}
if (session.payment_status === 'unpaid') {
return res.type('html').send('<h1>Payment not confirmed</h1>');
}
await fulfillCheckout(session.id);
res.type('html').send('<h1>Thank you</h1><p>Your order is confirmed.</p>');
});A forged session ID makes the API call fail, and the page answers 400 without showing any error details. A real one for an unpaid session is shown as not confirmed. The page never decides on its own that a payment happened. It asks Stripe.
Step 4 · Test the webhook on your computer
Stripe cannot reach localhost, so the Stripe CLI forwards events to it. Install the CLI from https://docs.stripe.com/stripe-cli, log in with stripe login, and start the forwarding in a second terminal:
stripe listen --forward-to localhost:3000/webhooks/stripeIt prints Your webhook signing secret is whsec_.... Copy that value into STRIPE_WEBHOOK_SECRET in .env, and restart the server so it reads it. The secret from the CLI does not change between restarts of stripe listen.
Run the purchase again with the test card. The server log shows something like fulfil order-1001: 900 usd, and stripe listen shows checkout.session.completed with a 200 response. If you only want to test your handler, stripe trigger checkout.session.completed sends a sample event.
Test the failure cases too. Use the declined test card 4000 0000 0000 0002 and confirm nothing is fulfilled. Resend an event, from the Dashboard or with stripe events resend <event_id>, and confirm the second delivery does not fulfil the order twice. Post to /webhooks/stripe with curl and no signature, and confirm you get 400.
Step 5 · Go live
When the sandbox flow works, switch to real payments:
- Complete your Stripe account activation, which asks for business and bank details.
- Create a live key. Stripe recommends a restricted key (
rk_live_...) with only the permissions your server needs, which here is creating and reading Checkout Sessions, over an unrestricted secret key. Put it in your production environment's secret store or a private file. Do not copy.envfrom your computer. - In the Dashboard, under Workbench's Webhooks tab, add an endpoint for your public HTTPS address, such as
https://example.com/webhooks/stripe, and subscribe it tocheckout.session.completed,checkout.session.async_payment_succeededandcheckout.session.async_payment_failed. In the current Dashboard this is the "Create an event destination" button, which may offer a choice between Snapshot and Thin events. Choose Snapshot (the full event objects that your code reads here), becausecheckout.session.completedis a snapshot event, and keep the API version the destination suggests, which should match what your library sends. The labels may differ slightly from what you see. Copy that endpoint's own signing secret into your production environment. It is different from the one the CLI gave you. - Serve the site over HTTPS, as in free HTTPS with Let's Encrypt and Nginx, and put the Node app behind a proxy as in Nginx as a reverse proxy for a Node app. Set
BASE_URLto your real address. - Do one real purchase with a small amount of your own, and refund it from the Dashboard.
Keep in mind:
- Returns, refunds and disputes have their own events, and the Dashboard handles them manually until you build more.
- Stripe emails receipts for you if you turn that on in the Dashboard.
- Tax, shipping address collection, coupons and subscriptions are options on the same Checkout Session. Add them one at a time, and test each in the sandbox.
- Check the API version your account uses in the Dashboard's developer settings. The library sets its own for every request it makes, so what your code sees is stable, but webhook events follow your endpoint's version.
Troubleshooting
No such priceorInvalid API Key: the key and the price must come from the same sandbox. A price from live mode does not exist in the sandbox.- The webhook returns
400for genuine events: the secret is wrong, or a body parser ran first. Use the secret fromstripe listenfor local work and the endpoint's own secret in production, and keepexpress.rawon that route. - You are redirected to
/cancelstraight away: look at the Session response in the Dashboard's logs for an error message, such as an unsupported currency or a price in the wrong mode. - Fulfilment ran twice: the session ID is not stored atomically. Add a unique constraint.
- The customer paid but the webhook never arrived: in the Dashboard's webhook page, look at the delivery attempts for the endpoint. Stripe retries failed deliveries for a time, and you can resend an event by hand.
Next steps
- Understand signature checking in depth: receive and verify webhooks in Node.js.
- Put the app on your server behind HTTPS: Nginx as a reverse proxy for a Node app.
- Keep your keys safe: keep secrets out of Git.
- Build more API routes around it: build a REST API with Express 5.
Related tutorials
- How to Build a REST API with Express 5You will build a small items API with Express 5.3 on Node.js 26 that validates its input, returns the right HTTP status codes, never sends a stack trace to callers, and has automated tests that use only Node's built-in test runner.
- How to Install Node.js 26 LTS on Ubuntu 26.04You will install Node.js 26 LTS with npm from the NodeSource apt repository on Ubuntu 26.04 so that apt keeps it patched, run a first script, set up global npm packages without sudo, and learn the checksum-verified tarball route as an alternative.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials