Securing Stripe payments
An application that takes payments through Stripe holds API keys that let its server create charges, refunds and customers through the Stripe API, and it runs a webhook endpoint, a public address to which Stripe posts events such as a completed payment. Attackers go after both. A leaked server key lets its holder "make unauthorized charges, access customer data, or disrupt your integration",1 and an endpoint that accepts unverified events lets anyone mark an order as paid.
Steps
1. Keep every key except the publishable key on the server
Stripe issues three kinds of account key, told apart by their prefix. Keys for a test sandbox contain _test_ and keys for real payments contain _live_.2
| Key | Public | What it can do |
|---|---|---|
Publishable, pk_live_ | Yes | Identify the account and turn card details into tokens or PaymentMethods. It cannot create charges or read account data. |
Restricted, rk_live_ | No | Only what its permissions allow, set per resource as Read, Write or None. |
Secret, sk_live_ | No | Everything, on every Stripe API. |
Only the publishable key is safe outside the back end.2 A restricted or secret key placed in browser JavaScript, in an HTML page or in a mobile build can be read by anyone who downloads it, and people do take apps apart to look for keys inside them.1 The general case is described in Privileged key in client-side code and Client-side code exposure.
2. Use restricted keys with only the permissions each part needs
New integrations should use restricted keys, and existing code should move off secret keys.2 Create one under API keys, Create restricted key, starting from zero permissions and granting each resource the code uses, which is the principle of least privilege applied to a key. Stolen, a key that can only read disputes still cannot create charges, read customers' payment methods or start payouts.3
3. Store keys outside the code and limit where they work
Keys belong in the hosting platform's secrets store, or in environment variables where none exists, and never in files under version control. Attackers scan public repositories for Stripe keys without pause, so run a secret scanner with Stripe patterns and add a pre-commit hook that rejects commits containing a key.1 A key can also be limited to the server's fixed IP addresses, so a copy used from elsewhere is refused.1
A key that has been visible somewhere it should not be, such as a public repository, a log file or an email, needs to be rotated at once, whether or not anyone used it.1 The response steps are in Responding to a leaked API key.
4. Set the amount on the server
The price of an order comes from the server's own records, never from a value the browser sends. An amount decided on the client lets "malicious customers" choose "their own prices".4
5. Verify the signature of every webhook
Each event Stripe sends carries a Stripe-Signature header with a timestamp t and one or more v1 values. A v1 value is an HMAC with SHA-256, computed over the timestamp, a full stop and the request body exactly as sent, keyed with the endpoint's signing secret. That secret starts with whsec_, is separate from the API keys and is shown per endpoint in the Dashboard.56 Without the secret, nobody can produce a matching value for a forged event.
The Stripe libraries do the check in one call, which needs the raw body. Any framework step that parses the body as JSON, reorders keys or strips whitespace first makes every check fail.56 In the Next.js App Router, Stripe's example reads the body as text:7
// app/api/webhooks/route.ts
import { Stripe } from 'stripe';
import { headers } from 'next/headers';
// a restricted key (rk_live_...) from the environment
const stripe = new Stripe(process.env.STRIPE_API_KEY);
export async function POST(req) {
let event;
try {
event = stripe.webhooks.constructEvent(
await req.text(),
(await headers()).get('stripe-signature'),
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
return new Response('Invalid signature', { status: 400 });
}
// handle event.type here
return new Response('ok', { status: 200 });
}In Express, the webhook route has to be registered before app.use(express.json()), because Express runs middleware in order.6
Because the timestamp is inside the signed text, an attacker who captures one delivery cannot change its time. The libraries reject events signed more than 5 minutes ago, which stops a captured event being sent again later. A tolerance of 0 turns this check off.5 The endpoint can also refuse requests from outside Stripe's published IP addresses, and it belongs behind TLS.89
6. Fulfil each payment once, from the webhook
A customer can pay and lose the connection before the return page loads, so fulfilment cannot rely on that page alone.10 The same event can also arrive more than once and out of order. Store the IDs of processed events and skip repeats.5 Before an action that matters, fetch the current object from the API, since the copy inside an event can be out of date, then check its payment_status and record that the order was fulfilled.810
7. Limit card testing on the payment form
A card-testing script tries stolen card numbers through a site's payment or card-saving form, often with small amounts, to learn which cards still work. The publishable key on the site is all it needs. The merchant is left with disputes, fees and more declines for real customers.11 Stripe Checkout and the current Payment Element include rate limiters and CAPTCHA triggers. A custom form needs its own controls: a CAPTCHA checked on the server, a login before payment, and rate limits such as a cap on new customers per IP address per day. A rule based on IP addresses alone is usually not enough.11
8. Keep card numbers off the server
A business whose servers handle full card numbers may face more than 300 PCI DSS controls. With Stripe's low-risk integrations, card data goes straight to Stripe and never passes through the application's servers. The server stores only what comes back, such as the card brand, the last four digits and the expiry date, all outside PCI scope.9 Keep scripts from other sites off payment pages where possible: a compromised script can run any code on the page.9
Prompt for a coding agent
Review how this project uses Stripe. 1) Find every Stripe key in the code, config files and anything sent to the browser or built into a mobile app; only a publishable key (pk_) may be there, and every other key must come from an environment variable on the server. 2) Make sure every payment amount is set on the server from our own prices, never from a value sent by the browser. 3) In the webhook route, verify the Stripe-Signature header with stripe.webhooks.constructEvent on the raw request body and the STRIPE_WEBHOOK_SECRET variable, return 400 when it fails, and keep the default timestamp tolerance. 4) Store processed event IDs and skip repeats, and only fulfil an order after fetching the Checkout Session and checking payment_status. List each file you changed and anything you were unsure about.
In SecFlash
SecFlash reports a route that takes payment events without checking their signature as SF-SEC-726 on the Security page. A secret key found in public JavaScript, in the HTML of a page or in a mobile build shows on the Exposure page as SF-EXP-301, SF-EXP-304 or SF-EXP-612; a Stripe publishable key appears there as SF-EXP-306. Scripts from other companies on a payment page are reported as SF-SEC-402 on the Security page.
See also
- Privileged key in client-side code
- Abuse of leaked API keys
- Secrets management
- Principle of least privilege
- Rate limiting
- Responding to a leaked API key
- Category: Guides
References
- a b c d e Stripe (n.d.). "Best practices for managing secret API keys". Stripe Docs.
- a b c Stripe (n.d.). "API keys". Stripe Docs.
- back Stripe (n.d.). "Restricted API keys". Stripe Docs.
- back Stripe (n.d.). "Accept a payment". Stripe Docs.
- a b c d Stripe (n.d.). "Receive Stripe events in your webhook endpoint". Stripe Docs.
- a b c Stripe (n.d.). "Manage webhook endpoints". Stripe Docs.
- back Stripe (n.d.). "examples/webhook-signing/nextjs/app/api/webhooks/route.ts". stripe-node on GitHub.
- a b Stripe (n.d.). "Set up events". Stripe Docs.
- a b c Stripe (n.d.). "Integration security guide". Stripe Docs.
- a b Stripe (n.d.). "Fulfill orders". Stripe Docs.
- a b Stripe (n.d.). "Protect yourself from card testing". Stripe Docs.
External links
- Best practices for managing secret API keys, Stripe Docs
- Receive Stripe events in your webhook endpoint, Stripe Docs