Payment Flow Test Author

payment-flow-test-author

Covers a refund matrix (full, partial, over-refund) for Stripe, Adyen, PayPal and Braintree, chargebacks with card-network reason codes, and webhook replay through each gateway's simulator.

When to use

Use when a payment integration needs refund, dispute or payment-webhook tests.

/plugin install qa-payment@testland-qa

First time in Claude Code? Add the marketplace with /plugin marketplace add testland/qa

View source (opens in a new tab)

Overview

The three highest-incident payment surfaces after the happy path - refunds, disputes, and webhook handling - are one suite-authoring job, because they share the same substrate: the gateway's async state machine. This workflow builds all three phases in dependency order, driven by the canonical states in references/payment-flow-states.md.

Common bugs each phase catches: double-refund and partial-refund-not-summing (Phase 1); missed evidence deadlines and unreconciled chargeback fees (Phase 2); non-idempotent redelivery handling and spoofable handlers (Phase 3).

When to use

  • New payment integration; need refund / dispute / webhook coverage.
  • A refund- or webhook-related incident; need to backfill tests.
  • Gateway migration; need to re-validate flow logic.

Phase 0 - Map the state machine

Before writing any test, translate the canonical lifecycle (created → requires_action → processing → succeeded → refunded / disputed) into your gateway's vocabulary using references/payment-flow-states.md. Every assertion below is on a state from that grid, and every async assertion waits on the webhook, never the synchronous API return.

Phase 1 - The refund matrix

Inventory refund touchpoints

grep -rn 'refund\|Refund\|REFUND' --include='*.{ts,js,py,java,go,rb,cs}' .

Categorise per gateway + per code path (order cancellation, CS portal, subscription downgrade, dispute-lost automation).

The 7 canonical refund cases

For each (gateway, touchpoint):

#TestExpected
1Full refund of captured chargerefund.status = succeeded; charge.amount_refunded = charge.amount
2Partial refund (50%)refund.amount = 0.5x charge.amount
3Multiple partials summing to fullCumulative refunded = charge.amount; charge.refunded = true
4Over-refund attempt (101%)Gateway rejects; descriptive error
5Refund of already-fully-refunded chargeRejected with "charge_already_refunded" or equivalent
6Refund of failed chargeRejected; no refund created
7Refund of disputed chargePer gateway policy: blocks or allows without reversing the dispute

Per-gateway refund APIs

Stripe, per docs.stripe.com/refunds (opens in new window):

test('over-refund rejected', async () => {
  const intent = await createSucceededIntent({ amount: 1000 });
  await expect(
    stripe.refunds.create({ payment_intent: intent.id, amount: 1500 })
  ).rejects.toThrow(/refund_amount_exceeds_charge_amount/);
});

Adyen refunds are async, per docs.adyen.com/online-payments/refund (opens in new window): the call returns [refund-received]; completion arrives as a [REFUND] notification - assert via webhook, not the sync response. PayPal uses CapturesRefundRequest per developer.paypal.com/docs/api/payments/v2#captures_refund (opens in new window); Braintree requires settlement first (gateway.testing.settle, sandbox-only) before gateway.transaction.refund.

Refund idempotency

test('idempotent refund', async () => {
  const intent = await createSucceededIntent({ amount: 1000 });
  const key = 'refund-' + intent.id;
  const r1 = await stripe.refunds.create({ payment_intent: intent.id, amount: 500 }, { idempotencyKey: key });
  const r2 = await stripe.refunds.create({ payment_intent: intent.id, amount: 500 }, { idempotencyKey: key });
  expect(r1.id).toBe(r2.id);
});

Without idempotency, network retries double-refund the customer.

Phase 2 - The chargeback / dispute suite

  1. Pick the 3-5 reason codes most common for your business from references/reason-codes.md - each code has different evidence requirements.
  2. Trigger a disputable charge in the gateway's test mode (Stripe pm_card_createDispute per docs.stripe.com/testing#disputes (opens in new window); an Adyen [CHARGEBACK] notification per docs.adyen.com/risk-management/disputes-api (opens in new window); a PayPal sandbox dispute per developer.paypal.com/docs/api/customer-disputes/v1 (opens in new window)).
  3. Assert the dispute lands in needs_response (or the gateway equivalent) with the expected reason.
  4. Submit evidence before evidence_details.due_by and assert has_evidence is set, per docs.stripe.com/disputes/responding (opens in new window).
  5. Drive each disposition - won (winning evidence), lost (no response), accepted - and confirm the final state via the charge.dispute.closed webhook.
  6. Verify the ledger reverses funds plus the chargeback fee on a lost dispute.
test('lost dispute reverses funds in ledger', async () => {
  const intent = await createSucceededIntent({ amount: 1000 });
  const dispute = await triggerLostDispute(intent);
  await waitForChargebackEvent();

  const ledger = await getLedgerEntries(intent.id);
  expect(ledger).toContainEqual(expect.objectContaining({ type: 'chargeback', amount: -1000 }));
  expect(ledger).toContainEqual(expect.objectContaining({ type: 'chargeback_fee' }));
});

Phase 3 - Webhook replay via gateway-native simulators

Payment webhooks are the source of truth for async transitions, so every handler must be signature-verified, idempotent, order-tolerant, and replay-safe.

  1. Confirm the handler reads the raw request body - signature verification fails on parsed-then-restringified bytes.
  2. Run the four-case signature gauntlet (unsigned / wrong-secret / valid / expired-timestamp) for your gateway; the per-gateway signature schemes, simulator commands, and the full gauntlet code are in references/replay-simulators.md.
  3. Add the idempotency dedup test - redelivery must not double-process:
test('redelivered webhook handled idempotently', async () => {
  const payload = makeWebhookPayload({ type: 'payment_intent.succeeded' });
  const sig = signPayload(payload);

  await postWebhook(payload, sig);
  await postWebhook(payload, sig);  // redelivery

  const rows = await db.payment_records.count({ event_id: payload.id });
  expect(rows).toBe(1);             // processed exactly once
});
  1. Wire the gateway's replay simulator and drive a real event end to end:
stripe trigger payment_intent.succeeded    # synthetic event to the forward URL
stripe events resend evt_test_12345        # replay a captured event (30-day window)
  1. Add the harder recovery scenarios - out-of-order delivery, mid-handler crash, archive replay, per-gateway suite layout - from references/advanced-recovery-scenarios.md.

For generic webhook receiver testing (Standard-Webhooks signature scheme, non-payment senders, inbound replay hardening), use webhook-delivery-tester in the qa-notifications plugin; this phase covers the payment-gateway-specific surface only.

Emit the coverage matrix

# tests/payment/flow-matrix.yaml
matrix:
  gateways: [stripe, adyen, paypal, braintree]
  refund_variants: [full, partial, multiple-partials, over-refund, already-refunded, failed-charge, disputed-charge]
  dispute_cells: ["Visa 10.4", "Visa 13.1", "Mastercard 4855"] # x [won, lost, accepted]
  webhook_cases: [signature-gauntlet, idempotent-redelivery, out-of-order, crash-recovery]

Report the matrix per release and document deliberate gaps.

Anti-patterns

Anti-patternWhy it failsFix
Test only full-refund happy pathPartial-refund accounting bugs hidePer-variant test
No idempotency key on mutating callsNetwork retry → double refund / chargeAlways set
Skip dispute testsWorst-case impact is highCover top 3-5 reason codes
No due-date trackingEvidence submitted late → auto-loseTest the due-date watcher
Skip chargeback-fee reconciliationBooks don't matchTest the ledger
Skip signature verificationSpoofed webhook payloadsFour-case gauntlet per gateway
Trust HTTP 200 == processedServer may have crashed mid-handlerAtomic commit + event-ID record
Sync assertions on async flowsAdyen / PayPal finalize via webhookWebhook-driven asserts per Phase 0
Test against live APIsReal moneySandbox-only, per payment-gateway-sandboxes

Limitations

  • Real chargebacks take weeks. Test mode collapses the timeline; production verification needs production traffic.
  • Reason codes change. Visa / Mastercard publish updates; test data goes stale annually.
  • Bank-declined refunds simulate poorly; rely on platform-documented test cases.
  • Bank-initiated webhooks aren't always test-mode-triggerable.

References

3-D Secure (3DS) is the EMVCo-specified card-authentication protocol. Per emvco.com (opens in new window), 3DS 2.x is the current spec (cite by stable ID: EMV 3-D Secure Protocol Specification v2.x); 3DS 1.0 is deprecated.

Use this reference when designing multi-gateway 3DS test coverage, auditing a 3DS redirect round-trip, or investigating a challenge-flow regression that is not gateway-specific.

The three flow outcomes

Per EMVCo 3DS 2.x spec:

OutcomeCustomer experienceLiability
FrictionlessNo challenge; issuer authenticates based on risk signalsShifts to issuer (in many regions)
ChallengeCustomer prompted (SMS, biometric, app)Shifts to issuer on success
Not applicable3DS not invoked (non-EU; merchant-initiated)Stays with merchant

The merchant's job: send all available data to the gateway; the gateway + issuer + 3DS server decide the flow.

SCA under PSD2

Per European Banking Authority RTS on SCA (opens in new window): since September 2019 (enforcement gradual through 2021), EU card payments require two-factor SCA (two of knowledge / possession / inherence). Exemptions: low-value (< €30), recurring, trusted-beneficiary, merchant-initiated - each with tracking requirements.

Per-gateway test cards

Per-PAN 3DS test cards for Stripe, Adyen, and Braintree, each with its source doc, are in gateway-test-cards.md (opens in new window). The core Stripe cards used in the assertions below: 4000 0000 0000 3055 (frictionless) and 4000 0027 6000 3184 (challenge).

Test flow surface

1. Merchant calls Authorize / PaymentIntent / Charge
2. Gateway returns "requires_action" / "RedirectShopper" / "PAYER_ACTION_REQUIRED"
   per the host SKILL.md state grid
3. Frontend redirects user to issuer-hosted 3DS challenge
4. User completes challenge (or auto-completes for frictionless)
5. Redirect back to merchant return URL
6. Merchant confirms PaymentIntent (or equivalent)
7. Gateway returns final state (succeeded / failed)

Test surface per step:

StepTest
1Initiate with each test card; assert state
2Frontend handles each gateway's "requires action" key correctly
3Redirect URL is built with the gateway-provided client secret / token
4Issuer-hosted page is reachable (manual + Playwright e2e)
5Return URL handler parses the response correctly
6Confirm call is idempotent (per the host SKILL.md Idempotency section)
7Final state matches expected per test card

Frictionless vs challenge - testable assertions

test('frictionless authentication', async () => {
  // Card 4000 0000 0000 3055 in Stripe test mode
  const intent = await stripe.paymentIntents.create({
    amount: 1000, currency: 'eur',
    payment_method: 'pm_card_threeDSecure2Supported',
    confirm: true,
  });
  expect(intent.status).toBe('succeeded');  // No challenge needed
});

test('challenge flow', async () => {
  // Card 4000 0027 6000 3184
  const intent = await stripe.paymentIntents.create({
    amount: 1000, currency: 'eur',
    payment_method: 'pm_card_threeDSecure2Required',
    confirm: true,
    return_url: 'https://example.com/return',
  });
  expect(intent.status).toBe('requires_action');
  expect(intent.next_action.type).toBe('redirect_to_url');
});

Anti-patterns

Anti-patternWhy it failsFix
Skip 3DS in testsEU regulations require it; you'll discover broken at launchPer-gateway 3DS card battery
Test only happy pathChallenge failure path also mattersTest failure + cancel mid-challenge
No return-URL handler testRace conditions on redirect-back lostTest the full round-trip
Hardcoded redirect URL in production codeLocalhost in prodPer-environment config
Treat requires_action as failureIt's the normal mid-flow stateHandle explicitly
3DS 1 still in code pathsDeprecated since 2022Remove and test
One test for all gatewaysEach handles 3DS slightly differentlyPer-gateway
Sync expectation on async flowConfirm is asyncWait for webhook

Limitations

  • EMVCo 3DS spec is paywalled. Reference by stable ID; rely on gateway docs for test cards.
  • Issuer-hosted challenge UIs vary. Bank-specific design; test via e2e against gateway test mode.
  • SCA exemptions are policy + technical. Code must claim the right exemption + log the decision.
  • 3DS data fields are extensive. Each gateway has its own field names; per-gateway docs are authoritative.

Sources

Reference

Webhook order-tolerance, partial-failure, and archive-replay scenarios

View source (opens in a new tab) (opens in new window)

Deep reference for payment-flow-test-author SKILL.md. Consult once the core signature + idempotency + replay-simulator surface is in place and the suite needs the harder recovery scenarios: out-of-order delivery, mid-handler crash recovery, replay of old events from the gateway archive, and the per-gateway suite layout.

Order-tolerance tests

Webhooks can arrive out of order:

test('out-of-order event delivery handled', async () => {
  const completedEvent = makeEvent({ type: 'payment_intent.succeeded' });
  const creatingEvent = makeEvent({ type: 'payment_intent.created' });

  // Deliver completed BEFORE created
  await postWebhook(completedEvent);
  await postWebhook(creatingEvent);

  // Final state should still be correct
  const record = await db.payments.findOne({ intent_id: completedEvent.data.id });
  expect(record.status).toBe('succeeded');
});

The handler must use versioned events or state-machine gates to handle this:

# Don't blindly overwrite state
def handle_event(event):
    record = db.payments.get(event.intent_id)
    new_state = event.data.status
    if state_transition_allowed(record.status, new_state):
        record.status = new_state
        record.save()
    # else: stale event, ignore

Partial-failure scenarios

What happens when the handler crashes mid-processing?

test('crash mid-processing → retry succeeds', async () => {
  let crashOnce = true;
  const handler = makeHandler({
    onProcessEvent: () => {
      if (crashOnce) {
        crashOnce = false;
        throw new Error('simulated crash');
      }
    },
  });

  await expect(handler.process(event)).rejects.toThrow();  // First attempt crashes
  await handler.process(event);  // Retry succeeds; idempotent

  const record = await db.payments.findOne({ event_id: event.id });
  expect(record).toBeTruthy();
});

Handlers should commit state changes atomically - either the processing succeeds and the event is marked handled, or both roll back.

Replay-from-archive

Production sometimes loses webhooks (network outage, deploy issue). Per gateway docs, all support some form of replay:

GatewayReplay windowMethod
Stripe30 daysstripe events resend <event_id>
AdyenUnlimited (Customer Area)Manual or notification-resend API
PayPal30 daysWebhook resend endpoint
BraintreeUnlimited (Control Panel)Manual or webhookTesting.sampleNotification

Test:

test('handler accepts replay from 7-day-old event', async () => {
  const oldEvent = makeEvent({ created: Math.floor(Date.now()/1000) - 7*86400 });
  const result = await handler.process(oldEvent);
  expect(result).toBe(200);
});

Suite layout

One directory per gateway so per-gateway quirks stay isolated:

tests/payment/webhooks/
  stripe/
    signature.test.ts
    idempotency.test.ts
    order-tolerance.test.ts
    replay.test.ts
  adyen/
    ... (same structure)
  paypal/
    ...
  braintree/
    ...
  fixtures/
    payloads/

Per-PAN test cards that drive 3DS challenge, frictionless, and bypass flows in each gateway's test mode. Cross-referenced from 3ds-flows.md (opens in new window). For single-gateway work, prefer the gateway skills (stripe-test-cards-and-webhooks, payment-gateway-sandboxes).

Stripe

Per docs.stripe.com/testing#regulatory-cards (opens in new window):

CardBehaviour
4000 0027 6000 3184Authentication required (challenge)
4000 0025 0000 3155Authentication required (challenge), payment failure after success
4000 0000 0000 3220Authentication required (challenge), payment success
4000 0000 0000 30553DS supported but not required (frictionless)
4242 4242 4242 4242Standard test card (no 3DS)

Adyen

Per docs.adyen.com/development-resources/test-cards-and-credentials/test-card-numbers (opens in new window):

CardBehaviour
4917 6100 0000 00003DS 2 challenge flow
5454 5454 5454 54543DS 2 frictionless
4012 8888 8888 18813DS 1 (deprecated; for migration testing)

Braintree

Per developer.paypal.com/braintree/docs/guides/3d-secure/testing/node (opens in new window):

CardBehaviour
4000 0000 0000 1091Authenticate via standard flow
4000 0000 0000 1109Frictionless
4000 0000 0000 1125Bypass (skipped)

Overview

Every payment platform exposes a state machine - the PaymentIntent in Stripe, the Authorisation in Adyen, the Order in PayPal, the Transaction in Braintree. Each has different terminology for what is fundamentally the same lifecycle.

Per stripe.com/docs/payments/payment-intents (opens in new window): "The PaymentIntent encapsulates the lifecycle of a customer payment."

The full per-platform terminology grid, the per-provider state machines, and the async webhook / refund / dispute detail live in payment-state-machines.md (opens in new window).

When to read this

  • Designing a payment-flow test suite.
  • Auditing state-handling code for a payment integration.
  • Mapping equivalent states across multiple providers.
  • Investigating "stuck payment" reports.

The canonical states

Most payment systems share the same conceptual lifecycle. The canonical states, in order:

  1. Created - intent exists, no payment method confirmed yet.
  2. Awaiting action - a 3DS or redirect challenge is pending.
  3. Processing - submitted, awaiting the async result.
  4. Authorized (not captured) - funds reserved; auth-only flows stop here.
  5. Captured / succeeded - funds transferred to the merchant.
  6. Failed - declined or rejected.
  7. Cancelled - voided before capture.
  8. Refunded - captured then reversed (async).
  9. Disputed / chargeback - customer's bank pulled the funds.

Each provider names these differently. The full canonical-to-provider grid and the four per-provider state machines (Stripe PaymentIntent, Adyen Authorisation/Capture, PayPal Order, Braintree Transaction) are in payment-state-machines.md (opens in new window).

Authorisation vs capture

Two-step:

  1. Authorize - bank reserves funds; merchant doesn't get them yet.
  2. Capture - funds transferred to merchant.

Default in most systems is auto-capture (auth + capture in one call). Separate auth-then-capture is used for:

  • Hold-then-charge flows (rental cars, hotels).
  • Inventory-confirm-before-charge.
  • Manual fraud review.

Per stripe.com/docs/payments/capture (opens in new window): PaymentIntent with capture_method=manual requires explicit capture call.

How to use

  1. Identify the platform and flow - which provider, and whether it is auth-only or auth+capture (see Authorisation vs capture).
  2. Map its state machine from payment-state-machines.md (opens in new window) - translate the canonical states into that provider's terminology.
  3. Enumerate the async transitions - the webhook states plus the refund, dispute, and chargeback transitions the flow can reach.
  4. Derive test cases per transition - one case per edge, happy and off-path (see State-handling test surface).
  5. Assert the state-handling code covers each - every transition the provider can emit has a handler and is webhook-driven, not inferred from the synchronous API return.

Worked example

Map a Stripe PaymentIntent lifecycle for a 3DS card that then gets refunded. The path: requires_payment_method -> requires_action -> processing -> succeeded, then a refund pending -> succeeded.

Test cases derived, one per transition:

TransitionTest case
requires_payment_method -> requires_actionConfirm with a challenge card; assert requires_action + next_action.type = redirect_to_url
requires_action -> processingComplete the issuer challenge; assert the intent leaves requires_action
processing -> succeededWait for payment_intent.succeeded webhook; assert final state (not the sync return)
succeeded -> refund pendingIssue a full refund; assert refund object pending
refund pending -> succeededWait for charge.refunded webhook; assert refund succeeded

Each async assertion waits on the webhook, so the same lifecycle exercised without 3DS (a frictionless card that skips requires_action) is a separate case, not a variant of this one.

Idempotency

Most payment APIs accept an Idempotency-Key header (Stripe, Adyen) or equivalent. The pattern: retry with the same key produces the same response.

Per stripe.com/docs/api/idempotent_requests (opens in new window): "Stripe supports idempotency for safely retrying requests without accidentally performing the same operation twice."

Tests should verify the merchant code uses idempotency keys for every mutating call.

State-handling test surface

SurfaceTest
Created → succeeded (happy path)Standard test-card; assert each state observed
Requires-action (3DS)Initiate with a challenge test card (Stripe (opens in new window) 4000 0027 6000 3184, Adyen (opens in new window) 4917 6100 0000 0000); assert requires_action / RedirectShopper with next_action.type = redirect_to_url; complete the issuer-hosted challenge; confirm and assert succeeded. Repeat with a frictionless card (Stripe 4000 0000 0000 3055) - must reach succeeded with no challenge. Per 3ds-flows.md (opens in new window)
Failed (insufficient funds)Use insufficient-funds test card; assert state
Cancelled before captureManual-capture + cancel; assert state
Webhook idempotencyReplay webhook twice; assert idempotent handling
Refund fullCapture + full refund; assert state sequence
Refund partialCapture + partial refund; assert state
Dispute wonTrigger dispute; respond; assert won
Dispute lostTrigger dispute; don't respond; assert lost

Anti-patterns

Anti-patternWhy it failsFix
Treating the API return as the final stateAsync; succeeded comes laterWait for webhook
No idempotency keyNetwork retries duplicate-charge customersAlways set idempotency
Hardcoded sleep waiting for webhooksFlakyPoll webhook endpoint or queue with timeout
Skipping the requires-action flow3DS regulations require it for most EU cardsAlways test 3DS path
Stale state stored locallyLocal DB diverges from platformWebhook-driven update
Trust the request-body statusWebhooks can be replayed by attackersVerify signature + idempotency
One test for all platformsState terminology differsPer-platform test suite
Refund tests in sync flowRefunds are asyncWebhook-based

Limitations

  • Platforms evolve. Stripe added the setup_intent for saved payment methods; PayPal's Orders API is newer than the legacy Payments API.
  • Regulatory states change. EU PSD2 introduced strong customer authentication; states evolved to support it.
  • Refund + dispute timelines. Real-world chargebacks take weeks; test environments shortcut this.

References

Reference

Per-platform payment state machines

View source (opens in a new tab) (opens in new window)

Deep reference for payment-flow-states.md (opens in new window). Consult when mapping the canonical lifecycle onto a specific provider, or when auditing that a state-handling integration covers every provider-specific state. The canonical-state names and the decision workflow stay in the SKILL; the full per-platform terminology grid, the per-provider state machines, and the async webhook / refund / dispute detail live here.

Per-platform terminology mapping

Every provider names the same lifecycle differently. This grid maps each canonical state to its provider-specific value.

Canonical stateStripeAdyenPayPalBraintree
Createdrequires_payment_methodReceivedCREATEDcreated
Awaiting action (3DS, etc.)requires_actionRedirectShopperPAYER_ACTION_REQUIREDn/a (handled inline)
ProcessingprocessingPendingPENDINGsubmitted_for_settlement
Authorized (not captured)requires_captureAuthorisedAPPROVED (no immediate capture)authorized
Captured / succeededsucceeded[Capture] SettledCOMPLETEDsettled
Failedfailed (charge)RefusedDECLINEDgateway_rejected / failed
CancelledcanceledCancelledVOIDEDvoided
Refundedsucceeded + refund object[Refund] SettledREFUNDEDrefunded
Disputed / chargebackdisputed (in dispute object)[Chargeback]disputedisputed

Per-platform state machines

Each provider exposes one primary object whose status field walks the lifecycle. Auth-only flows stop at the authorized state until an explicit capture; auth+capture flows run straight to the captured state.

Webhook event sequence

Providers emit one webhook per state transition; the async arrival is why tests must wait for the webhook, not the synchronous API return. Stripe example:

1. customer.created
2. payment_intent.created
3. payment_intent.requires_action   (if 3DS)
4. payment_intent.processing
5. payment_intent.succeeded
   AND
   charge.succeeded

Refund states

captured payment
   ↓
   refund created (status: pending)
   ↓
   refund succeeded (or failed)

Refunds are async: the API call returns immediately with pending, then a webhook delivers the final state minutes to hours later. Per docs.stripe.com/refunds (opens in new window).

Dispute / chargeback states

The most-complex part of the state machine. Per Visa's chargeback reason codes (cite by stable ID: Visa Chargeback Reason Codes), the customer's bank initiates the chargeback and the merchant has a fixed window to respond.

StateMeaning
InquiryBank requests info; not yet a chargeback
Pre-arbitrationInitial dispute filed
WonMerchant evidence accepted
LostMerchant evidence rejected; funds returned to customer
Pre-arbitration acceptedMerchant accepts the loss

Disputes resolve over weeks; test scenarios use test-mode dispute APIs to trigger the transitions synchronously. Per docs.stripe.com/disputes (opens in new window).

Reference

Chargeback reason code catalog

View source (opens in a new tab) (opens in new window)

Pick the 3-5 most-common reason codes for your business and verify the evidence-collection flow for each. Each code carries different evidence requirements, so a single-reason test under-covers the suite. Visa, Mastercard, and AmEx each maintain their own reason-code catalogs.

Visa

Per Visa Chargeback Reason Codes (cite by stable ID: Visa Chargeback Management Guidelines):

CodeCategoryDescription
10.4Fraud"Card-absent environment fraud"
11.1AuthorizationCard recovery bulletin
11.2AuthorizationDeclined authorization
11.3AuthorizationNo authorization
12.1Processing errorsLate presentment
12.2Processing errorsIncorrect transaction code
12.3Processing errorsIncorrect currency
12.4Processing errorsIncorrect account number
13.1Consumer disputesMerchandise/services not received
13.2Consumer disputesCancelled recurring transaction
13.3Consumer disputesNot as described
13.5Consumer disputesMisrepresentation

Mastercard

Per Mastercard MCC chargeback reason codes (cite by stable ID: Mastercard Chargeback Guide):

CodeDescription
4853Cardholder disputes
4855Non-receipt of merchandise
4859Services not rendered
4863Cardholder doesn't recognize

Sources

  • Visa Chargeback Reason Codes (cite by stable ID: Visa Chargeback Management Guidelines).
  • Mastercard Chargeback Guide (cite by stable ID).
Reference

Gateway-native replay simulators + signature schemes

View source (opens in a new tab) (opens in new window)

Deep reference for payment-flow-test-author SKILL.md Phase 3. The per-gateway mechanics for driving and replaying real webhook events, and the signature-verification gauntlet each gateway needs.

Replay simulators

Each gateway ships a way to (re)send a real event at the handler:

GatewayReplayNotes
Stripestripe trigger payment_intent.succeeded; stripe events resend evt_test_12345CLI (stripe-cli (opens in new window)); resend covers a 30-day window (cli/events/resend (opens in new window))
AdyenCustomer Area transaction "Resend webhook"Re-sends with the original signature - useful for idempotency tests
PayPalDashboard simulator; REST equivalent via the APIsimulate-event (opens in new window)
Braintreegateway.webhookTesting.sampleNotification(kind, id)Generates a test signature for any event kind (parse/node (opens in new window))

Signature schemes

The scheme differs per gateway; run the same four-case gauntlet against each:

GatewaySignature schemeReference
StripeHMAC-SHA256 over the payload; the signature carries a timestamp, so old timestamps rejectwebhooks/signatures (opens in new window)
AdyenHMAC-SHA256 over the canonical string; validated per-event, not per-requestverify-hmac-signatures (opens in new window)
PayPalSHA256-with-RSA; verify via the PayPal verification endpoint or SDK helperwebhooks/rest (opens in new window)
Braintreeparser validates bt_signature against the merchant's public keyBraintree webhook parser

The four-case signature gauntlet (Stripe form)

Per docs.stripe.com/webhooks/signatures (opens in new window), the gauntlet is four cases - unsigned, wrong-secret, valid, and expired-timestamp:

const payload = JSON.stringify({ type: 'payment_intent.succeeded' });

test('rejects unsigned payload', async () => {
  const res = await fetch('/webhooks/stripe', { method: 'POST', body: payload });
  expect(res.status).toBe(401);  // No Stripe-Signature header
});

test('rejects wrong-secret signature', async () => {
  const wrongSig = stripe.webhooks.generateTestHeaderString({ payload, secret: 'wrong-secret' });
  const res = await fetch('/webhooks/stripe', {
    method: 'POST', body: payload, headers: { 'stripe-signature': wrongSig },
  });
  expect(res.status).toBe(401);
});

test('accepts valid signature', async () => {
  const sig = stripe.webhooks.generateTestHeaderString({
    payload, secret: process.env.STRIPE_WEBHOOK_SECRET!,
  });
  const res = await fetch('/webhooks/stripe', {
    method: 'POST', body: payload, headers: { 'stripe-signature': sig },
  });
  expect(res.status).toBe(200);
});

test('rejects expired timestamp', async () => {
  const oldSig = stripe.webhooks.generateTestHeaderString({
    payload,
    secret: process.env.STRIPE_WEBHOOK_SECRET!,
    timestamp: Math.floor(Date.now()/1000) - 3600,  // 1 hour ago
  });
  const res = await fetch('/webhooks/stripe', {
    method: 'POST', body: payload, headers: { 'stripe-signature': oldSig },
  });
  expect(res.status).toBe(401);
});

Gotcha: the handler must read the raw request body - a parsed-then-restringified copy fails signature verification on the restringified bytes.

Sources

Get new posts by email.

Occasional email with new Testland posts and plugin releases.

Unsubscribe any time. Privacy policy