Monetizing TeaQL in Public — Day 5: Cancel Renewal, Keep Paid Access
A customer asking to stop the next renewal should not lose access they have already paid for. The application also needs to distinguish a confirmed cancellation from a request whose response never arrived.
On Day 4, we added recurring-payment handling. Today we add the complementary backend slice: preview and confirm an end-of-period cancellation for the subscription belonging to one Organization.
This remains local fixture verification, not a real Paddle Sandbox run. The tests use synthetic accounts, actual TeaQL/SQLite, IAM sessions, and injected provider transports. Real Sandbox cancellation, public HTTPS delivery, and the provider dashboard have not been verified. No subscription was canceled in a real Paddle account and no refund was issued.
Start with the customer's decision
Sam manages billing for Acme. Sam asks to stop its next renewal. The application first reads the subscription's current cancellation state and billing-period end from the provider. The confirmation includes that displayed date.
If the date has changed before the command is sent, the service asks for a fresh confirmation. If the provider confirms an end-of-period schedule, the response shows that schedule alongside the existing paid-through date.
A Developer cannot perform the operation. Sam cannot use Acme's billing role to cancel another Organization's subscription. Opening or returning from a page is not evidence that cancellation succeeded.
This entry implements backend APIs and their same-origin proxy route. It does not add a new console button or claim a new browser run.
Separate renewal state from paid access
Paddle's cancel-subscription API accepts an end-of-period cancellation. It creates a scheduled change; the subscription remains active until that change takes effect. Its get-subscription API lets us read the provider state again.
Our outbound cancellation body is fixed by the backend:
{ "effective_from": "next_billing_period" }
The browser cannot select immediate cancellation, a customer ID, or a provider subscription ID. Those fields are rejected if submitted.
The command does not modify the local entitlement, request a refund, or create a payment receipt. Existing paid access remains valid until its paid-through date. If no later confirmed payment extends it, the existing expiry resolver returns Free at that instant. Refund requests remain a separate workflow; this command does not decide their eligibility or amount.
The current scope covers active, automatically collected, non-trial USD subscriptions with a single recurring item. Paused, past-due, manual, and other scheduled-change cases return an unsupported-state result. They need a separate supported workflow rather than a fallback to immediate cancellation.
Use the model to locate the provider resource
The eight-object Billing model is unchanged. A fresh evaluation returned zero errors, warnings, and suggestions, and we obtained current query and expression Assist. No generated library files were edited or regenerated.
After IAM authorizes the Organization operation, a bounded query resolves its saved subscription:
const subscription = await Q.subscriptionRecords()
.filterByOrganizationAccount(String(account.id))
.limit(1)
.comment('Read cancellation subscription binding')
.purpose('Derive provider resources from the authorized Organization')
.executeForOne(context);
The provider identifiers come from that saved record, using complete E expressions:
const subscriptionId = String(
E.subscriptionRecord(subscription).providerSubscriptionKey().eval()
);
const customerId = String(
E.subscriptionRecord(subscription).providerCustomerKey().eval()
);
const priceId = String(
E.subscriptionRecord(subscription).priceKey().eval()
);
The provider response must match all three. Another Organization ID supplied in JSON cannot change that binding. Missing subscriptions fail before any provider call.
The local paid-through date is read independently:
const paidAccessUntil = entitlement
? E.organizationEntitlement(entitlement).validUntil().eval()
: null;
The provider owns the cancellation schedule. The confirmed-payment entitlement continues to own product access. We read the former on demand rather than adding a second, potentially stale cancellation-state cache to this model.
Preview, then confirm the displayed date
The new Organization-scoped endpoint accepts two operations:
| Operation | Permission | Effect |
|---|---|---|
GET /v1/organizations/:organization/cancellation | billing.transactions.read | Read provider state and the current period end |
POST /v1/organizations/:organization/cancellation | billing.subscription.manage | Confirm an end-of-period cancellation |
A confirmation has exactly these fields; the date below is a synthetic fixture:
{
"confirm": true,
"expectedPeriodEnd": "2026-12-28T10:00:00Z"
}
Immediately before the outbound command, the service reads provider state and
compares its period end with the confirmed date. A mismatch returns
CANCELLATION_PREVIEW_CHANGED without issuing the command. An ended period is
also rejected.
The service rechecks IAM permission and the saved binding after provider I/O. A test revokes Finance membership while the provider read is in progress and verifies that the command is not sent. Provider I/O stays outside the database transaction.
The read and subsequent provider command are not an atomic cross-system transaction. We check the returned schedule too; a changed or unconfirmed schedule is not reported as success. The remaining provider-side timing window must be exercised during real integration.
Treat a lost response as uncertainty
A timeout can happen after the provider accepted the cancellation. Reporting failure as if nothing happened is misleading; blindly repeating the command is also unnecessary.
The service returns CANCELLATION_OUTCOME_UNCERTAIN for an unconfirmed command
outcome. It does not retry the POST automatically. The caller can query the
status endpoint again.
One local test deliberately schedules the cancellation and then throws away the
response. The next status read sees the schedule. A subsequent confirmed
request returns already-confirmed without another provider cancel call.
Already canceled subscriptions are handled the same way: report the provider state without issuing another command. Provider read outages fail closed and do not fabricate a successful cancellation. A separate adapter-chain test loses the response at the IAM proxy after Billing processed the command. That proxy failure is also classified as an uncertain cancellation, and readback prevents a second command.
An in-process Organization lock blocks overlapping commands while one is in flight. This is not a durable idempotency ledger or a distributed lock. The existing single-writer deployment boundary still applies. A restart depends on fresh provider readback, not an in-memory claim that the operation succeeded.
Keep the proxy and permission checks independent
The IAM-side proxy now allowlists GET and POST for the scoped cancellation
path. Other methods are rejected. A POST still requires the verified session,
matching Origin, CSRF token, and a bounded JSON body before forwarding.
Billing independently asks IAM to authorize the requested Organization and operation. Tests use real IAM sessions through the same-origin adapter chain to verify Finance access, Developer denial, revoked membership, cross-Organization denial, and CSRF/Origin rejection. The proxy is transport, not a substitute for service authorization.
The provider adapter fixes the Sandbox host, rejects redirects, sets a request deadline, and bounds response bodies. It returns an allowlisted projection, not the entire provider entity. Customer-portal tokens, management URLs, emails, and payment details do not enter the cancellation API response.
Inspect the actual local journey
These dates are fixture values, not a real canceled subscription:
| Step | Provider cancellation state | Local paid access until | Cancel commands |
|---|---|---|---|
| Preview | Not scheduled | December 28, 2026, 10:00 UTC | 0 |
| Confirm | Scheduled for that date | Unchanged | 1 |
| Query again | Scheduled for that date | Unchanged | 1 |
| Confirm again | Already confirmed | Unchanged | 1 |
A separate expiry assertion advances the simulated clock to the paid-through instant and verifies that current access becomes Free. Cancellation itself adds no local entitlement mutation or payment receipt. The canceled-state read does not grant any extra product access.
The local journey retains only the Organization ID, state, dates, outcome, and provider call count. Owned temporary test databases and runtime logs are removed on exit; compact verification evidence remains.
What passed, and what remains
The TypeScript builds passed. The Billing suite now has 70 passing tests: 47 prior regressions plus 23 new cancellation, provider-transport, and same-origin integration tests. The 45 IAM regression tests also passed after the proxy change. No tests failed or were skipped.
We did not change or rerun the frontend suite and did not run a new browser flow. This is an API slice with local simulated provider responses. Real Paddle Sandbox readback, cancellation, and API permissions still require verification.
There is no local durable cancellation-command/audit ledger in this entry, and we have not added cancellation webhooks, a retry worker, a console confirmation screen, refunds, or resume/re-subscribe behavior. Those remain separate work before calling this a complete production billing lifecycle. Real setup now needs subscription read and write permissions in addition to checkout setup.
Other SaaS builders can take away four concrete decisions: derive provider resources from the authorized Organization; confirm the date the user actually saw; keep paid access separate from renewal state; and make uncertain outcomes queryable without an automatic command retry.
