MockCard API documentation

Version 2.0. Everything the dashboard, the GitHub Action and the SDKs do is plain HTTP and documented here. Coming from 1.x? Read Upgrading to 2.0. Setting up CI or monitoring? Start with the CI runs & monitoring guide. The machine-readable spec is at /openapi.yaml.

Overview

MockCard is a REST API for testing what your payment code does when payments go wrong, without a gateway sandbox. It has two layers:

  • Checks: generate Luhn-valid test cards for Visa, MasterCard, RuPay and Amex with any outcome (approval, decline, 3DS, timeout, limbo, latency) in Stripe or Razorpay wire format, and run a 5-probe webhook health check. Works without an account.
  • Runs and monitoring Pro · Agency: chaos runs that deliver signed duplicate, missing, late and abandoned-payment webhooks to your handler in CI or on staging, outcome assertions through the SDKs, safe signed probes for production, scheduled monitors with alerts, and client reports for agencies.
PropertyValue
Base URLhttps://www.mockcard.io
FormatJSON request and response bodies (application/json)
AuthenticationOptional for checks, required for everything else: X-Api-Key header (see below)
ErrorsAlways { "error": { "code", "message" } }, see Error codes
Webhook signingMockCard's HMAC-SHA256 by default; your gateway's own scheme when a project has your test secret
SpecOpenAPI 3.1 (/openapi.yaml)

Want to see it before you code?

The Playground fires a real request, shows the JSON response and the webhook event, all in your browser.

Open Playground →

Authentication & API keys

Send your key in the X-Api-Key header. Keys look like mc_ followed by 48 hex characters. Get one by verifying your email on the dashboard: your first key is shown once at sign-up, and you can create more there or with POST /api/keys.

ScopeCan doUse it for
ciGenerate cards, run health checks, create runs and report results, read projects, runs and monitors.CI secrets, test suites, the GitHub Action. Safe to hand to a pipeline.
accountEverything a ci key can, plus create and change projects, monitors, keys and team settings.Scripts that manage your setup. Keep it out of CI.
  • Keys are stored as SHA-256 hashes. MockCard can't show a key again after creating it: store it when it's shown, and revoke and replace it if you lose it.
  • A request that sends an X-Api-Key that doesn't match an active key fails with 401 invalid_api_key. It is never quietly treated as anonymous.
  • A ci key used for an account action fails with 403 insufficient_scope.
  • The website uses a session cookie (30 days) instead of a key. Sessions always have account scope.
  • The SDKs read MOCKCARD_API_KEY from the environment when you don't pass a key.

Plans & usage limits

AnonymousFreeProAgency
Price (USD)FreeFree$24.99/mo · $249/yr$74.99/mo · $749/yr
Metered calls5 in total50 / month2,000 / month10,000 / month
Chaos scenarios, webhook delivery, runs——YesYes
Projects——325
Monitors——325
Team seats—115
Client reports———Yes

What counts as a call: a successful POST /api/v1/generate (declines and timeouts are successful simulations and count too), a health check (POST /api/v1/audit/quick), creating a run, “run now” on a monitor, and a manual probe. Scheduled monitor runs, reading results, and requests rejected for bad input or a missing plan don't count. Usage resets on the 1st of each month (UTC). When it runs out you get 429 rate_limit_exceeded (or anonymous_limit_reached without a key).

Quick start

One POST request. The key is optional here: without one you get 5 anonymous calls in total, enough to try it.

curl -X POST https://www.mockcard.io/api/v1/generate \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $MOCKCARD_API_KEY" \
  -d '{
    "brand": "visa",
    "scenario": "success",
    "amount": 1000,
    "currency": "inr"
  }'

Testing a whole webhook handler rather than one call? The SDKs and GitHub Action run every scenario against your app and check what it did.

POST /api/v1/generate

Returns a mock card and simulates the payment outcome. For decline and timeout scenarios the HTTP status is the gateway's (402, 504) and there's no cardfield. That's a successful simulation, not an API failure. On paid plans, if you pass a webhook_url, the signed event is delivered there after the response.

Request body (all fields optional)

FieldTypeDefaultDescription
brandstringvisavisa · mastercard · rupay · amex
scenariostringsuccessSee Test scenarios
gatewaystringstripestripe or razorpay: the wire format of the error body and webhook event
amountinteger1000Smallest currency unit (cents, paise). 1 to 100,000,000.
currencystringinrISO 4217 code, 3 characters
webhook_url Pro · AgencystringnullWhere to POST the signed event. https:// (or http://localhost for local testing). Ignored on Free and anonymous calls, which still get a response.
simulate_race Pro · AgencybooleanfalseDeliver the event a second time ~1 s later with the same event id. Needs webhook_url. 402 pro_required on Free.
return_urlstringnullWhere the mock 3DS challenge page sends the customer afterwards (3ds_challenge). https:// or a relative path.

Response: 201 Created (success, limbo, latency)

{
  "status": "success",
  "payment_intent_id": "pi_mock_x7y8z9a0b1c2",
  "scenario": "success",
  "card": {
    "brand": "visa",
    "card_number": "4539578763621486",
    "masked_number": "••••••••••••1486",
    "expiry_month": "07",
    "expiry_year": "2028",
    "cvv": "382",
    "cardholder_name": "PRIYA PATEL",
    "luhn_valid": true
  },
  "webhook_event": {
    "id": "evt_mock_a1b2c3d4e5f6",
    "object": "event",
    "type": "payment_intent.succeeded",
    "created": 1741708800,
    "livemode": false,
    "data": {
      "object": {
        "id": "pi_mock_x7y8z9a0b1c2",
        "object": "payment_intent",
        "amount": 1000,
        "currency": "inr",
        "status": "succeeded",
        "payment_method_details": {
          "type": "card",
          "card": { "brand": "visa", "last4": "1486", "exp_month": "07", "exp_year": "2028" }
        }
      }
    },
    "delivery": null
  },
  "log_id": 18342
}

Response: 402 / 504 (decline, 3DS and timeout scenarios)

{
  "error": {
    "code": "card_declined",
    "message": "Your card has insufficient funds.",
    "decline_code": "insufficient_funds"
  },
  "webhook_event": {
    "id": "evt_mock_d4e5f6g7h8i9",
    "object": "event",
    "type": "payment_intent.payment_failed",
    "created": 1741708800,
    "livemode": false,
    "data": {
      "object": {
        "id": "pi_mock_j0k1l2m3n4o5",
        "object": "payment_intent",
        "amount": 1000,
        "currency": "inr",
        "status": "requires_payment_method",
        "last_payment_error": {
          "code": "card_declined",
          "decline_code": "insufficient_funds",
          "message": "Your card has insufficient funds.",
          "type": "card_error"
        }
      }
    },
    "delivery": null
  },
  "log_id": 18342
}

Top-level response fields

FieldTypeDescription
payment_intent_idstringYour transaction reference. pi_mock_… for Stripe, pay_mock_… for Razorpay. Matches the id inside the webhook event.
log_idinteger | nullMockCard's log row. Pass it to GET /api/v1/delivery-status?id= to see whether the webhook was delivered.
cardobject | absentPresent on 201 responses only. See below.
errorobject | absentPresent on 402/504 outcomes. Shape depends on gateway (see Gateway simulation).
webhook_eventobject | absentThe event payload. Only returned to the website and anonymous calls. With an X-Api-Key it is omitted: the event goes to your webhook_url instead, the way a real gateway works.

Card object

FieldTypeDescription
brandstringCard network (visa · mastercard · rupay · amex)
card_numberstringFull 15- or 16-digit PAN, Luhn-valid
masked_numberstringPAN with all but the last 4 digits replaced by •
expiry_monthstringTwo-digit month (01–12)
expiry_yearstringFour-digit year (current year + 1 to + 5)
cvvstring3-digit CVV (4-digit CID for Amex)
cardholder_namestringUppercase cardholder name
luhn_validbooleanAlways true

Card brands

BIN prefixes follow the official IIN ranges, and the Luhn check digit is computed, so every number passes real gateway format validation.

BrandEnum valueBIN prefixesCard length
Visavisa416
MasterCardmastercard51–55, 2221–272016
RuPayrupay60, 65, 81, 8216
Amexamex34, 3715

Test scenarios

Pass one of these as scenario. Event types shown are for gateway: stripe; see Gateway simulation for Razorpay.

Standard scenarios (every plan)

ScenarioEnum valueHTTPStripe event typeDescription
Successsuccess201payment_intent.succeededApproved; card returned
Insufficient fundsinsufficient_funds402payment_intent.payment_failedDeclined: no funds
Do not honordo_not_honor402payment_intent.payment_failedGeneric issuer decline
Expired cardexpired_card402payment_intent.payment_failedCard past its expiry date
Incorrect CVVincorrect_cvv402payment_intent.payment_failedSecurity code mismatch
3DS challenge3ds_challenge402payment_intent.requires_actionBank challenge required. The mock challenge page accepts 123456 and then fires payment_intent.succeeded.
Network timeoutnetwork_timeout504payment_intent.payment_failed10 s gateway lag, then 504

Chaos scenarios Pro · Agency

The edge cases production systems fail on, which gateway sandboxes don't produce. On Free and anonymous calls they return 402 pro_required.

ScenarioEnum valueHTTPStripe event typeDescription
3DS abandoned3ds_abandoned402payment_intent.canceledCustomer closes the 3DS window; the intent is cancelled
Limbolimbo201payment_intent.succeededCaptured and 201 returned, but the webhook is never delivered. Tests reconciliation.
Latencylatency201payment_intent.succeededSucceeds now; the webhook arrives 9 s later. Exposes timeout-then-retry double processing.

Runs add one more scenario, duplicate: the same success event delivered twice at the same moment. See Chaos runs.

Gateway simulation

Add "gateway": "razorpay"to get the response and webhook in Razorpay's wire format: their error envelope, payment entity and signature header. No Razorpay account needed. The card object is the same for every gateway; only the event and error shapes change.

Stripe vs Razorpay at a glance

PropertyStripe (default)Razorpay
payment_intent_id prefixpi_mock_…pay_mock_…
Success eventpayment_intent.succeededpayment.captured
Failure eventpayment_intent.payment_failedpayment.failed
3DS eventpayment_intent.requires_actionpayment.authorized
Error envelopeerror.code + decline_codeerror.code + reason + source + step + metadata.payment_id
Signature (MockCard key)X-MockCard-Signature: sha256=…X-Razorpay-Signature: <hex>
Signature (your test secret, runs)Stripe-Signature: t=…,v1=…X-Razorpay-Signature: <hex>
Event headerX-MockCard-EventX-Razorpay-Event-Type

Razorpay error codes

Scenariocodereasonsourcestep
insufficient_fundsBAD_REQUEST_ERRORinsufficient_balancecustomerpayment_authorization
do_not_honorBAD_REQUEST_ERRORcard_declinedcustomerpayment_authorization
expired_cardBAD_REQUEST_ERRORcard_expiredcustomerpayment_initiation
incorrect_cvvBAD_REQUEST_ERRORincorrect_cvccustomerpayment_initiation
network_timeoutGATEWAY_ERRORgateway_timeoutinternalpayment_authorization
3ds_abandonedBAD_REQUEST_ERRORauthentication_failedcustomerpayment_authentication

Verifying Razorpay signatures

Razorpay signatures are plain HMAC-SHA256 hex with no sha256= prefix, in X-Razorpay-Signature.

import { createHmac } from "crypto";

// Razorpay uses plain HMAC-SHA256 hex — no "sha256=" prefix
function verifyRazorpayWebhook(
  rawBody: string,   // req.body as raw string (express.text() middleware)
  signature: string, // X-Razorpay-Signature header
  secret: string     // your WEBHOOK_SECRET env var
): boolean {
  const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
  return expected === signature;
}

app.post("/webhook", express.text({ type: "*/*" }), (req, res) => {
  const sig = req.headers["x-razorpay-signature"] as string;
  if (!verifyRazorpayWebhook(req.body, sig, process.env.WEBHOOK_SECRET!)) {
    return res.status(400).send("Invalid signature");
  }
  const event = JSON.parse(req.body);
  const payment = event.payload.payment.entity;

  if (event.event === "payment.captured") {
    // fulfil order — payment.id is your transaction reference
    await db.orders.fulfill(payment.id);
  }
  res.status(200).send("ok");
});

Webhook events & signing

With a webhook_url on a paid plan, the event is POSTed in the background after the API responds, so it never slows your request down. In runs, MockCard plans the same events and either the SDK (pull) or MockCard (push) delivers them.

Event types

ScenarioEvent typePaymentIntent statusNotes
successpayment_intent.succeededsucceededpayment_method_details.card has brand and last4
insufficient_fundspayment_intent.payment_failedrequires_payment_methodlast_payment_error.decline_code = insufficient_funds
do_not_honorpayment_intent.payment_failedrequires_payment_methodlast_payment_error.decline_code = do_not_honor
expired_cardpayment_intent.payment_failedrequires_payment_methodlast_payment_error.decline_code = expired_card
incorrect_cvvpayment_intent.payment_failedrequires_payment_methodlast_payment_error.decline_code = incorrect_cvc
3ds_challengepayment_intent.requires_actionrequires_actionNot a decline: next_action.redirect_to_url present, last_payment_error null
3ds_abandonedpayment_intent.canceledcanceledRelease the order and any reserved stock
network_timeoutpayment_intent.payment_failedrequires_payment_methodlast_payment_error.code = gateway_timeout, type = api_error

Events from the same payment share one payment id. In a 3ds_challenge run, for example, the requires_action and the succeeded events carry the same pi_mock_…, so your handler can match them up.

Sample payloads: Stripe

// Headers
// X-MockCard-Event:     payment_intent.succeeded
// X-MockCard-Signature: sha256=a3f9c12b8e1d…

{
  "id": "evt_mock_a3f9c12b8e1d",
  "type": "payment_intent.succeeded",
  "created": 1741843200,
  "data": {
    "object": {
      "id": "pi_mock_7b2e4d9a1c3f",
      "object": "payment_intent",
      "amount": 1000,
      "currency": "inr",
      "status": "succeeded",
      "payment_method_details": {
        "card": {
          "brand": "visa",
          "last4": "1486",
          "exp_month": "07",
          "exp_year": "2028"
        }
      },
      "last_payment_error": null,
      "next_action": null
    }
  }
}

Sample payloads: Razorpay

All decline scenarios share one shape; only error_reason differs.

// Headers
// X-Razorpay-Event-Type: payment.captured
// X-Razorpay-Signature:  a3f9c12b8e1d… (plain HMAC-SHA256 hex — no "sha256=" prefix)

{
  "entity": "event",
  "account_id": "acc_mock_f9e8d7c6b5a4",
  "event": "payment.captured",
  "contains": ["payment"],
  "payload": {
    "payment": {
      "entity": {
        "id": "pay_mock_7b2e4d9a1c3f",
        "entity": "payment",
        "amount": 1000,
        "currency": "INR",
        "status": "captured",
        "method": "card",
        "card": {
          "id": "card_mock_x1y2z3a4b5c6",
          "entity": "card",
          "name": "PRIYA PATEL",
          "network": "Visa",
          "last4": "1486",
          "expiry_month": "07",
          "expiry_year": "2028"
        }
      }
    }
  },
  "created_at": 1741843200
}

Which signature you receive

WhenStripe formatRazorpay formatVerify with
Generate with webhook_url; runs for a project without a signing secretX-MockCard-Signature: sha256=<hex>
X-MockCard-Event: <type>
X-Razorpay-Signature: <hex>
X-Razorpay-Event-Type: <type>
MockCard's webhook secret (below)
Runs and monitors for a project with your test-mode signing secretStripe-Signature: t=<unix>,v1=<hex>X-Razorpay-Signature: <hex>
X-Razorpay-Event-Type: <type>
Your unchanged Stripe or Razorpay library and test secret
Production probesMockCard-Probe: 1
MockCard-Signature: t=<unix>,v1=<hex>
SameThe project's probe secret (Production probes)

The recommended setup is to store your gateway's test-mode webhook secret on the project (Projects). Then your real verification code runs unchanged during chaos runs, and a broken signature check shows up as a failed run.

Verifying MockCard's own signature

Compute HMAC-SHA256 over the raw request body bytes with the MockCard webhook secret and compare it with X-MockCard-Signature, using a constant-time comparison.

import { createHmac } from "crypto";

// Call this BEFORE json.parse() — sign the raw body string, not the object
function verifyWebhook(
  rawBody: string,   // req.body as raw string (use express.text() middleware)
  signature: string, // X-MockCard-Signature header
  secret: string     // your WEBHOOK_SECRET env var
): boolean {
  const expected =
    "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
  return expected === signature;
}

// Express.js example
app.post("/webhook", express.text({ type: "*/*" }), (req, res) => {
  const sig = req.headers["x-mockcard-signature"] as string;
  if (!verifyWebhook(req.body, sig, process.env.WEBHOOK_SECRET!)) {
    return res.status(400).send("Invalid signature");
  }
  const event = JSON.parse(req.body);
  if (event.type === "payment_intent.succeeded") {
    // fulfil order…
  }
  res.status(200).send("ok");
});

Delivery and retries (generate)

AttemptDelayBehaviour
1immediateFirst delivery (5 s timeout)
2+2 sOn any 4xx/5xx, timeout or connection error
3+4 sFinal attempt; the outcome is visible through delivery-status

Deliveries never follow redirects and only go to public addresses. Private and internal hosts are refused. simulate_race: true sends an identical second delivery (same event id) about one second later. Your handler must deduplicate on the event id, for example with a unique constraint.

Chaos runs

A run sends a set of scenarios to your webhook handler and scores how it coped. Pro · Agency

ModeWho deliversUse it for
pullYour SDK or the GitHub Action, inside your CI jobCI. Your app runs on localhost, which MockCard can't reach, so MockCard returns signed deliveries and the SDK sends them, then reports results. The SDK can also check outcomes in your database.
pushMockCardA public staging URL (target_url). MockCard delivers and scores the run itself; poll the run for the result.
probeMockCardProduction. One signed probe that a guarded handler skips (Production probes). Created by monitors and the probe endpoint.
EndpointAccessDescription
POST/api/v1/runsci · accountCreate a run. 201 with deliveries for pull, 202 for push.
POST/api/v1/runs/{runId}/resultsci · accountPull only. Report delivery results and assertions, once per run. Returns the scored run.
GET/api/v1/runs/{runId}ci · accountOne run with score and every check.
GET/api/v1/runs?project_id=&limit=ci · accountRecent runs, newest first (limit 1–100, default 50).

Create a run

FieldTypeDescription
project_idstring, requiredOne of your projects. Its gateway and signing secret shape the events.
modepull | pushDefault pull.
scenariosstring[]Any of success, insufficient_funds, do_not_honor, expired_card, incorrect_cvv, 3ds_challenge, network_timeout, 3ds_abandoned, limbo, latency, duplicate. Default: success, insufficient_funds, 3ds_challenge, 3ds_abandoned, duplicate, latency, limbo.
target_urlstringPush only, required there. A public https:// URL.
time_scale0–1Pull only, default 0.2. Shrinks the waits (latency, 3DS) so CI stays fast. Push always uses real timings.
triggerci | apiShown in run history. The SDKs set ci when the CI environment variable is present.
commit_shastringUp to 64 characters. Shown in run history.
branchstringUp to 200 characters. Shown in run history.
curl -X POST https://www.mockcard.io/api/v1/runs \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $MOCKCARD_CI_KEY" \
  -d '{
    "project_id": "prj_3f9a1c2b7d4e5f60",
    "mode": "pull",
    "scenarios": ["success", "duplicate", "3ds_abandoned", "limbo"],
    "time_scale": 0.2,
    "trigger": "ci",
    "commit_sha": "9c1d2e3",
    "branch": "feature/refactor-webhooks"
  }'
{
  "run": {
    "id": "run_8b2f4c1d9e0a7b36",
    "project_id": "prj_3f9a1c2b7d4e5f60",
    "mode": "pull",
    "status": "running",
    "scenarios": ["success", "duplicate", "3ds_abandoned", "limbo"]
  },
  "deliveries": [
    {
      "id": "dlv_1",
      "scenario": "success",
      "at_ms": 0,
      "group": null,
      "event_type": "payment_intent.succeeded",
      "probe": false,
      "body": "{\"id\":\"evt_mock_…\",\"type\":\"payment_intent.succeeded\",…}",
      "headers": { "Stripe-Signature": "t=1762300800,v1=5f0c…" }
    },
    {
      "id": "dlv_2",
      "scenario": "duplicate",
      "at_ms": 0,
      "group": "duplicate",
      "event_type": "payment_intent.succeeded",
      "probe": false,
      "body": "…",
      "headers": { "Stripe-Signature": "t=1762300800,v1=91ab…" }
    }
  ],
  "expectations": [
    { "scenario": "duplicate", "expectation": "Acknowledge both concurrent copies with 2xx and fulfil exactly once (idempotency)." }
  ]
}

For each delivery, wait until at_ms after the start (deliveries with the same group go at the same moment, concurrently), then POST the exact body string with the given headers plus Content-Type: application/jsonto your handler. Don't re-serialise the body, or the signature won't match. Then report what happened:

curl -X POST https://www.mockcard.io/api/v1/runs/run_8b2f4c1d9e0a7b36/results \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $MOCKCARD_CI_KEY" \
  -d '{
    "deliveries": [
      { "delivery_id": "dlv_1", "status_code": 200, "duration_ms": 41 },
      { "delivery_id": "dlv_2", "status_code": 200, "duration_ms": 37 },
      { "delivery_id": "dlv_3", "status_code": 200, "duration_ms": 52 }
    ],
    "assertions": [
      { "scenario": "duplicate", "name": "order fulfilled once", "passed": false,
        "message": "fulfilled 2 times for one payment" }
    ]
  }'

Scoring

Every delivery is one check: it passes on a 2xx (and, for probes, the acknowledgement header). Every assertion your SDK reports is one more check. All checks weigh the same: the score is the percentage that passed, and the run is passed only when every check passed. A delivery with no reported result counts as failed. A handler can answer 200 to both copies of a duplicate and still fulfil the order twice, which is why the SDK assertions matter.

What each scenario expects

ScenarioA correct handler…
successAcknowledge with 2xx and fulfil the order once.
insufficient_fundsAcknowledge with 2xx and mark the payment failed; never fulfil.
do_not_honorAcknowledge with 2xx and mark the payment failed; never fulfil.
expired_cardAcknowledge with 2xx and mark the payment failed; never fulfil.
incorrect_cvvAcknowledge with 2xx and mark the payment failed; never fulfil.
3ds_challengeAcknowledge both events; keep the order pending on requires_action, fulfil on success.
network_timeoutAcknowledge with 2xx and mark the payment failed so the customer can retry.
3ds_abandonedAcknowledge both events; release the order and stock when the payment is canceled.
limboNo webhook arrives. Never fulfil without confirmation; reconcile with the gateway instead.
latencyAcknowledge the late webhook without creating a second order for the client's retry.
duplicateAcknowledge both concurrent copies with 2xx and fulfil exactly once (idempotency).

Projects

A project is one app, or one client store for agencies. It holds the event format (Stripe or Razorpay), an optional test-mode signing secret, and the probe secret. Runs, monitors and reports belong to a project. Projects come with Pro (3) and Agency (25).

EndpointAccessDescription
GET/api/v1/projectsci · accountList projects.
POST/api/v1/projectsaccountCreate: { name, gateway? }. The probe_secret is in this response only.
GET/api/v1/projects/{projectId}ci · accountOne project. has_signing_secret says whether a secret is stored; the secret itself is never returned.
PATCH/api/v1/projects/{projectId}accountname, gateway, signing_secret (write-only; null removes it).
DELETE/api/v1/projects/{projectId}accountDelete the project with its runs and monitors.
POST/api/v1/projects/{projectId}/probe-secretaccountRotate the probe secret. The new one is shown once; update your production handler before the next probe.

Only ever store a test-mode secret

signing_secret must be your gateway's test-mode webhook secret (Stripe whsec_…from a test-mode endpoint, or a Razorpay test webhook secret), never a live one. Secrets are encrypted at rest (AES-256-GCM) and can't be read back, by you or through the API.

Production probes

Real chaos events would create real orders in production, so MockCard never sends them there. Production monitoring sends one probe: a normal-looking success event with two extra headers.

HeaderValue
MockCard-Probe1
MockCard-Signaturet=<unix seconds>,v1=<hex> where v1 = HMAC-SHA256(probe secret, "<t>.<raw body>")

Your handler checks the signature before anything else, skips all processing, and answers 2xx with MockCard-Probe-Ack: skipped. A probe passes only when that header comes back, which proves the request reached your code and was skipped. Reject signatures older than 5 minutes. A forged probe header can only make your handler skip a request, never process one. Every SDK includes this guard (list); without an SDK it's a few lines:

import { createHmac, timingSafeEqual } from "crypto";

// Returns true for a genuine, recent MockCard production probe.
function isVerifiedProbe(headers: Headers, rawBody: string, secret: string): boolean {
  if (headers.get("mockcard-probe") !== "1" || !secret) return false;
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(headers.get("mockcard-signature") ?? "");
  if (!m) return false;
  const [, t, v1] = m;
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false; // replay window
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  return timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
}

export async function POST(req: Request) {
  const raw = await req.text();
  if (isVerifiedProbe(req.headers, raw, process.env.MOCKCARD_PROBE_SECRET ?? "")) {
    // Skip ALL processing: no DB writes, no emails, no fulfilment.
    return new Response("ok", { status: 200, headers: { "MockCard-Probe-Ack": "skipped" } });
  }
  // …normal Stripe / Razorpay signature check and handling
}
EndpointAccessDescription
POST/api/v1/projects/{projectId}/probeci · accountSend one probe to { url } now. Returns the run and acked: true|false. Counts as one call.

Monitors

A monitor checks one URL on a schedule (every hour, 6 hours or day) and alerts you when it starts failing and when it recovers. Pro · Agency

EnvironmentWhat it sendsBefore it starts
stagingA push run with the monitor's scenarios (default: the standard run set)Domain verified
productionOne signed probe, nothing elseDomain verified and one acknowledged probe (POST …/run)
curl -X POST https://www.mockcard.io/api/v1/monitors \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $MOCKCARD_ACCOUNT_KEY" \
  -d '{
    "project_id": "prj_3f9a1c2b7d4e5f60",
    "url": "https://shop.example.com/api/webhooks/stripe",
    "environment": "production",
    "interval_minutes": 60,
    "alert_email": true,
    "slack_webhook_url": "https://hooks.slack.com/services/…"
  }'

# 201 → { "monitor": { "id": "mon_…", "verified_at": null, … },
#         "verification": {
#           "dns":  { "name": "_mockcard.shop.example.com", "type": "TXT", "value": "mockcard-verify=…" },
#           "file": { "url": "https://shop.example.com/.well-known/mockcard-verify.txt", "content": "…" } } }

Domain verification

MockCard only sends scheduled traffic to hosts you control. Add either the TXT record _mockcard.<host> with value mockcard-verify=<token>, or serve the token as plain text at https://<host>/.well-known/mockcard-verify.txt. Then call verify (or click Verify in the dashboard).

EndpointAccessDescription
GET/api/v1/monitorsci · accountList monitors.
POST/api/v1/monitorsaccountproject_id, url, environment, interval_minutes (60 · 360 · 1440, default 1440), scenarios, alert_email, slack_webhook_url. Returns the verification instructions.
GET/api/v1/monitors/{monitorId}ci · accountOne monitor with its verification instructions and last status.
PATCH/api/v1/monitors/{monitorId}accountChange interval_minutes, scenarios, alert_email, slack_webhook_url or paused.
DELETE/api/v1/monitors/{monitorId}accountDelete the monitor.
POST/api/v1/monitors/{monitorId}/verifyaccountCheck the DNS record or file. Returns { verified, method }.
POST/api/v1/monitors/{monitorId}/runaccountRun now. For production monitors, the first acknowledged probe enables the schedule. Counts as one call.

Alertsgo by email (to the account's address) and to Slack when a monitor goes from passing to failing, and again when it recovers. You don't get one for every failed run. A weekly digest summarises every monitor. Scheduled runs don't use your monthly calls.

Health check & audits

EndpointAccessDescription
POST/api/v1/audit/quickanyoneThe webhook health check: 5 probes at { webhook_url, gateway? }, scored out of 100, with a grade and a shareable share_token. One call. The URL is neither logged nor stored.
POST/api/v1/audit/runPro · AgencyA 12-probe resilience audit. Returns 202 with a run_id; poll the next endpoint.
GET/api/v1/audit/{runId}Pro · AgencyOne audit run with full probe results.
GET/api/v1/audit/historyPro · AgencyYour 20 most recent audits.
GET/api/v1/delivery-status?id={log_id}signed in{ pending: true } until a generate call's webhook delivery finishes, then delivered, status_code and delivered_at.
POST/api/v1/webhook/retrysigned inRe-deliver a stored event payload to a URL, signed with MockCard's key (one attempt).

For continuous testing of a real handler, use runs. Audits test a URL from the outside; runs also check what your app did.

Keys, team & reports

EndpointAccessDescription
GET/api/keysaccountYour keys: id, name, prefix, scope, created and last used. Never the full key.
POST/api/keysaccount{ name?, scope? }, scope ci by default. The full key is in this response only.
DELETE/api/keys/{keyId}accountRevoke a key. Requests using it fail immediately.
GET/api/teamAgency ownerMembers and seats: { used, limit } (5 seats including the owner).
POST/api/teamAgency ownerInvite { email }. They sign in with their own email and share the account's plan, projects and usage.
DELETE/api/team/{email}Agency ownerRemove a teammate and sign them out.
PATCH/api/accountownerbrand_name (1–80 characters) and brand_url (https://) for client reports; null clears them.
GET/api/v1/projects/{projectId}/reportAgencyThe white-label client report for a project, plus a signed share link (/r/…, valid 90 days) your client can open without an account.

Error codes

Every error uses one envelope. code is stable and machine-readable. message is for humans and may change. Some errors add fields (for example plan and limit).

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Monthly limit of 2,000 calls reached. Upgrade at mockcard.io/pricing.",
    "plan": "pro",
    "limit": 2000
  }
}

Simulated gateway outcomes (generate)

These are the scenario you asked for, not failures of the API.

codedecline_codeHTTPScenario
card_declinedinsufficient_funds402insufficient_funds
card_declineddo_not_honor402do_not_honor
expired_cardexpired_card402expired_card
incorrect_cvcincorrect_cvc402incorrect_cvv
authentication_required—4023ds_challenge
payment_intent_authentication_failure—4023ds_abandoned
gateway_timeout—504network_timeout

API errors

HTTPcodeMeaning
400invalid_requestThe body isn't valid JSON.
422invalid_requestA field is missing or invalid; the message names it.
401invalid_api_keyThe X-Api-Key matches no active key (revoked, mistyped).
401auth_requiredThis endpoint needs a key or a signed-in session.
403insufficient_scopeA ci key was used for an account action.
403owner_onlyOnly the account owner can do this (team members can't).
402pro_requiredNeeds Pro or Agency (chaos scenarios, simulate_race, runs, monitors, audits).
402agency_requiredNeeds Agency (client reports, team seats).
404not_foundNo such project, run, monitor or key in your account.
409project_limit_reachedYour plan's project limit is used up.
409monitor_limit_reachedYour plan's monitor limit is used up.
409domain_not_verifiedVerify the monitor's domain first.
409not_a_pull_runResults can only be reported for pull runs.
409run_finishedResults for this run were already recorded.
409too_many_keysRevoke a key before creating another.
409no_seatsAll team seats are in use.
409already_memberThat email is already on the team.
429rate_limit_exceededMonthly calls used up. Includes plan and limit.
429anonymous_limit_reachedThe anonymous allowance is used up. Get a free key.
5xxinternal_errorSomething failed on our side. Safe to retry.

Failure scenarios

Real payment flows break in ways happy-path tests miss. Watch them live in the Chaos Simulator, then put them in CI with a run. Pro · Agency

1 · Duplicate webhook (race condition)

A gateway delivers the same event twice when its first attempt times out, or two workers pick it up at once. Both copies carry the same event id. Without deduplication, the customer is fulfilled or credited twice.

How to triggerWhat to fix
Run scenario duplicate (both copies at the same moment), or generate with simulate_race: true (second copy ~1 s later).Reject an event whose id was already processed, atomically: a UNIQUE constraint on event_id, or Redis SET NX. A check-then-insert without a lock fails the concurrent case.

2 · 3DS abandonment

The customer closes the 3DS window. payment_intent.canceled follows the requires_action event. Your app must release the order and stock instead of leaving them pending.

How to triggerWhat to fix
Scenario 3ds_abandoned. Runs send both events for the same payment.Handle payment_intent.canceled (Stripe) or payment.failed with reason authentication_failed (Razorpay): mark the order cancelled and release stock.

3 · Limbo

The payment is captured, but the webhook never arrives. The order stays pending with no automatic way out.

How to triggerWhat to fix
Scenario limbo: 201 success, and no webhook at all.Never fulfil without confirmation, and run a reconciliation job that asks the gateway about payments stuck pending.

4 · Latency

The payment succeeds immediately, but the webhook arrives 9 s later. Meanwhile your client retried, or your proxy timed out and the gateway resent it. If both paths create an order, the customer pays once and gets two.

How to triggerWhat to fix
Scenario latency. In runs, time_scale shortens the wait in CI.Make order creation idempotent per payment id, and deduplicate on the event id, so a late event is a no-op.