Skip to main content

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:

  1. tenant_id in the provider metadata. Checkout puts it there, and Polar copies checkout metadata onto the subscription and its orders.
  2. The tenant that already holds that provider subscription id.
  3. 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.createCheckout throws PaidPlansUnavailableException (409). That one gate covers both the Billing page and the expired-trial renewal from the login page.
  • GET /api/public/billing/availability returns {"paidPlansEnabled": false}. The frontend reads it through useBillingAvailability() 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 / monthMinimum (5 employees)15 employees50 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:

  1. Checkout sends seats = max(active employees, minimum) (BillingServiceImpl#createCheckout).
  2. The seat sync (SeatSyncService) compares the billed seats with the employee count and calls PATCH /v1/subscriptions/{id} with the new seats:
    • More employees: applied now, using BILLING_SEAT_INCREASE_PRORATION (default invoice), so new hires are charged for the rest of the period.
    • Fewer employees: scheduled for renewal, using BILLING_SEAT_DECREASE_PRORATION (default next_period). The scheduled count is kept in pending_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.
  3. The webhook (subscription.updated) reports seats and pending_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 | reset but does not document what each one does. Change seats both ways on a sandbox subscription and check the invoices and pending_update before 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.

FailureFrom PolarCustomer seesEmails billing admins
PAYMENT_DECLINED402Orange banner + "Payment issue" header badgeYes
PAYMENT_ACTION_REQUIRED402 PaymentActionRequired (3-D Secure)Same, asks them to confirm the paymentYes
TEMPORARY409 locked, 429, 5xx, networkGrey "we'll retry tonight" noteNo
PROVIDER_CONFIG401/403/404: our token, scope or productGrey "needs a fix on our side" note; ERROR logNo
REJECTED422 / other 4xxSame as aboveNo
  • Emails (SeatBillingNotifier, template mail/seat-payment-failed) go to every active user in the tenant whose roles grant system.admin.billing.manage. There is one when a streak starts, and one final reminder once it passes BILLING_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 → Polar POST /v1/customer-sessions/, token scope customer_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_at is 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.

  1. Polar dashboard → Products → Create product (do this once in sandbox and once in production).
    • Name: Payroll Essentials (then again for People 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 (9900 minor units). Use ₱149 / 14900 for People Suite.
  2. Put the new product UUIDs in POLAR_PRODUCT_ID_STARTER / POLAR_PRODUCT_ID_GROWTH and restart the backend. Archive the old flat products so nobody buys them.
  3. The Organization Access Token needs checkouts:write, subscriptions:write and customer_sessions:write. Without subscriptions:write every seat sync fails with 403 (recorded as PROVIDER_CONFIG). Without customer_sessions:write the "Update payment method" button returns 503.
  4. 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.

ChangeWhenPolar call
Upgrade (right in billing.planOrder)Now. The prorated difference for the rest of the period is invoiced at oncePATCH /v1/subscriptions/{id} {product_id, proration_behavior: "invoice"}
DowngradeAt the next renewal. Nothing is charged or refunded nowsame, with "next_period"; Polar stores it as pending_update
Leaving a flat (pre-seat) priceNow, either directionPolar refuses next_period for non-seat → seat
Keep current planClears the scheduled downgradeDELETE /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). A subscription.updated webhook that describes pending_update overwrites 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, default starter,growth) decides upgrade vs downgrade.
  • A subscription recorded by a provider this server no longer loads (e.g. a stub row after switching to polar) 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.providerAvailable tells 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"; SubscriptionLocked or 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:

  1. A user who signs in with the right password and holds system.admin.billing.manage gets the usual 403 TENANT_TRIAL_EXPIRED, plus canRenew: true and a renewalToken. Everyone else gets canRenew: false and no token. A wrong password gets the plain 401, so the organization's state is never disclosed.
  2. The login page shows that user a plan picker. Choosing a plan calls POST /api/public/billing/renewal-checkout with { 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".
  3. 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.
  • TrialRenewalService re-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:

StateWhen
SUSPENDEDTenant is SUSPENDED or ARCHIVED (wins over everything)
PAIDVerified Active subscription (also wins over a tenant row still saying TRIAL)
PAST_DUEProvider failed to collect. Kept separate from "expiring soon".
EXPIREDRevoked, a Canceled period that has ended, or a closed trial window
EXPIRING_SOONA trial or a cancelling subscription ending within billing.expiringSoonDays (default 7) Manila calendar days
FREE_TRIALA trial with more time than that
MANAGEDACTIVE 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​

ConcernFile
The portbackend/.../service/billing/provider/PaymentProvider.java
Canonical eventbackend/.../service/billing/provider/BillingEvent.java
Polar adapterbackend/.../service/billing/provider/PolarPaymentProvider.java
Signature checkbackend/.../service/billing/provider/PolarWebhookVerifier.java
Polar → canonicalbackend/.../service/billing/provider/PolarEventMapper.java
Idempotency + apply + tenant routingbackend/.../service/impl/BillingServiceImpl.java
Badge statebackend/.../service/billing/SubscriptionStatusService.java
Seat count rulebackend/.../service/billing/BillableSeats.java
Seat sync (+ nightly job)backend/.../service/billing/SeatSyncService.java, config/SeatSyncScheduler.java
Refused-charge emailsbackend/.../service/billing/SeatBillingNotifier.java, resources/mail/seat-payment-failed.*
SchemaV52__billing.sql, V167__subscription_lifecycle.sql, V168__billing_seats.sql, V169__billing_seat_sync_failures.sql
UIfrontend/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​

  1. Sign up at sandbox.polar.sh — a separate account from production.

  2. Create an organization and a recurring, seat-based product (see Setting up the Polar products). Copy the product UUID.

  3. Create an Organization Access Token in the sandbox dashboard. Grant it the checkouts:write, subscriptions:write and customer_sessions:write scopes. Without the first, checkout creation fails with 403 insufficient_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.

  4. Expose your local backend. The Polar CLI can tunnel (polar listen), or use ngrok http 8081 / cloudflared tunnel. Port 8081 is the host-mapped backend from docker-compose.yml; under dev.sh (mvn spring-boot:run) it is 8080 instead.

  5. In the sandbox dashboard, add a webhook endpoint pointing at https://<your-tunnel>/api/webhooks/polar, format Raw, subscribing to subscription.* and order.*. Set a secret (or copy the generated one).

  6. Fill in .env and restart the backend:

    BILLING_PROVIDER=polar
    POLAR_SERVER=sandbox
    POLAR_ACCESS_TOKEN=polar_oat_...
    POLAR_WEBHOOK_SECRET=<the endpoint's secret, verbatim>
    POLAR_PRODUCT_ID_GROWTH=<product uuid>
  7. /billing → pick a plan → pay with test card 4242 4242 4242 4242, any future expiry, any CVC.

  8. You should land on /billing/success, see the delivery in the tunnel/dashboard, and watch GET /api/billing/subscription turn Active.

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):

  1. "Buy now instead" on /pricing links to /signup?plan=<code>&buy=1. A signed-in user goes straight to /billing?checkout=<code>.
  2. 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.
  3. 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 normal POST /api/billing/checkout.

That checkout sets every option Polar's checkout-link form would (PolarPaymentProvider):

  • the single product
  • seats with min_seats = max_seats, which locks the count
  • allow_trial: false, because the app owns the trial
  • require_billing_address (BILLING_REQUIRE_BILLING_ADDRESS, default on)
  • allow_discount_codes (BILLING_ALLOW_DISCOUNT_CODES, default off) and an optional discount_id (POLAR_DISCOUNT_ID)
  • return_url = /billing
  • customer_billing_name = the company name
  • is_business_customer
  • external_customer_id = tenant-<id>, for one Polar customer per company
  • metadata.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)​

  1. Implement PaymentProvider in service/billing/provider/, returning a new name().
  2. Map that provider's events onto BillingEventType in its own mapper. Map anything you don't act on to IGNORED — never throw, or the provider retries forever.
  3. Add its config block to BillingProperties.
  4. 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.