New in 2.4: Test runs you can trust See what's new →

A fake payment API for testing checkout: declines, refunds and safe retries

Share

Checkout code is the code you least want to test against real money, and the provider sandboxes are often more than you need. Stripe's test mode wants an account and keys in CI, and it is Stripe-shaped. When what you are testing is your own client (how it shows a declined card, whether a timeout can charge someone twice, what a second refund click does), a small fake payment API with predictable failures is enough.

This post tests a checkout client against https://api.testingapis.com/api/Payments, a free fake payments API with no key, idempotency keys, refunds and a card that is always declined. Every response below was captured on 2 December 2026.

Create a payment

A payment is a POST with an Idempotency-Key header. The key is required: without it the API answers 400.

Terminal
$ curl -i -X POST https://api.testingapis.com/api/Payments \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: 905a85a4-93bd-4290-b385-e35878970a1e" \
    -d '{"userId":101,"orderId":1,"amount":49.99,"currency":"USD","method":"card","cardLast4":"4242"}'
HTTP/1.1 201 Created
content-type: application/json; charset=utf-8

{"message":"Payment created successfully","idempotencyKey":"905a85a4-93bd-4290-b385-e35878970a1e",
 "data":{"id":13,"userId":101,"orderId":1,"amount":49.99,"currency":"USD","method":"card",
  "status":"succeeded","description":"","cardLast4":"4242","createdAt":"2026-12-02T14:24:00Z","refundedAt":null}}
FieldValues
amountGreater than 0
currencyThree letters; usd is stored as USD
methodcard, upi, paypal, bank_transfer
cardLast4Four digits, required when method is card
userId, orderId, descriptionFree to use for your own references

Declined cards and pending transfers

Two test values give you the outcomes a real checkout has to handle. A card ending in 0002 is always declined, and a bank_transfer starts as pending:

Terminal
$ curl -s -X POST https://api.testingapis.com/api/Payments ... -d '{... "cardLast4":"0002"}'
HTTP/1.1 201 Created

{"message":"Payment declined", "data":{"id":14, ..., "status":"failed","cardLast4":"0002"}}

$ curl -s -X POST https://api.testingapis.com/api/Payments ... -d '{... "method":"bank_transfer"}'
HTTP/1.1 201 Created

{"message":"Payment created successfully", "data":{"id":15, ..., "status":"pending","cardLast4":null}}

Note the status code on the decline: 201, not an error. The payment exists, it just failed, so its status is failed. Providers differ here (some answer a decline with a 402 error instead), which is one more reason not to trust the status code alone. A client that only looks at the HTTP status will tell this customer their order went through. Branch on the payment's status field.

Safe retries with an idempotency key

The dangerous moment in checkout is a request that times out. The charge may or may not have happened, and the client can't tell. The fix is to send the same Idempotency-Key again with the same body. Here is what the API does with each variation:

Text
# Same key, same body (keys in a different order): the first response again
HTTP/1.1 201 Created
idempotent-replayed: true

{"message":"Payment created successfully", "data":{"id":13, ...}}

# Same key, amount changed to 59.99
HTTP/1.1 422 Unprocessable Entity

{"status":422,"error":"Unprocessable Entity","message":"This Idempotency-Key was already used with a different request body."}

# No key at all
HTTP/1.1 400 Bad Request

{"status":400,"error":"Bad Request","message":"Missing Idempotency-Key header. Send a unique value (e.g. a UUID) per logical payment."}
RequestResponse
Same key, same bodyThe stored response, with Idempotent-Replayed: true. Key order and whitespace don't matter
Same key, different body422, and nothing is charged
Same key while the first request is still running409; wait and try again
Request that fails validation400, and the key is not stored, so you can fix the body and reuse it
Keys are kept for24 hours

The rules for building a server like this, and the bug where a quoted key slips past duplicate detection, are in the post on the Idempotency-Key draft. This post is about the client side: when to make a new key and when to reuse one.

Refunds and their conflicts

POST /api/Payments/{id}/refund refunds the full amount of a succeeded payment. Everything else is a 409 or a 404:

Terminal
$ curl -s -X POST https://api.testingapis.com/api/Payments/13/refund
{"message":"Payment refunded successfully","data":{"id":13, ..., "status":"refunded","refundedAt":"2026-12-02T14:24:11Z"}}

$ curl -s -X POST https://api.testingapis.com/api/Payments/13/refund
{"status":409,"error":"Conflict","message":"Payment 13 was already refunded at 2026-12-02T14:24:11Z."}

$ curl -s -X POST https://api.testingapis.com/api/Payments/14/refund
{"status":409,"error":"Conflict","message":"Only succeeded payments can be refunded (payment 14 is 'failed')."}

$ curl -s -X POST https://api.testingapis.com/api/Payments/15/refund
{"status":409,"error":"Conflict","message":"Only succeeded payments can be refunded (payment 15 is 'pending')."}

$ curl -s -X POST https://api.testingapis.com/api/Payments/9999/refund
{"status":404,"error":"Not Found","message":"Payment with ID 9999 does not exist."}

The refund endpoint takes no idempotency key, and it refunds in full: a body such as {"amount":10}is ignored. A double click on "Refund", or a retry after a timeout, gets 409 already refunded. For the customer that is a success, and the client below treats it as one. The other 409s are real errors: you can't refund a payment that failed or hasn't settled.

A checkout client worth testing

The client keeps one rule: a key belongs to one checkout attempt. Retries of that attempt reuse it; a new attempt (the customer changes the cart and clicks Pay again) gets a new one. It maps the payment status to something the UI can show, and treats a repeated refund as done.

checkout.js
const API = process.env.PAYMENTS_API ?? "https://api.testingapis.com/api/Payments";

// One key per checkout attempt the customer makes. Retries of that attempt reuse it.
export function newCheckout(cart) {
  return { key: crypto.randomUUID(), cart };
}

// Pays for a checkout. Network errors and 5xx are retried with the same key,
// so a timeout can never charge the customer twice.
export async function pay({ key, cart }, { attempts = 3 } = {}) {
  for (let attempt = 1; ; attempt++) {
    try {
      const res = await fetch(API, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Idempotency-Key": key },
        body: JSON.stringify(cart),
        signal: AbortSignal.timeout(8_000),
      });
      const body = await res.json();
      if (res.status === 201) {
        const p = body.data;
        const outcome = { succeeded: "paid", failed: "declined", pending: "awaiting_transfer" }[p.status];
        return { outcome, payment: p, replayed: res.headers.get("idempotent-replayed") === "true" };
      }
      if (res.status === 409 && attempt < attempts) { await sleep(500); continue; } // first request still running
      if (res.status >= 500 && attempt < attempts) { await sleep(500 * attempt); continue; }
      return { outcome: "error", status: res.status, message: body.message };
    } catch (err) {
      if (attempt >= attempts) throw err;
      await sleep(500 * attempt);
    }
  }
}

// A refund that already happened counts as done, so retrying a refund is safe too.
export async function refund(id) {
  const res = await fetch(`${API}/${id}/refund`, { method: "POST" });
  const body = await res.json();
  if (res.ok) return { outcome: "refunded", payment: body.data };
  if (res.status === 409 && /already refunded/.test(body.message)) return { outcome: "refunded", already: true };
  return { outcome: "error", status: res.status, message: body.message };
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

The test suite

Each test creates its own payments, so it doesn't depend on ids that other people's tests also use. No mock server, no keys, nothing to clean up:

checkout.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { newCheckout, pay, refund } from "./checkout.js";

const cart = (extra = {}) => ({ userId: 101, orderId: 1, amount: 49.99, currency: "USD", method: "card", cardLast4: "4242", ...extra });

test("a good card is paid", async () => {
  const r = await pay(newCheckout(cart()));
  assert.equal(r.outcome, "paid");
  assert.equal(r.payment.amount, 49.99);
});

test("a declined card is an outcome, not an exception", async () => {
  const r = await pay(newCheckout(cart({ cardLast4: "0002" })));
  assert.equal(r.outcome, "declined");
  assert.equal(r.payment.status, "failed");
});

test("a bank transfer waits for the money", async () => {
  const { cardLast4, ...rest } = cart();
  const r = await pay(newCheckout({ ...rest, method: "bank_transfer" }));
  assert.equal(r.outcome, "awaiting_transfer");
});

test("retrying a checkout charges once", async () => {
  const checkout = newCheckout(cart());
  const first = await pay(checkout);
  const retry = await pay(checkout); // e.g. the first response timed out
  assert.equal(retry.payment.id, first.payment.id);
  assert.equal(retry.replayed, true);
});

test("a new key for the same cart is a second charge", async () => {
  const a = await pay(newCheckout(cart()));
  const b = await pay(newCheckout(cart()));
  assert.notEqual(a.payment.id, b.payment.id); // this is the double charge to avoid
});

test("changing the cart under the same key is refused", async () => {
  const checkout = newCheckout(cart());
  await pay(checkout);
  const r = await pay({ ...checkout, cart: cart({ amount: 59.99 }) });
  assert.deepEqual([r.outcome, r.status], ["error", 422]);
});

test("refunding twice is still one refund", async () => {
  const { payment } = await pay(newCheckout(cart()));
  const first = await refund(payment.id);
  const second = await refund(payment.id);
  assert.equal(first.outcome, "refunded");
  assert.equal(first.payment.status, "refunded");
  assert.deepEqual(second, { outcome: "refunded", already: true });
});

test("a declined payment can't be refunded", async () => {
  const { payment } = await pay(newCheckout(cart({ cardLast4: "0002" })));
  const r = await refund(payment.id);
  assert.equal(r.status, 409);
  assert.match(r.message, /is 'failed'/);
});

test("bad input comes back as a message you can show", async () => {
  const r = await pay(newCheckout(cart({ cardLast4: undefined })));
  assert.deepEqual(r, { outcome: "error", status: 400, message: "cardLast4 (4 digits) is required for card payments." });
});
Text
$ node --test checkout.test.js
✔ a good card is paid (580.7021ms)
✔ a declined card is an outcome, not an exception (573.7128ms)
✔ a bank transfer waits for the money (287.4647ms)
✔ retrying a checkout charges once (565.7715ms)
✔ a new key for the same cart is a second charge (545.1856ms)
✔ changing the cart under the same key is refused (538.2432ms)
✔ refunding twice is still one refund (854.8589ms)
✔ a declined payment can't be refunded (523.7535ms)
✔ bad input comes back as a message you can show (279.3895ms)
ℹ tests 9
ℹ pass 9
ℹ fail 0

What each test protects

TestThe bug it catches
Declined cardTreating a 201 as success and shipping an unpaid order
Bank transferShowing "paid" for money that hasn't arrived
Retry charges onceA new key on every retry, so a timeout becomes two charges
New key, second chargeDocuments why the key must survive a retry: it proves the API would charge twice
Changed cart, same keyReusing a key after the cart changed, so the customer pays the old total
Refund twiceShowing an error for a refund that worked
Refund a declineOffering a refund button for a payment that never took money
Bad inputSwallowing the API's message and showing "Something went wrong"

The same retry in Python

Standard library only. The second call simulates a retry after a lost response:

pay.py
import json
import urllib.error
import urllib.request
import uuid

API = "https://api.testingapis.com/api/Payments"


def pay(cart, key):
    req = urllib.request.Request(
        API,
        data=json.dumps(cart).encode(),
        headers={"Content-Type": "application/json", "Idempotency-Key": key},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=8) as r:
            return r.status, r.headers.get("Idempotent-Replayed"), json.load(r)
    except urllib.error.HTTPError as e:
        return e.code, None, json.load(e)


cart = {"userId": 101, "orderId": 1, "amount": 49.99, "currency": "USD",
        "method": "card", "cardLast4": "4242"}
key = str(uuid.uuid4())

status, replayed, body = pay(cart, key)
print(status, replayed, body["data"]["id"], body["data"]["status"])

# The response was lost? Send the same request again with the same key.
status, replayed, body = pay(cart, key)
print(status, replayed, body["data"]["id"], body["data"]["status"])

# Same key, different amount: refused, nothing charged.
status, replayed, body = pay({**cart, "amount": 59.99}, key)
print(status, body["message"])
Text
$ python pay.py
201 None 27 succeeded
201 true 27 succeeded
422 This Idempotency-Key was already used with a different request body.

With requests or httpx, generate the key once outside your retry loop or retry decorator. A key generated inside the function being retried is a new key every time, which is the double charge again.

Payment lists for order history and reconciliation

GET /api/Payments filters on any field, searches with ?q=, sorts with ?sort=amount&order=desc and pages with ?limit=. Totals are in headers, so you can test a paged table or a nightly reconciliation job:

Terminal
$ curl -s -D - -o /dev/null "https://api.testingapis.com/api/Payments?limit=2"
x-total-count: 12
x-page: 1
x-per-page: 2
x-total-pages: 6

$ curl -s "https://api.testingapis.com/api/Payments?method=upi&limit=1"
[{"id":3,"userId":103,"orderId":3,"amount":1499.00,"currency":"INR","method":"upi","status":"succeeded",
  "description":"Order #3 — coffee mugs","cardLast4":null,"createdAt":"2025-07-03T09:05:00Z","refundedAt":null}]

The 12 seed payments cover card, UPI, PayPal and bank transfer in USD, EUR and INR, with refunded and failed ones among them: ?status=refunded and ?status=failed give you rows for both. For page-handling patterns, see the pagination guide.

Common checkout testing mistakes

MistakeWhat happensFix
Checking only the HTTP statusDeclines look like successesRead the payment's status
A new idempotency key per HTTP attemptTimeouts turn into double chargesMake the key when the checkout starts; reuse it on retries
Reusing the key after the cart changesAn error here; on a careless server, the old charge replayedNew cart, new key
Retrying 400 and 422The same error, foreverRetry only network errors, 5xx and the in-flight 409
Treating every 409 on refund as failure"Refund failed" for a refund that workedTreat "already refunded" as done
Tests that depend on fixed payment idsThey break when someone else refunds payment 1Create the payments each test needs

Questions

Is there a free fake payment API with no key?

Yes. /api/Payments needs no account or key, answers CORS requests from a browser, and takes no real card numbers: only the last four digits, which decide the outcome.

Which test card is declined?

Any card payment with cardLast4 0002. Every other four digits succeed. For a pending payment, use method: "bank_transfer".

Does a pending bank transfer ever settle?

No. It stays pending, which is what you want for testing a "waiting for payment" screen. Settlement in real providers arrives by webhook; to test that part, see webhook testing, which includes a signed Stripe payment_intent.succeeded sample.

Is the data shared?

Yes. Payments you create are visible to everyone and may be reset, so don't send real customer data, and don't write tests that expect a particular id or total count.

All the endpoints, with parameters and live examples, are in the payments API reference. For generating keys by hand, use the UUID generator.