Billing
Subscription billing for a deployment. Polar.sh is the provider today; the module is written
against a PaymentProvider port so Paddle/PayPal/PayMongo can be added as adapters.
Setting it up? Follow billing-setup.md: step-by-step setup, from an offline test to the Polar sandbox to going live, with a check after every step and a troubleshooting table. This page explains how it works.
How it fits together
Browser ──► POST /api/billing/checkout (authed, system.admin.billing.manage)
│
▼
BillingService ──► PaymentProvider (port)
├── PolarPaymentProvider ──► sandbox-api.polar.sh
└── StubPaymentProvider (dev only, no network)
▲
│ canonical BillingEvent
POST /api/webhooks/{provider} (public, signature-verified)
│
▼
billing_subscription ◄── the only writer of paid state
The frontend never decides paid state. /checkout hands back a URL and nothing else. The
subscription only changes when a signed webhook arrives. The post-checkout redirect is a UX
hint — /billing/success polls the backend rather than assuming payment succeeded, because the
webhook can (and does) land after the browser gets back.
Each tenant has at most one subscription row (ux_billing_subscription_tenant, V167). A tenant
with no row has never paid through a provider: it is on a trial, or the platform operator
provisioned it. The webhook is unauthenticated, so it finds the tenant itself, in this order:
tenant_idin the provider metadata. Checkout puts it there, and Polar copies checkout metadata onto the subscription and its orders.- The tenant that already holds that provider subscription id.
- The only tenant, on a single-tenant install.
If none of those match, the event is recorded with processed = false and acknowledged. It is
never guessed, and never left to retry forever.
Payment ends a trial. A verified Active subscription moves the tenant from TRIAL, or from
SUSPENDED with suspension_reason = TRIAL_EXPIRED, to ACTIVE. Without this, a company that
paid would still be locked out when trial_ends_at passed. Payment never lifts an operator's
suspension (ADMINISTRATIVE) or a failed provisioning (PROVISIONING).
All billing dates are Manila wall time. Polar's UTC timestamps are converted on the way in, the
same clock Tenant.businessNow() uses for trials.
Nothing is enforced. A lapsed subscription is shown, not blocked. For a payroll system, a webhook bug or a Polar outage must never lock a client out of their own payroll during a cutoff. Enforcement is a product decision to make deliberately, not a TODO.
Early Access: paid plans switched off
billing.paidPlansEnabled (BILLING_PAID_PLANS_ENABLED) defaults to false. MotorPH
Enterprise is not yet operating under a registered business entity, so it takes no payments.
While the flag is off:
BillingServiceImpl.createCheckoutthrowsPaidPlansUnavailableException(409). That one gate covers both the Billing page and the expired-trial renewal from the login page.GET /api/public/billing/availabilityreturns{"paidPlansEnabled": false}. The frontend reads it throughuseBillingAvailability()to:- label pricing as planned,
- replace the plan buttons on
/billing, - turn the login page's renewal panel into a "free extension on request" link.
- The operator grants the extension with Reactivate on
/admin/tenants. - Webhooks, the customer portal and seat sync are unchanged. With no subscriptions they have nothing to do, and turning the flag on later needs nothing else.
Per-employee pricing
A subscription bills one seat per active employee, never fewer than BILLING_MINIMUM_SEATS
(default 5). An active employee is one that is not archived (is_deleted = false) and not
INACTIVE, the same set a payroll run pays (EmployeeRepository#countBillableByTenantId).
| Plan (code) | Price per employee / month | Minimum (5 employees) | 15 employees | 50 employees |
|---|---|---|---|---|
Payroll Essentials (starter) | ₱99 | ₱495 | ₱1,485 | ₱4,950 |
People Suite (growth) | ₱149 | ₱745 | ₱2,235 | ₱7,450 |
The plan codes predate the names and stay as they are. Env vars, Polar metadata and existing
subscriptions all use them. Display names and prices live in
frontend/src/components/billing/billing-labels.ts (PLANS). The price that is actually
charged is the one on the Polar product, so keep the two equal.
How the seat count follows headcount:
- Checkout sends
seats = max(active employees, minimum)(BillingServiceImpl#createCheckout). - The seat sync (
SeatSyncService) compares the billed seats with the employee count and callsPATCH /v1/subscriptions/{id}with the newseats:- More employees: applied now, using
BILLING_SEAT_INCREASE_PRORATION(defaultinvoice), so new hires are charged for the rest of the period. - Fewer employees: scheduled for renewal, using
BILLING_SEAT_DECREASE_PRORATION(defaultnext_period). The scheduled count is kept inpending_seats, so the next night's sync does not request it again. - The sync runs nightly at 02:45 Manila (
SeatSyncScheduler,BILLING_SEAT_SYNC_ENABLED) and on demand from Billing → Sync now (POST /api/billing/seats/sync). It does not run on every hire, because an import of 80 employees should be one charge, not 80.
- More employees: applied now, using
- The webhook (
subscription.updated) reportsseatsandpending_update.seats. Those overwrite what the sync recorded, so the stored count always ends at what Polar actually did.
A subscription bought on a flat product before this change has seats = NULL. The sync leaves
it alone (NOT_SEAT_BASED), and the Billing page asks the customer to choose a plan again.
Verify the proration modes in the sandbox before going live. Polar's API lists
invoice | prorate | next_period | resetbut does not document what each one does. Change seats both ways on a sandbox subscription and check the invoices andpending_updatebefore trusting the defaults. Set either variable to blank to use the Polar organization's default.
When a seat charge fails
Hiring past the paid seats is never blocked, and neither is payroll. The company is billed after the fact, and a refused charge is recorded, shown, and emailed, never silently retried forever.
Polar's answer is classified (PolarPaymentProvider.classify) into a SeatSyncFailure, stored
on billing_subscription (V169) together with the start of the streak and the seat count we
tried to bill. Seats stay at what was last paid.
| Failure | From Polar | Customer sees | Emails billing admins |
|---|---|---|---|
PAYMENT_DECLINED | 402 | Orange banner + "Payment issue" header badge | Yes |
PAYMENT_ACTION_REQUIRED | 402 PaymentActionRequired (3-D Secure) | Same, asks them to confirm the payment | Yes |
TEMPORARY | 409 locked, 429, 5xx, network | Grey "we'll retry tonight" note | No |
PROVIDER_CONFIG | 401/403/404: our token, scope or product | Grey "needs a fix on our side" note; ERROR log | No |
REJECTED | 422 / other 4xx | Same as above | No |
- Emails (
SeatBillingNotifier, templatemail/seat-payment-failed) go to every active user in the tenant whose roles grantsystem.admin.billing.manage. There is one when a streak starts, and one final reminder once it passesBILLING_SEAT_GRACE_DAYS(default 7), which also logs a WARN for the operator. Nothing further is sent and nothing is blocked. - Fixing it: the banner's Update payment method opens Polar's customer portal
(
POST /api/billing/portal-session→ PolarPOST /v1/customer-sessions/, token scopecustomer_sessions:write). Retry now runs the sync again. - It clears itself when a sync succeeds, when headcount drops back to the paid seats, when the subscription stops renewing, or when a webhook reports at least the seats we tried to bill.
- Late webhooks: a delivery whose subscription
modified_atis older than the one that set the current seat count (seats_reported_at) cannot put the old count back. - Concurrency: the sync locks the subscription row (
findByTenantIdForUpdate), so the nightly run and a click on "Sync now" cannot both PATCH Polar.
To try it locally with the stub, set BILLING_STUB_SEAT_UPDATE_FAILURE=PAYMENT_DECLINED (any
SeatSyncFailure name) and click Sync now with more active employees than paid seats.
Setting up the Polar products
Each plan needs a recurring monthly product with a seat-based price. A flat ("fixed") price
has no seats to resize, and Polar documents the checkout seats field as working with
seat-based pricing only.
- Polar dashboard → Products → Create product (do this once in sandbox and once in production).
- Name:
Payroll Essentials(then again forPeople Suite) - Billing: Recurring, monthly
- Pricing: Seat-based, currency PHP (check that your Polar organization offers it), one tier from 5 seats to unlimited at
₱99 (
9900minor units). Use ₱149 /14900for People Suite.
- Name:
- Put the new product UUIDs in
POLAR_PRODUCT_ID_STARTER/POLAR_PRODUCT_ID_GROWTHand restart the backend. Archive the old flat products so nobody buys them. - The Organization Access Token needs
checkouts:write,subscriptions:writeandcustomer_sessions:write. Withoutsubscriptions:writeevery seat sync fails with 403 (recorded asPROVIDER_CONFIG). Withoutcustomer_sessions:writethe "Update payment method" button returns 503. - Don't create Checkout Links, and don't put a trial on the products. "Buy now" signs up first and opens its own checkout (see "Buy now" from the pricing page).
Or with the API (token needs products:write):
curl -sX POST https://sandbox-api.polar.sh/v1/products/ \
-H "Authorization: Bearer $POLAR_ACCESS_TOKEN" -H 'Content-Type: application/json' \
-d '{"name":"Payroll Essentials","recurring_interval":"month",
"prices":[{"amount_type":"seat_based","price_currency":"php",
"seat_tiers":{"seat_tier_type":"volume",
"tiers":[{"min_seats":5,"max_seats":null,"price_per_seat":9900}]}}]}'
Volume discounts for large companies are extra tiers on the same price (for example 5–100 seats at ₱99 and 101+ at ₱89). Nothing in the app needs to change for that.
Changing plans
What a plan unlocks (modules, add-ons, Early Access, read-only after a downgrade) is in entitlements.md.
An organization with a live subscription (Active or Past Due, with a provider subscription id)
changes plan in place with POST /api/billing/change-plan {planCode}. It never opens a second
checkout; createCheckout now refuses with 409 while a live subscription exists, because a second
checkout would create a second subscription billed alongside the first.
| Change | When | Polar call |
|---|---|---|
Upgrade (right in billing.planOrder) | Now. The prorated difference for the rest of the period is invoiced at once | PATCH /v1/subscriptions/{id} {product_id, proration_behavior: "invoice"} |
| Downgrade | At the next renewal. Nothing is charged or refunded now | same, with "next_period"; Polar stores it as pending_update |
| Leaving a flat (pre-seat) price | Now, either direction | Polar refuses next_period for non-seat → seat |
| Keep current plan | Clears the scheduled downgrade | DELETE /api/billing/pending-change → {"pending_update": null} |
- This matches the seat rules: increases apply now, decreases at renewal.
- The PATCH response is parsed straight away (
PolarEventMapper.planState), so the page updates without waiting for the webhook. That matters locally, where sandbox webhooks can't reach localhost. - A scheduled downgrade is stored in
billing_subscription.pending_plan_code/pending_change_at(V171). Asubscription.updatedwebhook that describespending_updateoverwrites them, so a renewal that applies the downgrade clears them and sets the new plan. - A subscription set to cancel can't change plan (Polar's rule); the page says to resume it in the portal first.
billing.planOrder(BILLING_PLAN_ORDER, defaultstarter,growth) decides upgrade vs downgrade.- A subscription recorded by a provider this server no longer loads (e.g. a
stubrow after switching topolar) is not live. It can't be changed; the 409 says which provider made it. It doesn't block a new checkout either, and the new provider's first webhook replaces the row.SubscriptionDto.providerAvailabletells the Billing page to offer "start a new subscription". - Refusals map to what the admin should do: a declined payment → 409 "update your payment method";
SubscriptionLockedor a provider error → 503 "try again in a minute".
Renewing an expired trial
When a trial ends, everyone in that organization is refused at login, the administrators included. They therefore cannot reach the Billing page to pay. Instead:
- A user who signs in with the right password and holds
system.admin.billing.managegets the usual 403TENANT_TRIAL_EXPIRED, pluscanRenew: trueand arenewalToken. Everyone else getscanRenew: falseand no token. A wrong password gets the plain 401, so the organization's state is never disclosed. - The login page shows that user a plan picker. Choosing a plan calls
POST /api/public/billing/renewal-checkoutwith{ renewalToken, planCode }, which returns the provider's checkout URL. Its success URL is/login?renewed=1, where the login page shows "payment is being confirmed". - The payment webhook carries the tenant id and moves the tenant
SUSPENDED (TRIAL_EXPIRED)→ACTIVE, so everyone can sign in again.
About the token (BillingRenewalTokens):
- It is an HMAC-signed value, valid for 15 minutes, bound to one user and one tenant.
- It is not a JWT and grants no session, so it can never be used as an access token.
TrialRenewalServicere-checks everything when the token is spent: the user still exists, is still active, still belongs to that tenant and still holds the billing permission, and the tenant is still locked out for an ended trial. An operator's suspension can never be paid off.- The endpoint is rate-limited like a login (
LoginRateLimitFilter).
Subscription status badge
GET /api/billing/status feeds the badge in the global header. Every member of a tenant can
read it; platform operators and portal customers cannot. SubscriptionStatusService decides the
state from the tenant row and the subscription row together:
| State | When |
|---|---|
SUSPENDED | Tenant is SUSPENDED or ARCHIVED (wins over everything) |
PAID | Verified Active subscription (also wins over a tenant row still saying TRIAL) |
PAST_DUE | Provider failed to collect. Kept separate from "expiring soon". |
EXPIRED | Revoked, a Canceled period that has ended, or a closed trial window |
EXPIRING_SOON | A trial or a cancelling subscription ending within billing.expiringSoonDays (default 7) Manila calendar days |
FREE_TRIAL | A trial with more time than that |
MANAGED | ACTIVE with no verified subscription: operator-provisioned. Never shown as PAID. |
The billing block (provider, raw provider status, amount) is filled only when the caller's
effective permissions include system.admin.billing.manage; for everyone else it is null.
"Effective" means the role view: the frontend sends X-Active-Role, and the server narrows to the
intersection of the caller's grants and that role's grants. The header can only remove detail.
It is a presentation filter, not a security boundary. The management endpoints
(/subscription, /checkout) still authorize against the user's full grants.
Key files
| Concern | File |
|---|---|
| The port | backend/.../service/billing/provider/PaymentProvider.java |
| Canonical event | backend/.../service/billing/provider/BillingEvent.java |
| Polar adapter | backend/.../service/billing/provider/PolarPaymentProvider.java |
| Signature check | backend/.../service/billing/provider/PolarWebhookVerifier.java |
| Polar → canonical | backend/.../service/billing/provider/PolarEventMapper.java |
| Idempotency + apply + tenant routing | backend/.../service/impl/BillingServiceImpl.java |
| Badge state | backend/.../service/billing/SubscriptionStatusService.java |
| Seat count rule | backend/.../service/billing/BillableSeats.java |
| Seat sync (+ nightly job) | backend/.../service/billing/SeatSyncService.java, config/SeatSyncScheduler.java |
| Refused-charge emails | backend/.../service/billing/SeatBillingNotifier.java, resources/mail/seat-payment-failed.* |
| Schema | V52__billing.sql, V167__subscription_lifecycle.sql, V168__billing_seats.sql, V169__billing_seat_sync_failures.sql |
| UI | frontend/src/pages/billing/, frontend/src/components/billing/SubscriptionBadge.tsx |
Local testing — stub provider (no network)
The default. BILLING_PROVIDER=stub in .env, then:
docker compose up -d --build
Log in as a System Administrator, open http://localhost:5173/billing, pick a plan. The stub
"checkout" returns straight to /billing/success. Drive the webhook by hand:
curl -X POST http://localhost:8081/api/webhooks/stub \
-H 'Content-Type: application/json' \
-d '{"type":"subscription.active","plan_code":"growth","tenant_id":1}'
tenant_id picks the tenant. It can be left out only on a single-tenant install. Two optional
fields drive period-end states: current_period_end (a Manila local date-time such as
2026-12-01T09:00:00) and cancel_at_period_end.
Then confirm the state flipped:
curl -s http://localhost:8081/api/billing/subscription -H "Authorization: Bearer $TOKEN"
Other type values the stub understands: subscription.canceled, subscription.revoked,
subscription.past_due.
Local testing — real Polar sandbox
-
Sign up at sandbox.polar.sh — a separate account from production.
-
Create an organization and a recurring, seat-based product (see Setting up the Polar products). Copy the product UUID.
-
Create an Organization Access Token in the sandbox dashboard. Grant it the
checkouts:write,subscriptions:writeandcustomer_sessions:writescopes. Without the first, checkout creation fails with 403insufficient_scope. Without the others, the seat sync and the payment-portal button fail the same way. Sandbox tokens do not work against production and vice versa. -
Expose your local backend. The Polar CLI can tunnel (
polar listen), or usengrok http 8081/cloudflared tunnel. Port 8081 is the host-mapped backend fromdocker-compose.yml; underdev.sh(mvn spring-boot:run) it is 8080 instead. -
In the sandbox dashboard, add a webhook endpoint pointing at
https://<your-tunnel>/api/webhooks/polar, format Raw, subscribing tosubscription.*andorder.*. Set a secret (or copy the generated one). -
Fill in
.envand restart the backend:BILLING_PROVIDER=polarPOLAR_SERVER=sandboxPOLAR_ACCESS_TOKEN=polar_oat_...POLAR_WEBHOOK_SECRET=<the endpoint's secret, verbatim>POLAR_PRODUCT_ID_GROWTH=<product uuid> -
/billing→ pick a plan → pay with test card4242 4242 4242 4242, any future expiry, any CVC. -
You should land on
/billing/success, see the delivery in the tunnel/dashboard, and watchGET /api/billing/subscriptionturnActive.
If the CLI provisions a fresh secret per session, POLAR_WEBHOOK_SECRET changes and the backend
needs a restart.
"Buy now" from the pricing page
There are no static Polar Checkout Links. Someone paying through one has no workspace yet, so
the webhook carries no tenant_id, and resolveTenant can't attach the payment to a company. It
used to be recorded as unprocessed while the buyer's new workspace ran out its trial.
Instead (frontend/src/lib/purchase-intent.ts):
- "Buy now instead" on
/pricinglinks to/signup?plan=<code>&buy=1. A signed-in user goes straight to/billing?checkout=<code>. - After verification, signup sends the new admin to
/billing?checkout=<code>(signupDestination). It only does that while paid plans are on and the plan is a self-serve one. - The Billing page shows
CompletePurchasePanel(the plan and the monthly cost for the headcount) when there is no live subscription. Continue to payment calls the normalPOST /api/billing/checkout.
That checkout sets every option Polar's checkout-link form would (PolarPaymentProvider):
- the single product
seatswithmin_seats=max_seats, which locks the countallow_trial: false, because the app owns the trialrequire_billing_address(BILLING_REQUIRE_BILLING_ADDRESS, default on)allow_discount_codes(BILLING_ALLOW_DISCOUNT_CODES, default off) and an optionaldiscount_id(POLAR_DISCOUNT_ID)return_url=/billingcustomer_billing_name= the company nameis_business_customerexternal_customer_id=tenant-<id>, for one Polar customer per companymetadata.tenant_id
The old /order-received page redirects to /pricing. The unprocessed-event path in
handleWebhook stays as a safety net for anything that still arrives without a tenant.
The webhook secret gotcha
Polar follows Standard Webhooks, but not in the way a stock Standard Webhooks library expects. The spec treats the secret as base64 and libraries decode it before signing. Polar's SDKs base64-encode the configured secret and pass that to such a library, which decodes it right back — so the real HMAC key is the secret's raw UTF-8 bytes. Polar's docs say the same from the other side: "base64 encode the secret you configured on Polar in your code before generating the signature to validate against."
PolarWebhookVerifier therefore signs with secret.getBytes(UTF_8) directly. Getting this
wrong produces a signature mismatch on every delivery and no other symptom.
PolarWebhookVerifierTest pins both the correct derivation and the naive one, so a "fix" toward
the intuitive reading fails a test instead of failing in production.
Adding another provider (Paddle, PayPal, PayMongo)
- Implement
PaymentProviderinservice/billing/provider/, returning a newname(). - Map that provider's events onto
BillingEventTypein its own mapper. Map anything you don't act on toIGNORED— never throw, or the provider retries forever. - Add its config block to
BillingProperties. - Set
BILLING_PROVIDER=<name>.
BillingServiceImpl, the entity, the schema and the entire frontend stay untouched. If they
don't, the abstraction has sprung a leak worth fixing.
Webhooks resolve their provider from the URL path, so /api/webhooks/polar and
/api/webhooks/paddle can both be live while migrating.
Why the stub is guarded
StubPaymentProvider verifies no signatures, and /api/webhooks/** is public. If the bean
existed in production, anyone could POST a forged activation to /api/webhooks/stub. It carries
@ConditionalOnProperty(billing.provider=stub), so outside dev the bean doesn't exist and the
path 404s. Don't relax that.
Production notes
Each client stack is its own deployment, so each needs its own webhook endpoint registered in
Polar, pointing at https://<slug>.motorphenterprise.com/api/webhooks/polar.
scripts/onboard-client.sh prints this reminder; it is a manual step.
Be aware of where this goes: Polar delivers every event to every endpoint on the organization, so once several client stacks are registered, each receives other clients' events (they're recorded and ignored — an event for another subscription won't match this deployment's state), and the Polar token sits in every stack. That's fine for the first handful of clients and is the thing that eventually argues for a central control-plane service that owns billing and provisioning. The port and canonical event model are what make that a move of a self-contained module rather than a rewrite.