DEV Community

静亭雅苑
静亭雅苑

Posted on

A Payment Test Mode That Cannot Charge a Real Card

A Payment Test Mode That Cannot Charge a Real Card

The first time I tested a payment flow end to end, I used the production checkout page. It worked. That was the problem: a working test that costs money is not a test, it is a purchase.

The second attempt was the usual patch — one TEST_MODE flag that swapped the checkout URL. It swapped the URL and nothing else. Test payments landed in the production database, test webhooks hit the production signature check, and the notification worker emailed a receipt to a real address.

The fix was not a bigger flag. It was treating "test" as a whole environment that must differ on five independent axes, and making the app refuse to start when they are inconsistent.

Five things that can go wrong, not one

A payment flow touches money, storage, identity, messaging, and external callbacks. Each one needs its own switch, because each one fails differently:

Axis Wrong setting What it looks like
Checkout target production URL real charges, real refunds needed
Database production file test users and fake orders in real analytics and support queues
Webhook acceptance loose in production an unsigned or test-mode callbacks writes state nobody asked for
Outbound notifications real SMTP / chat bot customers receive emails about orders that never existed
Link source HTML hardcoded some entry points still point at production after the "switch"

A single boolean cannot cover these. What can: a startup check that asserts all five agree with the mode, and a local environment where all five are flipped by one command.

Checkout URLs need one owner

My first implementation had the checkout URL in four places: a button in the index page, a pricing page, a JavaScript handler, and an email template. Changing environments meant editing four strings, and forgetting one meant a test run that quietly charged a card.

The version that works keeps one object:

const PAY = {
  prodUrl: 'https://checkout.example.com/store/<store>/product/<prod-product-id>',
  testUrl: 'https://checkout.example.com/store/<store>/checkout/<test-session>?test=true',
  testMode: /^(1|true|on|yes)$/i.test(String(process.env.PAY_TEST_MODE || '')),
};
const CHECKOUT_URL = PAY.testMode ? PAY.testUrl : PAY.prodUrl;
Enter fullscreen mode Exit fullscreen mode

Only CHECKOUT_URL is exported. The API endpoint that returns public config includes it; the front end reads it from that endpoint and rewrites every href that carries a marker attribute:

<a class="buy" data-checkout href="https://checkout.example.com/...">Get the annual pass</a>
Enter fullscreen mode Exit fullscreen mode
const cfg = await fetch('/api/pay/config').then(r => r.json());
document.querySelectorAll('[data-checkout]').forEach(el => {
  el.href = cfg.checkoutUrl;
});
Enter fullscreen mode Exit fullscreen mode

The static href is a fallback for the case where the page is opened from a host with no API at all. On the real site it is always overwritten. That single detail removes an entire class of "I switched the env but one button still charged" bugs: there is nothing to switch, only one value to read.

The test database must be a different file, not a different row

The second leak was storage. My test orders were rows in the production SQLite file, which meant the support queue, the revenue numbers, and the "recent activity" panel all contained fiction.

The rule that fixed it: a test run gets its own database file, created fresh, seeded with a handful of sample records, and never touched by production code paths.

# one command, everything isolated
pnpm test         # port 3998, api/data/app-test.db, seeded, test checkout, no real mail
pnpm test:stop    # shut down and delete the test database
pnpm test:stop -- --keep   # keep the file to inspect the last run
Enter fullscreen mode Exit fullscreen mode

Two properties matter more than the mechanism:

  • Deletion is the default. A test database that survives is a database that eventually gets mistaken for real data.
  • Seeding is deterministic. Twelve sample rows, same IDs every run, so a screenshot from yesterday still matches today's state.

Webhooks: allow test events, keep signatures

The tempting shortcut is to disable signature verification in test mode. That is how a test environment becomes a way to write arbitrary state into a real one, because the same code path usually serves both.

A safer pair of switches:

  1. Accept test-mode events only when the environment is explicitly a test environment. The payment provider flags its own test events; reject anything whose mode does not match the current environment.
  2. Allow unsigned payloads only behind a third flag that is off by default and only ever set by the local test runner. If an attacker finds your test host, the endpoint should still verify signatures.

The invariant to write down: mode of the event must equal mode of the server. Not "test events are accepted", but "test events are accepted by a test server, production events by a production server". A mismatch is a 400, not a silent write.

Nothing should talk to a real human

Notifications are the axis people forget, because they are asynchronous. A test order that triggers an email to a real customer is worse than a test charge: you cannot refund it.

So in the test environment:

  • mail transport is a dry run — messages are rendered and logged, never sent;
  • chat bot and SMS notifications are disabled, not "pointed at a test channel" (that still creates noise and, worse, a habit of ignoring it);
  • the outbox still records every notification, so you can verify the queue, the deduplication key, and the retry counters without delivering anything.

That last point is why an outbox table is worth having before you need a test environment: the thing you want to assert in test is usually "the task was queued exactly once", which is a database question, not a delivery question.

Boot-time assertions instead of discipline

Discipline fails at 2 a.m. Two checks in the startup path catch the expensive mistakes:

if (PAY.testMode && process.env.NODE_ENV === 'production') {
  throw new Error('refusing to start: test payments in production');
}
if (!PAY.testMode && /-test\.db$/.test(DB_PATH)) {
  throw new Error('refusing to start: production mode on a test database');
}
Enter fullscreen mode Exit fullscreen mode

Print the resolved configuration once at boot: mode, checkout host, database path, mail transport, notification channels. One line each. If a run behaves strangely, the answer is in the first ten lines of the log instead of an hour of guessing.

The verification checklist

Before trusting a payment flow, I walk through this:

  1. curl -s localhost:3998/api/pay/config — checkout URL contains test=true.
  2. Every buy button on every page carries data-checkout and no hardcoded production URL survives a grep.
  3. Database path in the boot log ends in -test.db.
  4. A completed test payment appears in the test database only, and production counts are unchanged.
  5. A test-mode webhook is accepted; a production-mode webhook sent to the test server is rejected.
  6. Mail log shows rendered messages, real inbox is empty.
  7. pnpm test:stop removes the database file.
  8. Switching back to production mode changes exactly one environment variable, and the boot log proves it.

None of this requires a staging cluster. It requires deciding that "test" is a configuration of the whole system, not a flag on one function.

The same "one owner per value" reasoning, applied to cache headers that ignored their config, is written up at wuhuajin.com.


Originally published on wuhuajin.com.

Top comments (0)