Monetizing TeaQL in Public — Day 2: From Subscriptions to Organization Access
A successful payment needs to change the right Organization's access, exactly once. It must also leave the payer's permissions alone: someone handling Finance should not gain access to developer resources simply because a subscription exists.
On Day 1, we built the IAM foundation. Today we added a separate Billing service using TypeScript, TeaQL, Hono, and SQLite. Its first slice connects a server-authorized checkout to a subscription record and an expiring Organization entitlement.
The results in this entry come from local integration tests. IAM authorization, TeaQL persistence, database constraints, and HTTP routing are real. Paddle transaction creation is replaced by a local test adapter, and webhook fixtures are signed locally. Real Paddle Sandbox credentials and an HTTPS callback are still to be configured. This is an API implementation and test report, not a completed Sandbox checkout or a billing UI launch.
Start with the user journey
Alex owns Acme and selects Plus. Billing asks IAM whether Alex can manage Acme's subscription, then records the selected plan and a fresh checkout correlation key. The server asks Paddle to create a transaction and binds the returned transaction ID to that checkout intent.
Once payment processing is complete, Paddle's transaction.completed event can
activate Acme's entitlement. The handler must verify the signature and match
the transaction to the existing intent. A browser return URL cannot activate it.
Morgan is an Acme Developer and can read the resulting entitlement. Sam handles Finance and can view the subscription, but cannot use the developer entitlement endpoint. Another Organization remains on Free throughout.
We scoped this day to an initial, automatically collected, non-trial subscription. Refunds, renewals, proration, cancellation, usage metering, and quota resets belong to later slices.
Keep IAM and Billing as separate services
IAM continues to own users, Organization membership, roles, and permissions. Billing has its own process and database. Its production adapter asks IAM for the authenticated session and permission decisions over HTTP; it does not read IAM's database or import its domain entities.
Billing uses the existing grants:
| Operation | Allowed IAM roles |
|---|---|
| Create a checkout | Owner, Finance |
| Read subscription details | Owner, Finance |
| Read the developer entitlement | Owner, Admin, Developer |
An explicitly assigned Developer + Finance membership can have both sets of permissions. Paying for a plan does not assign either role.
The local integration tests use the actual IAM service and role rules with a
server-injected test identity adapter. Separate transport tests check the HTTP
session adapter, including its cookie, Origin, and CSRF handling. No browser
x-user-id or role header is accepted as authority.
Model the business operation before writing the handler
The Billing KSML model has eight objects, including two constant catalogs. Its final official evaluation returned 0 errors, 0 warnings, and 0 suggestions before TypeScript generation.
| Object | Responsibility |
|---|---|
| Billing Platform | Service root |
| Plan Tier | Free, Plus, Pro, Max catalog |
| Checkout State | Pending, Ready, Completed catalog |
| Organization Account | Billing's reference to an IAM Organization |
| Checkout Intent | Server-authorized plan, price, correlation key, and transaction binding |
| Subscription Record | Provider subscription/customer references and purchased plan |
| Organization Entitlement | Organization plan and its validity end |
| Webhook Receipt | Event/transaction identity, payload digest, and minimal processing metadata |
The checkout intent is the connection between an authorized user action and an
external payment event. The webhook's custom_data is a correlation hint; it
cannot choose an Organization or a plan on its own.
The model generates typed Q queries, E expressions, and audited mutations. Application code still decides when a payment is acceptable and which changes must commit together.
Reserve checkout before contacting Paddle
Billing first checks billing.subscription.manage for the requested
Organization. It selects a price from server configuration, saves an intent,
and then calls Paddle's Sandbox transaction endpoint outside the database
transaction.
When the provider returns a transaction, Billing binds its ID to the intent and marks the intent Ready. A callback that arrives before binding receives a retryable response; it cannot grant access using the correlation key alone.
One outstanding initial checkout per Organization is allowed. A database unique index backs that rule, alongside service checks. If a provider create request times out, the intent stays Pending and another automatic checkout is refused. That uncertain transaction needs reconciliation before a new checkout is opened. Blindly creating another transaction could create another charge.
Verify and apply a payment as one transaction
The webhook route reads a bounded raw body and verifies Paddle-Signature
before parsing the event. The implementation uses HMAC-SHA256 over
timestamp:rawBody, constant-time comparison, and a five-second timestamp
window, following Paddle's signature verification contract.
For a completed initial transaction, the handler checks the event and transaction IDs, subscription/customer IDs, the checkout correlation and bound transaction, configured price, quantity, currency, billing cycle, and billing period. Unsupported or mismatched payments cannot change the entitlement.
The following query is from the implemented handler:
const intent = await Q.checkoutIntents()
.withCorrelationKeyIs(custom.checkout_key as string)
.limit(1)
.comment('Resolve checkout correlation')
.purpose('Bind signed event to server-created checkout intent')
.executeForOne(context);
We then read the generated E expressions explicitly:
const accountId = String(
E.checkoutIntent(intent).organizationAccountId().eval()
);
All accepted changes happen inside context.transaction(...):
- Create the subscription mirror.
- Create the Organization entitlement and its expiry.
- Mark the checkout intent Completed.
- Record the minimal processed-event receipt.
Each save declares an audit reason. A failure after the first save or after the receipt save rolls the whole operation back, including committed audit output. Both failure points are covered by tests.
Deduplicate purchases as well as event delivery
Event IDs and transaction IDs solve different problems. The same event may be delivered repeatedly; another event ID may also describe the same transaction.
We check both and enforce database uniqueness on each. A repeated event with different body bytes is rejected as a conflict. A second event for an already processed transaction must retain the existing subscription/customer binding. It cannot attach the purchase to another Organization.
The receipt commits with the entitlement. It stores identifiers and a payload digest, rather than the raw payment payload. One test adds an email address and card-like value to a fixture and confirms that neither appears in the Billing database.
Make the entitlement expire
A subscription reference alone should not become permanent paid access. The entitlement stores the end of the signed billing period. The resolver uses the generated E accessors and returns Free when that validity period ends:
const validUntil = row
? E.organizationEntitlement(row).validUntil().eval()
: null;
This also exposed a provider-integration case that needed its own path:
Paddle permits a transaction's billing_period to be null.
When that happens, Billing first checks the existing checkout binding, then
queries the Sandbox subscription
for its current billing period. It requires an active subscription and matching
customer, price, quantity, currency, and collection mode. The query happens
outside the write transaction, with a two-second timeout; the handler rechecks
the checkout binding inside the transaction before granting anything.
An unavailable, inactive, or mismatched subscription grants no access. A later valid retry can complete the operation. Once committed, an exact replay is acknowledged from its receipt without another provider query. Local transport tests exercise these paths; actual Sandbox responses still need verification.
An expired first event cannot grant access, and replaying an already processed event cannot extend the entitlement.
What the local run actually showed
The reproducible demo runs real IAM and Billing databases with a local Paddle
adapter. Its captured output identifies itself as local-signed-fixture and
sets realPaddleSandbox to false.
| Observation | Result |
|---|---|
| Organization before confirmation | Free |
| First accepted completed event | applied; plan becomes Plus |
| Same event delivered again | duplicate; no additional grant |
| Finance reading billing | HTTP 200 |
| Finance reading developer entitlement | HTTP 403 |
| Developer reading subscription details | HTTP 403 |
| Actor requesting another Organization's entitlement | HTTP 403 |
| Other Organization's plan | Remains Free |
The Billing suite passed 26 tests, covering sequential/concurrent duplicate delivery, transaction-level deduplication, invalid signatures, mismatched checkout data, cross-Organization subscription binding, both rollback points, durability through an independent runtime connection, role revocation, checkout concurrency, expiry, missing-period reconciliation and its failure paths, and an actual loopback HTTP health check.
These results cover a single Billing writer per SQLite database. They do not certify multiple writer processes, database row-level security, or a deployed payment system. The entitlement resolver is available for a developer service to consume; metered model processing and numerical plan allowances are not yet wired into it.
What other SaaS builders can reuse
Keep checkout intent, provider subscription, product entitlement, and IAM grants as distinct concepts. Bind an incoming payment to the transaction your server created, commit deduplication with the access change, and make expiry explicit.
Then test the awkward paths: the same webhook arriving concurrently, a new event ID for an old transaction, a Finance actor requesting developer access, an Organization ID being changed in a URL, and a failure halfway through the writes. Those rules are useful beyond TeaQL and beyond any particular payment provider.
The next integration step is the real Sandbox run: configure the price and webhook destination, complete checkout, capture a redacted provider delivery, and repeat the entitlement and isolation checks. We will keep that evidence separate from today's local results.
