Join our Newsletter — 33% off our NHI Course
Home› Guides› Payment Gateway Integration Security Guide: Keys, Webhooks and…
Guide Web & API Security

Payment Gateway Integration Security Guide: Keys, Webhooks and Checkout

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 13 min read
On this page

Outsourcing card processing to a payment gateway removes card data from your servers, but it does not remove the logic that decides what the customer pays and whether an order is marked as paid, and that logic is where most integration attacks land. Price tampering in the cart, spoofed or replayed payment callbacks, trusting the browser redirect instead of the gateway's server-to-server notification, and leaked gateway API keys all lead to goods shipped for free or money moved without authority. This guide walks through a typical gateway flow step by step, the controls at each step, webhook verification, gateway credentials as non-human identities, PCI DSS scope effects, and how to test and monitor the integration. It is for developers, architects and security reviewers integrating hosted checkouts, payment links or gateway APIs.

Key takeaways

  • The server owns the price. Recalculate every total, discount and currency from trusted data on the backend before creating the gateway order; the client only sends product IDs and quantities.
  • The browser redirect proves nothing. OWASP's gateway cheat sheet states that only server-to-server callbacks should be trusted for payment verification and fulfilment; the return URL is user-controlled.
  • Verify, then reconcile. Check the webhook signature on the raw body with a constant-time compare, check freshness, then confirm amount, currency and order ID against your record, or query the gateway API for the current state.
  • Fulfil exactly once. Gateways retry (Stripe for up to three days in live mode) and do not guarantee order, so fulfilment must be idempotent on the event and order IDs.
  • Gateway keys are high-value machine credentials. Secret API keys and webhook signing secrets belong in a secrets manager with least privilege, per-environment separation and rotation.

The payment flow and where it breaks

The OWASP Secure Integration of Third-Party Payment Gateways Cheat Sheet describes five steps common to most integrations. The table maps the risks and controls at each.

StepWhat happensTypical risksControls
1. Cart preparationUser selects items and starts checkoutPrice, quantity or product substitution in client-side data; negative quantities; stacked discount codesServer-side cart; validate product IDs, prices, discounts and quantity bounds
2. Order initialisationBackend creates the gateway order and gets an order_id or payment_urlTotals taken from the request; order created in client-chosen currency; gateway key exposed in front-end codeRecalculate totals server-side; create the order only from the backend with the secret key; store expected amount, currency and order ID
3. Redirect to gatewayUser goes to the gateway-hosted page or embedded fieldsTampered redirect parameters; skimming script on your page if fields are not isolatedUse gateway-hosted pages or iframed fields; protect any page that loads them (PCI DSS script controls)
4. Payment executionUser pays or fails at the gatewayCard testing; 3-D Secure skipped where requiredGateway fraud tools, rate limits on order creation, SCA where required
5. Return and verificationUser returns to your return URL; gateway sends a server-to-server notificationTrusting return URL parameters; spoofed, replayed or out-of-order callbacks; race between multiple callbacks; fulfilling before verificationVerify signature and freshness; reconcile amount, currency and order ID; idempotent fulfilment; trust only server-to-server notifications

Many of these are business logic flaws rather than injection bugs, so scanners rarely find them. See the Business Logic Vulnerabilities Guide for the wider class.

Price and order integrity

  • Accept identifiers, not values: the checkout request should carry product IDs, quantities and a discount code. Prices, tax, shipping and the final total are computed on the server from the catalogue and promotion rules.
  • Bound everything: reject zero, negative and absurd quantities, and totals below a sane floor. Apply discount codes once per order and check their eligibility server-side.
  • Freeze the order: once the gateway order is created, store the expected amount, currency, merchant reference and line items. Any later change to the cart creates a new gateway order rather than editing the old one.
  • Currency is part of the amount: 100 in a weak currency is not 100 in a strong one. Compare amount and currency together at verification.
  • Remember why validation is not enough: the OWASP Business Logic Security Cheat Sheet gives the textbook case: every input in a checkout request passes validation, yet the server recalculates the total from a client-submitted price, so a user pays one cent for a television. Its rule of thumb is that if a value influences price, access, ownership or state, assume the client made it up and recompute it from trusted data.
  • Use a merchant reference you control: pass your own order ID to the gateway in the metadata or reference field so callbacks map unambiguously to one order.

Webhook and callback verification

The gateway's server-to-server notification is the authoritative signal that money moved. The OWASP Webhook Security Cheat Sheet and Stripe's webhook documentation describe the controls in detail.

ControlDetailFailure if missing
Signature over the raw bodyUse the gateway's library; supply the raw bytes before the framework parses JSON. Stripe signs timestamp.payload with HMAC-SHA256 and sends it in the Stripe-Signature header as t= and v1= valuesForged "payment succeeded" events
Constant-time comparisonFor example hmac.compare_digest, crypto.timingSafeEqual, MessageDigest.isEqual; never ==Timing side channel on the signature check
Accept only the expected schemeStripe says to ignore any scheme other than v1 to prevent downgradeDowngrade to a weaker or test scheme
Freshness windowReject signed timestamps outside a small tolerance; Stripe libraries default to 5 minutes and Stripe warns that a tolerance of 0 disables the check; keep clocks synchronised with NTPReplay of a captured delivery
Event ID deduplicationPersist processed event IDs for at least the gateway's retry periodDouble fulfilment, duplicate credits
ReconciliationMatch amount, currency and order ID with the stored order; for anything ambiguous, fetch current state from the gateway APIPartial payment or a payment for another order fulfils this one
Fast acknowledgement, asynchronous processingReturn 2xx quickly and process via a queueTimeouts cause retries and duplicate processing
IP allowlisting (defence in depth)Gateways publish delivery addresses; OWASP treats allowlisting as an extra layer only, because ranges changeNone on its own; signature verification remains mandatory

Two delivery behaviours shape the design. Stripe documents that it retries failed deliveries for up to three days with exponential backoff in live mode and generates a new timestamp and signature for each retry, and that it does not guarantee event order. The OWASP gateway cheat sheet adds that checkout expiry should be handled separately from signature freshness: a late but genuine notification should be verified and reconciled, not discarded because the checkout session expired. See the Webhook Secrets Security Guide for signing secret management.

A practical note from Stripe's documentation: frameworks such as Rails and Django apply CSRF protection to POST routes, so the webhook route usually needs a narrow CSRF exemption. Make the exemption specific to that one route, and rely on signature verification for that route instead.

Gateway credentials as non-human identities

A gateway secret key can create charges, issue refunds, read customer data and change webhook endpoints. It is one of the most powerful machine credentials in an e-commerce stack, and it is often hard-coded or copied between environments.

  • Separate publishable and secret keys: only publishable keys belong in front-end code. Scan repositories and client bundles for secret key prefixes in CI.
  • Restrict scope: where the gateway supports restricted or scoped keys, issue each service only the permissions it needs (for example create payment intents but not refunds).
  • Separate environments: test and live keys, and test and live webhook secrets, in different secret stores. Stripe generates a unique signing secret per endpoint and a different one for test and live.
  • Rotate safely: Stripe allows rolling a webhook secret with an overlap of up to 24 hours, signing with each active secret during that time. Rotate on staff changes and on any suspected exposure.
  • Watch the admin plane: dashboard accounts that can change payout bank details or webhook URLs need phishing-resistant MFA and change alerts, because redirecting payouts is a direct theft path.

See the PCI DSS Requirements for Service Accounts and NHIs Guide (8.6) for how PCI DSS treats system and application accounts.

PCI DSS scope and integration models

ModelWhere card data is enteredYour exposureNotes
Full redirect to a hosted payment pageGateway's domainLowest; the page that redirects can still be tampered withUsually the smallest PCI DSS scope
Embedded iframe or hosted fieldsGateway-served iframe inside your pageYour page hosts the frame, so scripts on it matterPCI DSS v4.0 Requirements 6.4.3 (payment page script management) and 11.6.1 (change and tamper detection) are relevant
Direct API or JavaScript that collects card data on your pageYour page or serverHighest; you handle card dataAvoid unless you need it and can meet the full requirements
Payment links or invoicesGateway's domainLow, but links can be phished or reusedExpire links and bind them to one order

Scope rules are detailed and set by the PCI Security Standards Council and your acquirer; confirm your eligibility for any self-assessment questionnaire with them. See the PCI DSS for E-commerce Payment Page Scripts Guide and the PCI DSS Scoping and Network Segmentation Guide. The OWASP gateway cheat sheet also reminds integrators not to retain sensitive authentication data such as card verification codes after authorisation, even if encrypted.

Implementation and testing

  1. Draw the flow: document every request between browser, your backend and the gateway, including retries, refunds, partial captures and cancellations. Mark which party is trusted for each value.
  2. Move pricing server-side: refactor checkout so the client sends identifiers only; add unit tests that tampered prices and quantities are ignored or rejected.
  3. Implement the webhook handler: raw body, gateway library verification, scheme check, tolerance, deduplication table, reconciliation, queue.
  4. Gate fulfilment: one function marks an order paid, and it requires a verified, reconciled notification or an API lookup; the return URL handler only shows "processing" until then.
  5. Test abuse cases in a sandbox: modified totals, replayed webhook deliveries, deliveries with a bad signature, out-of-order events, concurrent duplicate deliveries (race on the deduplication check), callbacks for a different order, partial amounts, and currency mismatch. The OWASP Web Security Testing Guide has a payment functionality test section for reviewers.
  6. Pilot and monitor: release behind a feature flag to a fraction of traffic and compare paid-order counts against gateway settlement reports.
  7. Roll back: keep the previous handler deployable, but never fall back to trusting return URL parameters.

Decision guidance

  • Small merchants: hosted payment pages or payment links from the gateway, the gateway's official SDK for webhooks, and no card data on your systems. See the Card Payments Security for Small Merchants Guide.
  • Mid-size platforms: hosted fields for conversion, strict script controls on checkout pages, a dedicated payments service holding the gateway keys.
  • Marketplaces and multi-gateway platforms: a payment orchestration layer that normalises callbacks, enforces one verification and reconciliation path for every gateway, and keeps per-gateway credentials isolated.

Detection and measurement

The OWASP gateway cheat sheet recommends logging every payment attempt, redirect and callback with timestamps and source addresses, and alerting on orders marked paid without gateway confirmation, excessive callbacks for one order, and repeated failures with identical data. Log callback identifiers, validation outcomes and order correlation data rather than raw bodies and headers, and exclude credentials and unnecessary card or personal data.

MetricTarget
Orders marked paid without a verified notification or API confirmationZero
Daily reconciliation differences between paid orders and gateway settlementZero unexplained differences
Webhook signature failures per dayNear zero; spikes indicate probing or a misconfigured secret
Duplicate deliveries suppressed by deduplicationTracked; confirms retries are handled
Gateway secret keys older than the rotation policy, or found in code scansZero
Order creation rate per session or IPBaseline with alerts for card-testing spikes

Common failure patterns

  • Trusting the return URL: marking orders paid because the browser arrived at /success?status=paid.
  • Client-side totals: sending the amount from the browser to the order creation call.
  • Parsing before verifying: a framework re-serialises the JSON so verification fails, and someone "fixes" it by disabling the check.
  • No idempotency: retries and duplicate events ship goods twice or credit wallets twice.
  • Storing card data you do not need: the AI Agent Retail Card Theft Campaign 2026 shows the cost: most cards came from store databases decrypted with a key reached through dumped cloud secrets, alongside skimmers planted on checkout pages. Hosted fields or tokenisation keep card numbers out of your database; see the Tokenisation and Data Masking Guide.
  • Shared gateway keys across environments: a leaked staging config exposes live refund capability.

Framework mapping

FrameworkReferenceRelevance
OWASP ASVS 5.0V2.3.3; V16.5.3; V4.1.5Business transactions succeed entirely or roll back; fail securely without processing a transaction after validation errors; signed messages for sensitive transactions
PCI DSS v4.0Requirements 6.4.3, 11.6.1, 8.6Payment page scripts, tamper detection, system and application accounts
NIST SP 800-53 Rev. 5SI-10, SC-8, AU-12, SA-9Input validation, integrity in transit, audit records, external services
MITRE ATT&CKT1565.002 Transmitted Data Manipulation; T1565.001 Stored Data ManipulationTampering with order and payment data
MITRE CAPECCAPEC-162 Manipulating Hidden FieldsClient-side price tampering

Practitioner checklist

  • Compute every price, discount, tax and total on the server; the client sends identifiers only.
  • Store expected amount, currency and order ID when creating the gateway order.
  • Treat return URL parameters as untrusted; fulfil only on a verified server-to-server notification or API lookup.
  • Verify webhook signatures on the raw body with the gateway library, a constant-time compare and the expected scheme only.
  • Enforce a freshness window and deduplicate event IDs across the full retry period.
  • Make fulfilment idempotent and safe under concurrent duplicate deliveries.
  • Keep secret keys and webhook secrets in a secrets manager, scoped, per environment, and rotated.
  • Use hosted pages or hosted fields so card data never touches your systems, and control scripts on any page that hosts them.
  • Reconcile paid orders against gateway settlement daily and alert on mismatches.
  • Apply the same verification, reconciliation and idempotency rules to refunds, partial captures and cancellations, which attackers probe as often as payments.

Standards and references

Related NHI Mgmt Group resources: Webhook Secrets Security Guide · PCI DSS for E-commerce Payment Page Scripts Guide · Retail and E-Commerce Identity Security Guide · Transaction Authorisation Guide · Card Testing and Carding Attacks Defence Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.