- Published on
Stairno 3. Building Payments and the Production Rehearsal
- Authors

- Name
- seren-wib
Contents
- 0. Introduction
- 1. What gets built, and by what rules
- 2. Build order and the path of one payment
- 3. What I ran into while building
- No interactive transactions
- Webhooks: verify before saving
- Signing download links ourselves
- Telling a decline from an outage
- 4. Why I moved to Git Flow midway
- 5. v0.4.0 and v0.4.1
- 6. A rehearsal-only site
- 7. A 404 on the first button
- 8. Mail pointing at a deleted address, and v0.4.2
- 9. A secret nobody had kept
- 10. Results of the 10 scenarios
- Moving refund requests into the account center
- 11. The last two (21 October)
- 12. Closing step 4 (22 October)
- 13. Reflection
0. Introduction
This is roadmap step 4. I added payments to the shared API, then checked that they really work in production before closing the step. The big picture is in Stairno 0. The whole roadmap. In payments a mistake is a money incident, so rules came before code. And since passing tests guarantee neither production addresses nor notices, I ran a separate rehearsal that plays scenarios in production.
In restaurant terms, the site is the dining room, the API is the kitchen, and the cashier is the payment company. A guest places an order and pays, the kitchen talks only to the cashier, and once the bill is settled it hands out an entry ticket. Register a regular's card once and it is charged every month on its own, and before opening day the staff play guests and run a whole day in advance. The cashier is the payment provider (here Toss Payments and PayPal), the entry ticket is the entitlement, the regular's card is the billing key, the monthly charge is subscription renewal, the interpreter at the cashier is the adapter, and the dress rehearsal is the rehearsal.
From the afternoon to the night of 18 October I built payments in sandbox and shipped v0.4.0 and v0.4.1. In the early hours of 20 October I ran 10 scenarios in production. Right at the start it turned out that sign-in from other sites had been broken since launch day. 8 passed on the first night and the last two the next day, and step 4 closed on 22 October with v0.4.3. No real money moved.
1. What gets built, and by what rules
| Payment provider | Currency | What was built |
|---|---|---|
| Toss Payments | Korean won (KRW) | One-time payments, card registration (billing key), automatic subscription charges, cancellation, webhooks |
| PayPal | US dollars (USD) | One-time payments, refunds, webhooks |
The account center gets card registration, deletion and choosing the default card, order history, cancelling and resuming subscriptions, and downloading purchased programs again. Receipts, failed renewal notices and refund results go out by mail. Switching to real payments is designed to take nothing but swapping the test keys for real keys and adding the business details. That switch is step 9, after business registration. All the rules are in the repo's working rules, and the AI agent follows them too.
- Providers live only behind an adapter. The order code knows only common operations like "approve" and "cancel", not whether it is Toss Payments or PayPal. Tests run on a fake adapter instead of a real provider and can create situations like "decline the next payment" or "pretend the provider is down" at will
- Amounts are an integer plus a currency. 1,000 won is
1000 KRWand 1 dollar is100 USD(cents). No decimal arithmetic, and won and dollars are never added together - There is no code that takes card numbers. The payment provider's screen takes them. We keep only the encrypted billing key, the card issuer and the last four digits
- The server re-checks the amount. If the amount sent by the browser differs from the order amount, it is refused and no approval request goes out
- Webhooks are idempotent. The same notice arriving twice is processed once
- Orders follow a state machine. Only allowed moves happen
- A kill switch turns off payments only. In an outage, sign-in stays up and only payments stop
- No personal data in logs. Order numbers and provider numbers instead of emails, tokens or card data
2. Build order and the path of one payment
One feature per PR, test first, in this order.
| Order | Built | What it does |
|---|---|---|
| 1 | Payment DB design | Tables for products, prices, orders, payments, cards, subscriptions, entitlements, refund requests, webhook records |
| 2 | Adapter, fake adapter, state machine | The frame for talking to providers, and the rules for how an order moves |
| 3 | Product registration command, kill switch | The operator registers products with a command. No admin screen |
| 4 | Site identity, order API | A site says "I am a registered Stairno site" and creates orders |
| 5-7 | Toss Payments approval, webhooks, PayPal | Check and finalize a payment that comes back. PayPal goes to the approval screen, returns and captures |
| 8-10 | Card registration and deletion, account deletion hook, payment methods screen | The registration window issues a billing key, stored encrypted. Deleting an account also deletes the keys stored at the provider |
| 11-13 | Billing key charges, starting a subscription, default card change | Charge the default card right away and open the subscription. Changing the default card had left subscriptions tied to the old one, fixed separately |
| 14-15 | Daily automatic renewal, cancel and resume | Once a day cron charges subscriptions whose period has ended. Cancelling is account center only |
| 16-17 | Entitlement lookup, download link | A site asks "may this person use this product?". The buyer gets a 10-minute download address |
| 18-20 | Refund request and operator refund command, payment mail, order history | The operator checks and refunds by command. Mail goes out once per order and kind |
Here is one purchase of a 1,000 won program. (Labs does not exist yet, so the rehearsal site in section 6 stands in for it.)
- The site sends its site token and the buyer's token together and creates an order. The API reads the price from the DB and makes the order
pending. The site does not set prices, and an unpaid order expires after 30 minutes - The user enters a card and authenticates in the Toss Payments window. No money has moved yet
- The site sends the API "finalize this". The API checks in order whether it is this site's order, whether the payment number was already handled (if so it returns the first result as is), whether the order is still
pending, and whether the amount equals the order's. If not, the order is set tofailedand no approval request goes to Toss Payments - The API asks Toss Payments to approve. The money moves here, and the approved amount is compared once more
- Payment done, order
fulfilledand entitlement created are recorded in one go, and a receipt goes out in the user's language - When the webhook arrives later the payment is already handled, so nothing changes. If the user closed the window after step 2, this webhook does steps 3-5
3. What I ran into while building
No interactive transactions
Normally the payment record, the order status and the entitlement go into one transaction. But the HTTP connection from Cloudflare Workers to Neon treats each request separately, so a transaction spanning several requests cannot be opened. So every state change is written as one SQL statement with the condition "change it only if the order is in one of these states". The allowed-state list is generated from the state machine table. Even if two requests try to change the same order at once, only the one that gets there first succeeds.
Webhooks: verify before saving
Saving "received" first lets a forged notice take a real notice's event number, and when the real one arrives it is discarded as "already received". So the order is verify, save, process. Toss Payments payment notices carry no signature, so on receipt we ask Toss Payments directly about that payment and trust only the status it answers with.
Signing download links ourselves
Files live in R2. Making a 10-minute download address in R2 needs one more key, and I did not want more secrets. So the address is the API's own, and the API signs "this file, until this time". When the user arrives it checks signature and time and streams the file.
Telling a decline from an outage
"Card limit exceeded" is a decline: close the order as failed and tell the user. "The provider's server is not answering" is an outage: leave the order and allow a retry. I checked the error codes in the docs one by one so the adapter tells the two apart by code.
4. Why I moved to Git Flow midway
Up to step 3, a PR that passed CI went straight to main, and main went straight to production. With payments half in, going to production is not the same weight as a changed letter on the sign-in screen. On the evening of 18 October, with over 20 payment PRs in, I moved to Git Flow.
- Everyday work collects in
develop, and going intodevelopdoes not deploy - When one roadmap step ends, a
releasebranch is cut and sent tomain, and that is the single deploy - An urgent production bug is fixed with a hotfix that touches only the production version
- The middle number of the version number is the roadmap step. The first release of step 4 is
v0.4.0
Checks come in layers: only the changed tests per commit, all of CI when pushing to develop, CI required to reach main, tests once more right before deploy, then the rehearsal in production. That last layer is section 6 onward, because the address the payment provider returns to and the webhook can only be truly checked in production.
5. v0.4.0 and v0.4.1
Around 10 pm, with payment mail, order history and the re-download screen in, I shipped v0.4.0. Then I saw that the account center was scattered across profile, devices, connected sites, payment methods, subscriptions, orders, downloads and deletion. I compared the account screens of Google, Microsoft, Apple, GitHub and Kakao and changed it.
- Four blocks on one page: account, payment, my products, security. Clicking the left contents scrolls there and marks the block in view
- Account deletion at the very bottom, hard to press by mistake
- Password change, which was missing. Changing it signs out every other device and sends a "your password was changed" mail
- Country/region and time zone (order dates shown in it), profile photo
Birthday, gender, phone number and address are not collected. Not collecting personal data you have no feature for is data minimization, a principle of the Korean privacy law, and it also leaves less to leak. Just after midnight I shipped v0.4.1, and that is the build. What remained was checking it works in production.
6. A rehearsal-only site
Tests run in a fake payment provider, a fake DB and a fake server. But whether the user who finished paying returns to the real site address, whether webhooks reach the real server and whether mail reaches a real mailbox can only be confirmed in production. So step 4 closes only after the scenarios are run one by one and the acceptance checklist is filled in.
The catch was that creating an order needs a site connected to the API. An order request needs both a site token and the buyer's token, the return address must be that site's https address, and the payment window opens on the site's page. The first site, Labs, is step 5. In step 3 I deferred a similar case with "check it once a site exists", but not this time. If something broke while attaching payments to Labs, I could not tell whether it was a bug in the payment API or in Labs.
So I built a one-page Worker that only rehearses, at experiments/payment-rehearsal in the repo.
- It signs in exactly like a real Stairno site, with OIDC (including PKCE), and receives a site token
- Buttons: sign in, one-time product order (won via Toss Payments, dollars via PayPal), confirm payment, confirm payment with the amount halved, start a subscription, look up orders and entitlements. There is no card number field
- The site password (
client_secret) lives only as this Worker's secret - The API has no rehearsal exceptions or back doors at all. The rehearsal only means something if it takes the same road as a real site. The tool stays in the repo and is rerun on every release that changes the payment path
Setup was: deploy the tool to Cloudflare, register it in the account center as an OIDC site and put the issued name and password into its secrets, register two products (1,000 won and 1 dollar one-time) and a monthly subscription (1,000 won), check the webhook addresses in the Toss Payments and PayPal dashboards, and create a rehearsal account. I also wrote a script that reads the production DB. Roles: I enter cards and passwords and change dashboard settings, and the AI agent presses buttons and checks results (responses, DB records, mail).
Two things snagged. The site password issued at the first registration was printed in the working conversation log as is, so I deleted that registration and registered again, and confirmed that signing in with the deleted password is refused (invalid_client). Also, a DB account made in the Neon console joins the admin group automatically, so "read permission only" had no effect. Instead the script opens its transaction as a read-only transaction, which blocks writes at the source. It prints no emails, tokens or card keys.
7. A 404 on the first button
I pressed sign in in the rehearsal tool and the account center's /sign-in was a 404. That page is where other sites land when they press "Sign in with Stairno". Since launch day on 18 October no site had been able to sign in with Stairno, and nobody knew because no site was attached. It was exactly the check I had deferred to step 5 in step 3.
The cause: the account center prefixes addresses with a language (i18n), and Astro's setting was "prefix every page with a language", which renders a page without one and then turns it into a 404. The OIDC sign-in address is the language-less /sign-in that other sites send without knowing the user's language. Screen tests render a page in isolation, so address handling from the language setting never enters. "/sign-in renders the form" passed, while "this address is alive in the production build" was checked by no one.
In Astro, the only thing that can answer outside the language prefix is an address injected separately by an extension (integration). So I added /sign-in that way and sent the request to the sign-in page in the user's language (/ko/sign-in etc.) with a 302. Addresses that must answer without a language are tested as a list, and I started a real build to check that /sign-in gives a 302 and other addresses still give a 404.
8. Mail pointing at a deleted address, and v0.4.2
Preparing "press the button in the mail sent when a renewal fails", I saw that the button pointed at /billing. That is an address I deleted myself when v0.4.1 in section 5 made the account center one page. While changing the screen layout I had not looked at the links inside mail. I changed it to the payment block of the new structure (/ko/#payment-methods).
I bundled the two fixes onto the production v0.4.1 as hotfix v0.4.2, with none of the other changes piled up in develop. CI, usually a few minutes, took close to 40 minutes that day because GitHub Actions was slow, so push to merge took an hour. v0.4.2 reached production around 1:30 am, and after checking /sign-in I restarted the rehearsal.
9. A secret nobody had kept
The original value of the production server's BETTER_AUTH_SECRET was nowhere. Not in the password manager, not on my computer, and Cloudflare Workers does not show a secret again once it is set. The signing key that signs sign-in tokens (JWKS) is stored encrypted in the DB with this value, so nothing I had could decrypt it.
Before launch the only users were me and a test account, so I replaced the value.
- Save the new value in the password manager first
- Put it into Cloudflare with wrangler (
wrangler secret put) - Delete the signing key encrypted with the old value from the DB
- Fetch the public key address once so a new signing key is created, and check that it decrypts with the new value
Changing this value signs out every login and invalidates every download link already out. With users I would have had to announce it first. A secret written down nowhere is a lost secret, and I moved this procedure into the operations doc.
10. Results of the 10 scenarios
Cards used Toss Payments test cards, and PayPal used a sandbox buyer account.
| Order | Scenario | What was checked | Result |
|---|---|---|---|
| 1 | Toss Payments one-time payment | Order fulfilled, entitlement created, receipt mail | Pass |
| 2 | Amount tampering | Halving the amount is refused (422), order failed, no approval request sent | Pass |
| 3 | Cancel and refund | Order refunded, entitlement revoked, refund mail | Pass |
| 4 | Register and delete a card | Last 4 digits shown, deleting also deletes the provider's billing key | Pass |
| 5 | Start a subscription | Charged the default card at once, active, entitlement end = period end | Pass |
| 6 | Three failed renewals, expiry | Mail on each failure, expired on the fourth attempt | Pass (21 October) |
| 7 | PayPal payment and refund | fulfilled to refunded, webhook signature check passed | Pass |
| 8 | Resend a webhook | Sending the same notice again adds no record and leaves the order (idempotent) | Pass |
| 9 | Turn the kill switch off | Sign-in works and only ordering gives a 503 | Pass |
| 10 | Mail in two languages | Switched the account to English and redid 1 and 3 | Pass (21 October) |
Moving refund requests into the account center
Scenario 3 exposed a gap in the design. The procedure said "request a refund in the account center", but the account center had no refund button. The requirements spec had refund requests come from the site and the account center only show status, so the code matched the spec and the procedure was wrong. I made the rehearsal pass by adding a "request refund" button to the tool.
But from the user's side, whichever site they bought from, requesting in the account center that holds the order history is natural, and building a refund screen on every site is the "same work many times" that Stairno 0 set out to avoid. So I changed the decision on the spot and wrote it into the plan.
- Refund requests are taken on the order detail in the account center. Sending a reason makes a request, and it does not refund immediately
- The operator approves or rejects, and the result goes out by mail. The path for a site to submit a request stays as an entrance
- The refund policy text lives on the selling site, and the account center links to it
- The spec is fixed first, then built, in the next release
11. The last two (21 October)
Scenario 10. I switched the account language to English and redid 1 and 3 with an easy-pay method. The order became fulfilled and an English receipt arrived, and requesting a refund and approving it by operator command gave refunded, entitlement revoked and an English refund mail. Mail language follows the account language at the moment of sending, so the first night's Korean result could not prove the English side.
Scenario 6. The Toss Payments test environment approves every payment whatever the card, so failures had to be made. The official way, a test marker on the request, needs an API change and breaks the "no rehearsal exceptions" rule. So I changed only the rehearsal data in the production DB so the stored billing key and customer number no longer matched, and Toss Payments genuinely refused with "customer information does not match" (NOT_MATCHES_CUSTOMER_KEY). I changed the daily renewal cron to every minute for a while, and since a retry normally waits three days after the last attempt, I set "last attempt date" back three days for each retry. Our side took this as a payment decline, not an outage, and handled it with a failed order and an English mail, and the mail button went to the account center payment section fixed in section 8.
| Attempt | Subscription state | Failure count |
|---|---|---|
| First renewal | past_due | 1 |
| Retry 1 | past_due | 2 |
| Retry 2 | past_due | 3 |
| Retry 3 | expired | 4 |
After expired, the subscription entitlement still looked set to its original expiry (a month later). The rehearsal had moved only the period end and left the entitlement expiry alone, and in reality by the time a renewal fails that time has already passed.
I added a per-minute Cron Triggers entry in the dashboard and waited 15 minutes with nothing happening, and only after losing 30 minutes did I open the logs. When cron runs, the API writes one renewal run line even with nothing to renew, and since adding the per-minute cron there was not a single one. That morning at 9:00 (midnight UTC) there was, so the original cron was fine. The cause: I pressed "Add" in the add window and never pressed "Save". The first run came about 8 minutes after Save. The procedure now says "Save after Add, reload and check that it stayed".
12. Closing step 4 (22 October)
With the rehearsal all passed, cleanup and the release were still left.
- Cleanup. I deleted the check script that read the production DB, the connection file, and the allow rule that ran it without asking, and removed the temporary DB account in the Neon console. The rehearsal tool stays
- Shared docs. The source is the repo's markdown, and Google Docs are aligned once when a step ends. I did not upload anew to keep the links and fixed only the changed places in the same documents. The design spec was three lines, the plan a few table rows and three decisions, the test and deployment doc a whole rehearsal section and all the acceptance checklist results, and the requirements spec was already correct. With a three-day step that was fine, and a longer one needs one more alignment midway
- Refund procedure. Look at open refund requests in the DB, judge by the site's refund policy and approve or reject by operator command. Checking the code, refunding by hand in the payment provider's dashboard makes the webhook set the order to refunded but does not close the open refund request. So the procedure says "do not refund by hand in the dashboard"
- Webhook replay. A webhook that failed while processing stays in the DB as failed and the answer is an error, so the payment provider resends it (Toss Payments up to seven times over 3 days 19 hours). After fixing the cause and deploying, resend from the dashboard and you are done, and scenario 8 already showed it is handled without duplicates
- v0.4.3. It shipped what had piled up in
develop: removing the underline on order-list links, the refund request button in the rehearsal tool, and one flaky test. The test that checks a forged billing key is refused changes the second-to-last character of the ciphertext toA(toBif it is alreadyA), but it decided "is it alreadyA" by looking at the neighboring character. When the character to change is alreadyA, nothing changes, decryption succeeds and the test fails. That is about 1 in 64. I fixed it to look at the very character it changes - Two issues left open. I wrote "Closes #209, closes #211" in the
v0.4.2PR body, yet two GitHub issues stayed open. GitHub closes issues with that keyword only when the PR merges into the default branch. This repo's default branch isdevelopand release PRs go tomain, so the keyword does nothing. I confirmed the fixes in production and closed them by hand
What remains is the refund request in the account center and keep-me-signed-in (both spec first), plus three bugs found in the rehearsal: the hub account menu's "sign in" link points at an address that does not exist, "connected sites" in the account center is still empty after an OIDC sign-in, and a refunded order shows the refund mark twice in the list. Then comes step 5, stairnolabs.com, where the production experiment step 13 deferred from step 3 and the "token refresh fails after account deletion" check also get done. Real payments come after business registration and contracts, and before that I recheck the move to a paid Workers plan and the business details in the terms.
13. Reflection
Passing tests do not make an address alive: the check I put off because there was no site to attach had blocked sign-in for nearly two days, and it only surfaced once a real site was attached in production.