Skip to main content

Billing setup, step by step

This guide connects MotorPH billing to Polar. At the end, customers pay ₱99 or ₱149 per active employee per month. The bill follows their headcount automatically, and a declined card shows up as a warning instead of failing silently.

Each step ends with You should see. Don't move on until it matches. If it doesn't, the troubleshooting table at the end lists every failure we have hit so far.

How it works under the hood is in billing.md. You don't need it to finish this guide.

PartWhat you doTime
1. Try it offlineRun the whole flow with the fake "stub" provider10 min
2. Connect the Polar sandboxReal checkout with test cards, no real money30–45 min
3. "Buy now" on the pricing pageHow visitors buy, and what each Polar checkout option is set to5 min
4. Go liveRepeat Part 2 on production Polar20 min

Where settings go: every value below goes in the .env file at the repository root, not backend/.env.example. After you change it, apply it with:

docker compose up -d backend

This recreates the backend container with the new values. No rebuild is needed.


Part 1 — Try it offline (no Polar account needed)​

This proves the app side works before any Polar setup is involved.

Step 1.1 — Switch to the stub provider​

In .env:

BILLING_PROVIDER=stub
BILLING_PAID_PLANS_ENABLED=true

BILLING_PAID_PLANS_ENABLED is the Early Access switch. While it's false, nothing can be bought and prices show as planned.

Run docker compose up -d backend.

You should see: http://localhost:5173/billing loads when you're logged in as sysadmin_demo. The password is in demo-users.md.

Step 1.2 — "Buy" a plan​

On /billing, click Switch to Payroll Essentials (or People Suite).

You should see: you land straight on the success page. The stub has no payment screen. The plan doesn't turn Active yet, because only a webhook can do that.

Step 1.3 — Send the "payment succeeded" webhook by hand​

This plays the part of Polar telling the app "they paid for 95 employees":

curl -X POST http://localhost:8081/api/webhooks/stub \
-H 'Content-Type: application/json' \
-d '{"type":"subscription.active","plan_code":"starter","tenant_id":1,"seats":95,"amount":9405}'

You should see: after you refresh /billing, the status is Active, Employees billed shows 95, and the header badge says Paid plan.

Step 1.4 — Let the headcount catch up​

The demo company has more than 95 active employees. Click Sync now on /billing.

You should see: a toast saying "Now billing N employee(s)…", and Employees billed matches the active-employee count under it.

Step 1.5 — Rehearse a declined card​

In .env:

BILLING_STUB_SEAT_UPDATE_FAILURE=PAYMENT_DECLINED

Run docker compose up -d backend. Make the paid seats lower than the headcount by sending step 1.3's command again with "seats":90. Then click Sync now.

You should see:

  • An orange banner: "We couldn't collect the charge for N added employees", with Update payment method and Retry now buttons.
  • The header badge turns to Payment issue.
  • One email per System Administrator in Mailpit at http://localhost:8025. Clicking Sync again sends no more.

Step 1.6 — Rehearse the fix​

Set BILLING_STUB_SEAT_UPDATE_FAILURE= back to blank, run docker compose up -d backend, then click Retry now.

You should see: the banner disappears, the badge returns to Paid plan, and Employees billed matches the headcount.

Part 1 is done. The app side works.


Part 2 — Connect the Polar sandbox​

The sandbox is a separate Polar site with its own account, products and tokens. Nothing you do there touches real money or your production setup.

Step 2.1 — Create the sandbox account​

Sign up at https://sandbox.polar.sh and create an organization. Use the business name your customers should see on receipts.

You should see: an empty dashboard for your organization.

Step 2.2 — Create the two products​

Products → New product, twice. The pricing type must be seat-based. A plain fixed price cannot follow headcount.

FieldProduct 1Product 2
NamePayroll EssentialsPeople Suite
BillingRecurring, monthlyRecurring, monthly
Pricing typeSeat-basedSeat-based
CurrencyPHPPHP
Tierfrom 5 seats, no maximumfrom 5 seats, no maximum
Price per seat₱99₱149

Then copy each product's ID (a UUID) from its page. If older flat-price products exist, archive them so nobody can buy them by mistake.

You should see: two products whose price reads per seat, with 5 as the minimum.

If PHP isn't offered as a currency for your organization, stop and contact Polar support. Prices in another currency would not match what the app shows customers.

Step 2.3 — Create the access token​

Settings → Organization Access Tokens → New. Tick these scopes:

ScopeWhat breaks without it
checkouts:write"Switch to …" on /billing fails
subscriptions:writeSeat changes fail (grey "needs a fix on our side" note)
customer_sessions:writeThe Update payment method button fails

Pick a long expiry, or note the date somewhere you will see it. An expired token returns 401 and checkout stops working.

You should see: a token starting with polar_oat_. Copy it now; Polar shows it only once.

Check it works (should print HTTP 200):

curl -s -o /dev/null -w "HTTP %{http_code}\n" \
-H "Authorization: Bearer polar_oat_..." \
"https://sandbox-api.polar.sh/v1/products/?limit=1"

Step 2.4 — Make your local backend reachable from Polar​

Polar has to call your app when someone pays. Your laptop isn't on the internet, so open a tunnel to the backend on port 8081:

cloudflared tunnel --url http://localhost:8081
# or
ngrok http 8081

You should see: a public https://… address. Keep this terminal open. If it closes, webhooks stop arriving and payments never activate.

Step 2.5 — Register the webhook​

In the Polar sandbox: Settings → Webhooks → Add endpoint.

FieldValue
URLhttps://<your-tunnel-address>/api/webhooks/polar
FormatRaw
Eventsevery subscription.* event and every order.* event

Save, then copy the endpoint's secret. It's a random string, not a URL.

You should see: the endpoint listed as enabled.

Step 2.6 — Fill in .env​

BILLING_PROVIDER=polar
POLAR_SERVER=sandbox
POLAR_ACCESS_TOKEN=polar_oat_... # from step 2.3
POLAR_WEBHOOK_SECRET=... # from step 2.5, the secret string, verbatim
POLAR_PRODUCT_ID_STARTER=<Payroll Essentials product id>
POLAR_PRODUCT_ID_GROWTH=<People Suite product id>
BILLING_SUCCESS_URL_BASE=http://localhost:5173
BILLING_PAID_PLANS_ENABLED=true
BILLING_STUB_SEAT_UPDATE_FAILURE=

The optional per-employee knobs already have sensible defaults:

BILLING_MINIMUM_SEATS=5
BILLING_SEAT_SYNC_ENABLED=true
BILLING_SEAT_INCREASE_PRORATION=invoice
BILLING_SEAT_DECREASE_PRORATION=next_period
BILLING_SEAT_GRACE_DAYS=7

Run docker compose up -d backend.

Step 2.7 — First real test purchase​

Log in as sysadmin_demo → /billing → Switch to Payroll Essentials.

You should see: Polar's hosted checkout, pre-filled with the number of active employees as the seat count. Pay with test card 4242 4242 4242 4242, any future expiry date and any CVC.

After paying you return to the success page, which waits for the webhook.

You should see, within a few seconds:

  • /billing shows Active, the right plan, and Employees billed equal to the active employees (minimum 5).
  • Polar → Webhooks → your endpoint → deliveries all return 200.
  • Polar → Subscriptions shows the new subscription with the same seat count.

Step 2.8 — Test a hire (seats go up)​

Add an employee, or reactivate an INACTIVE one. Then click Sync now on /billing.

You should see:

  • The toast "Now billing N employee(s)…".
  • In Polar, the subscription's seats go up by one, with a prorated charge for the rest of the month.

Step 2.9 — Test someone leaving (seats go down at renewal)​

Set an employee to INACTIVE and click Sync now.

You should see:

  • The toast "Billing drops to N employee(s) at your next renewal" and a matching note on /billing.
  • In Polar, the subscription shows a pending change for the next period, not an immediate credit.

Check this step carefully. Polar's documentation doesn't explain exactly what each proration mode does. If seats in step 2.8 weren't charged right away, or step 2.9 credited the customer immediately, change BILLING_SEAT_INCREASE_PRORATION / BILLING_SEAT_DECREASE_PRORATION. The options are invoice, prorate, next_period and reset; leave a value blank to use your Polar organization's default. Restart the backend and repeat the step.

Step 2.10 — Test a declined card​

Click Update payment method on /billing.

You should see: Polar's customer portal for this subscription.

There, replace the card with Stripe's test card that attaches fine but declines every charge: 4000 0000 0000 0341. (Polar runs on Stripe. If the sandbox portal won't accept this card, rely on the rehearsal in step 1.5 instead.) Then add an employee and click Sync now.

You should see:

  • The orange banner and the Payment issue header badge. Hiring and payroll still work.
  • One email to each System Administrator, in Mailpit for local runs.

Fix it: switch the card back to 4242… in the portal, then click Retry now.

You should see: the banner clears, the badge returns to Paid plan, and the seats go up in Polar.

Part 2 is done. Billing works end to end against Polar.


Part 3 — "Buy now" on the pricing page (no Polar setup needed)​

You don't create Polar Checkout Links. A checkout link takes payment from someone who has no workspace yet, so the app can't tell which company paid. The payment would be recorded but never attached, and the customer would hit "trial expired" despite having paid.

Instead, "Buy now" signs the customer up first, and then the app opens a Polar checkout that carries their workspace's id and real employee count.

How it works for the customer​

  1. On /pricing, they click Buy now instead under a plan. Signed-in users see Choose this plan instead.
  2. Signup says "Payroll Essentials: you'll choose how to pay right after your workspace is created."
  3. Once the workspace exists, they land on /billing with a Complete your purchase panel. It shows the plan and the monthly cost for their headcount (a new workspace pays the 5-employee minimum, ₱495 / ₱745).
  4. Continue to payment opens Polar's checkout. After paying they return to the Billing page, which turns Active.

"Buy now" only appears while BILLING_PAID_PLANS_ENABLED=true.

The app sets every option from that form on each checkout it opens, so there's nothing to fill in on Polar's side:

Polar fieldWhat the app setsWhy
Labeln/aNo links
ProductsOnly the chosen plan's productThey picked the plan on the pricing page; switching would confuse the price they just saw
Success URLhttps://<your-domain>/billing/successWaits for Polar's webhook, then shows the active plan
Return URLhttps://<your-domain>/billingThe checkout's back button returns to the plan cards
Preset discountNone, or POLAR_DISCOUNT_IDFor a launch promotion: create the discount in Polar → Discounts, put its id here
Allow discount codesOff (BILLING_ALLOW_DISCOUNT_CODES=false)Turn on only while you're handing out codes
Require billing addressOn (BILLING_REQUIRE_BILLING_ADDRESS=true)Companies need invoices with their registered address
Lock number of seatsLocked to the active-employee count (minimum 5)They pay for the employees they actually have; the nightly sync follows hires and departures afterwards
Free trial periodOffThe app already gave a free trial at signup
Metadatatenant_id, plan_codeHow the webhook knows which company paid

The app also prefills the company name as the billing name, marks the buyer as a business, and ties every checkout to one Polar customer per company (tenant-<id>). A returning company keeps its saved card instead of becoming a duplicate customer.

To change these, set the env vars in .env and run docker compose up -d backend:

BILLING_REQUIRE_BILLING_ADDRESS=true
BILLING_ALLOW_DISCOUNT_CODES=false
POLAR_DISCOUNT_ID=

Check these in the Polar dashboard​

  • The two products have no trial configured.
  • The customer portal is enabled, so the "Update payment method" button works.
  • Order email receipts go to customers.
  • Delete any old Checkout Links you created, so nobody can pay through a link that isn't tied to a workspace.

Try it​

Log out, open /pricing, click Buy now instead under Payroll Essentials, and complete signup. Use Mailpit at http://localhost:8025 for the code.

You should see:

  • The Complete-your-purchase panel showing ₱495 / month for 5 employees.
  • Continue to payment opens Polar's checkout with the seat count fixed at 5, the full billing address required, your company name filled in, no trial, and a back button that returns to /billing.

Part 4 — Go live (real money)​

Production Polar is a completely separate site (polar.sh, not sandbox.polar.sh). Nothing carries over from the sandbox.

  1. Repeat steps 2.1–2.3 on https://polar.sh: organization, the same two products, and a token with the same three scopes.

  2. Repeat step 2.5, with the webhook URL pointing at your real domain: https://<your-domain>/api/webhooks/polar. No tunnel is needed.

  3. Put the production values in the production env. That is the PROD_ENV_FILE GitHub secret, which every deploy writes to /srv/motorph/.env on the server; the template is deploy/.env.prod.example, and the details are in vps-guide.md §7 "Configuration":

    BILLING_PROVIDER=polar
    POLAR_SERVER=production
    POLAR_ACCESS_TOKEN=polar_oat_... # production token
    POLAR_WEBHOOK_SECRET=... # production endpoint secret
    POLAR_PRODUCT_ID_STARTER=... # production product ids (they differ from sandbox)
    POLAR_PRODUCT_ID_GROWTH=...
    POLAR_DISCOUNT_ID= # production discount id, if any (they differ from sandbox)
    BILLING_PAID_PLANS_ENABLED=true # only once you're ready to take payments

    Production derives BILLING_SUCCESS_URL_BASE from DOMAIN automatically.

  4. Never set BILLING_STUB_SEAT_UPDATE_FAILURE in production, and never set BILLING_PROVIDER=stub there.

  5. Deploy, then make one real purchase with your own card and refund it from Polar.

You should see: the same results as step 2.7, on your real domain.

Go-live checklist:

  • Products are seat-based, PHP, 5-seat minimum, ₱99 / ₱149
  • Token has checkouts:write, subscriptions:write, customer_sessions:write, and its expiry date is recorded somewhere
  • Webhook URL uses the production domain, format Raw, all subscription.* and order.* events
  • POLAR_WEBHOOK_SECRET is the secret string, not a URL
  • POLAR_SERVER=production
  • Real test purchase activated and was refunded
  • Steps 2.8–2.9 behaved as expected in the sandbox (proration modes confirmed)
  • Polar → Settings → Notifications emails you on every new order
  • No old Checkout Links left in Polar; products have no trial
  • Your business registration and tax setup are done before BILLING_PAID_PLANS_ENABLED=true

Troubleshooting​

What you seeMost likely causeFix
No "Buy now" on /pricing, prices marked "planned", or checkout says paid plans are unavailableBILLING_PAID_PLANS_ENABLED is false (Early Access)Set it to true and restart the backend
Checkout fails with "Polar checkout request failed"; backend log shows 401Token expired or revokedMake a new token (step 2.3) and update .env
Same, log shows 403 insufficient_scopeToken missing checkouts:writeAdd the scope, or make a new token
Same, log shows 422Product isn't seat-based, or the product ID is from the other environment (sandbox vs production)Recheck step 2.2 and the IDs in .env
Paid in Polar, but /billing stays NoneThe webhook isn't reaching the appPolar → Webhooks → deliveries. No deliveries: the tunnel is down or the URL is wrong. Deliveries returning 400: see the next row
Webhook deliveries return 400Wrong POLAR_WEBHOOK_SECRET: a URL, a different endpoint's secret, or a base64-decoded valueCopy the endpoint's secret again, paste it verbatim, restart. If you use polar listen, it issues a new secret each session
/billing says "This subscription has a flat price"Bought on an old fixed-price productChoose a plan again so it moves onto the seat-based product
Grey note "needs a fix on our side" after Sync nowToken missing subscriptions:write (backend log: PROVIDER_CONFIG)Add the scope (step 2.3)
Grey note "we'll retry automatically tonight"Polar busy or unreachableNothing to do; it retries at 02:45 Manila, or click Sync now later
Update payment method shows "Could not open the payment portal"Token missing customer_sessions:writeAdd the scope (step 2.3)
Orange banner + Payment issue badgeThe customer's card was declinedThat's the customer's step: update the card, then Retry now
Seats never change on their ownBILLING_SEAT_SYNC_ENABLED=false, or nobody has clicked Sync now since the headcount changedThe sync runs nightly at 02:45 Manila; click Sync now to run it immediately
No emails arriveMail isn't configured (MAIL_ENABLED), or no active System Administrator has an email addressSee email.md

Useful commands:

# What the app thinks the subscription is
curl -s http://localhost:8081/api/billing/subscription -H "Authorization: Bearer $TOKEN"

# Billing-related backend log lines
docker compose logs backend | grep -iE "polar|seat|billing"