Skip to content

Platform Billing with Stripe

How shops pay Badger Commerce for their own plan. Billing runs on Stripe Billing in the Badger Commerce platform Stripe account, never on a shop's own Stripe account: a shop's customers pay the shop through Stripe Connect as before, and the shop pays Badger for its plan here.

The plans, add-ons, billing accounts and platform subscriptions themselves are described in Subscription Entitlements. This page covers what talks to Stripe: PlatformBillingService (implemented by PlatformBillingServiceImpl), VatRuleService, the billing webhook, the nightly reconcile and the application fee.

Setting it up

Two global settings (System › Global Config, group platform-billing-config):

Setting What it is
platform-billing-stripe-secret-key A secret or restricted key of the platform account (test mode on test environments). Blank: the BADGER_BILLING_STRIPE_SECRET_KEY environment variable
platform-billing-webhook-secret The signing secret (whsec_...) of the billing webhook endpoint. Blank: BADGER_BILLING_STRIPE_WEBHOOK_SECRET

Both are secrets: never shown again once saved, never exported. Without a key, platform billing makes no Stripe calls (the reconcile does nothing, VAT treatments carry no tax rate); without a webhook secret, every delivery to the billing webhook is refused.

In the Stripe dashboard of the platform account, add a webhook endpoint pointing at https://<api host>/v1/webhooks/stripe/billing for these events:

  • checkout.session.completed, checkout.session.expired
  • customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, customer.subscription.paused, customer.subscription.resumed, customer.subscription.trial_will_end
  • invoice.paid, invoice.payment_failed

Plans and add-ons are pushed to Stripe from System (syncPlan / syncAddOn), which fills in their Stripe product and price ids. A price that has never been synced can't be sold: checkout and plan changes refuse it.

Products and prices

Each plan and each add-on is one Stripe product; each of its prices (base, founding, extra location; monthly and yearly) is one Stripe price, created exclusive of VAT (tax_behavior=exclusive), so the published prices are always "+ VAT". Every product and price carries our ids in its metadata.

Stripe prices can't be changed. Syncing a plan therefore:

  • creates a Stripe price for every active price that has none;
  • archives the Stripe price of every price marked inactive;
  • turns a price whose amount, currency or interval was edited into a new price: the old one is put back to what Stripe actually charges, marked inactive and archived, and the new one takes its place (a founding offer is pointed at the new founding price). Shops already on the old price keep it until moved with moveToActivePrice, which switches them at their next renewal with no proration.

Sign-up: Checkout

createCheckoutSession opens a Stripe Checkout session in subscription mode for a sign-up whose email is verified:

Card Always collected (payment_method_collection=always), trial or not, and only a card: Checkout offers no other payment method (Bacs Direct Debit, Klarna), as the card is the anti-abuse check
Items The plan's base price for the chosen interval, or its founding price; each add-on; the extra-location price with its quantity
Trial An explicit trial_end, now plus the plan's trial (days or calendar months). None when the plan has no trial or the billing account has already had one
Founding When asked for, a place is claimed atomically; a full or closed offer falls back to the base price. The place is given back if Stripe refuses the session
Setup fee A one-off line on the first invoice, unless the plan waives it for annual payment or for a founding place
VAT The tax rate from VatRuleService as the subscription's default tax rate (and on the setup fee line)
Collected Billing address (required) and tax ids
Discounts A promotion code carried in the link is applied; otherwise the customer may type one
Metadata signupId, billingAccountId and siteId, on the session and the subscription

completeCheckout reads a session back (the webhook and the return page may both do this, in either order). For a completed session it records the customer's country and tax ids on the billing account and marks the account's trial as used. It doesn't create the shop: sign-up provisioning does that from the outcome, which the webhook also publishes as a PlatformCheckoutCompletedEvent.

When Stripe creates the subscription, the webhook finishes it off: it books the founding price's move to the base price on a subscription schedule (12 months from sign-up, trial included), and sets the VAT rate again from the address and VAT id the customer actually gave.

An invoiced shop moving onto a plan: Checkout without a sign-up

A shop that pays Badger by direct invoice can move onto a self-serve plan, keeping its site, once a superadmin has invited it (System › Billing). createMigrationCheckoutSession opens the session for the existing site:

Card, VAT, collected As for a sign-up: card only, the VatRuleService rate, billing address and tax ids
Items The plan's base price for the chosen interval, nothing else
Setup fee, trial, founding None
Billing start subscription_data.trial_end is the date the shop has paid Badger up to by invoice, so that period isn't charged twice. Checkout wants it at least 48 hours ahead, so a nearer date becomes 49 hours from now; a date passed (or none) charges at Checkout
Discounts None offered
Metadata billingAccountId, siteId and planMigration=true, on the session and the subscription. No signupId

It is refused for a shop that already has a Stripe subscription. The billing account is the one the shop's assigned plan names, else a new one owned by the owner choosing the plan. Before a new session is opened, the one the invite opened last is expired (expireCheckoutSession), so only one can be paid; when that one was already paid, a new one is refused.

completeCheckout reads such a session back as an outcome with migration set and no sign-up id; the trial it starts doesn't use up the account's free trial. The billing webhook hands a migration outcome to PlanMigrationService rather than to provisioning (so a failure answers 500 and Stripe retries), and the owner's return page (/admin/settings/billing/chosen) does the same. The return page reads the session first (readCheckout, which records nothing) and refuses one that isn't this shop's before completing it.

PlanMigrationService applies a session only when the shop has an open invite whose last Checkout is this session. Anything else is a stray: its Stripe subscription is cancelled at once (cancelStraySubscription) and Slack is told to refund any payment (ids only). The attach is atomic: PlatformSubscriptionService.claimStripeSubscription sets the Stripe subscription id only while the shop's record has none (creating a bare record when it has no record, the unique siteId index deciding a race), so of the webhook and the return page one attaches and the other finds it attached, with no second history entry or Slack line. The winner copies plan, price, status and dates from Stripe, sets the source to self-serve and paidUpTo to the trial end, and re-projects the entitlement; if that fails the claim is released so Stripe's retry can try again. No site is provisioned. While the trial end is still paidUpTo, the owner's page shows the shop as paid up rather than on a free trial, no trial banner is shown, and ending the trial early is refused.

VAT, on Stripe's free tax rates

Stripe Tax is not used. VatRuleService picks the treatment and attaches one of three Stripe Tax Rates, created exclusive of VAT the first time each is needed and found again by their metadata:

Customer Treatment Rate
UK, business or not Standard rate "VAT", 20%
Outside the UK, with a VAT or tax id of the right shape for the country Reverse charge; the customer is also marked tax-exempt "reverse" so the invoice says so "VAT (reverse charge)", 0%
EU, no VAT id (or one of the wrong shape) Not offered at sign-up none
Rest of the world, no tax id Outside the scope of UK VAT "VAT (outside the scope)", 0%

A VAT id is checked for its format only (each EU member state's pattern; 4 to 20 letters and digits elsewhere). It is not yet looked up with HMRC or VIES, so a treatment never reports a verified id. Neither the address nor the VAT id is logged.

Managing a plan

Change What happens
Upgrade (same interval, dearer per month) Applied now, prorated and invoiced at once (proration_behavior=always_invoice); the entitlement is rewritten straight away
Downgrade, or monthly to yearly and back Booked for the period end on a subscription schedule, recorded as the subscription's pending change; cancelPendingChange releases it
A plan the shop's add-ons don't fit Refused with the add-ons named, unless the owner agreed to swap them: an add-on is swapped for one the new plan offers with the same capabilities (Premium's capped bookings add-on becomes Pro's unlimited one), or dropped
Anything that lowers a limit Refused while the shop's usage is over the new enforced limits (plus its allowances), with the limits named. The monthly-active-customers limit, a warning only, never refuses anything
Add-on, extra locations Items on the shop's one subscription, prorated and invoiced now; fewer extra locations are refused while that many locations are in use. Refused while a downgrade or interval switch is booked (cancel it first); a founding shop's move to the base price is booked again with the new items
Cancel At the period end, with a reason; resume undoes it until then. A founding shop's move to the base price is booked again on resume
End trial now The trial ends and the first period is invoiced
Card and invoices The Stripe Billing Portal, configured for payment methods and invoice history only, so every plan change goes through the checks above

Leaving a founding price, by any plan change, gives it up. A plan only Badger staff can assign (visibility SALES) can't be chosen; staff assign it in System. Staff can also move the trial end, apply a coupon or promotion code, cancel at once, and re-read a shop's subscription from Stripe.

Every change is made in Stripe first and our record is then copied from Stripe's answer, so a failure in Stripe changes nothing here.

previewPlanChange answers what changePlan would do without doing it: the same checks (limits, add-ons, sale status) and, for an upgrade, the prorated amount Stripe would invoice now, from an upcoming-invoice preview with the new items (subscription_items, subscription_proration_behavior=always_invoice; the proration lines, without VAT). If Stripe can't price it the preview still comes back, unpriced. Shop owners make these changes in Plan & billing, through OwnerBillingService, which offers only the public plans of the shop's family (and self-serve Enterprise), turns refusals into the owner's own messages and records each change in the shop's billing history as an owner.* entry with the acting user's id.

The billing webhook

POST /v1/webhooks/stripe/billing on the API host (see the API reference) is separate from the platform account's shop payment webhook and has its own signing secret. The Stripe-Signature header is checked on the exact raw body before anything else. Each event is recorded once by its Stripe id in billingEvent (ids only, never the payload), so a redelivery changes nothing; a delivery whose handling fails records nothing and answers 500, so Stripe retries it.

Only objects carrying billingAccountId metadata are acted on; anything else is recorded as ignored. The platform account's own hook (/stripeAccountHook) skips the same events, so a shop's plan is never mistaken for one of its payments.

Event Effect
checkout.session.completed / .expired Reads the session back and hands the outcome to sign-up provisioning; an invoiced shop's plan checkout is attached to its existing site instead (see above)
customer.subscription.created Books the founding price's end and sets the VAT rate, then as below
customer.subscription.updated / .deleted / .paused / .resumed Re-reads the subscription from Stripe (never trusting the event's copy, as events can arrive out of order) and saves its status, prices, period, trial and cancellation; the entitlement is rewritten
customer.subscription.trial_will_end As above, plus a "trial ends in 3 days" notice
invoice.paid Re-reads the subscription; the first invoice marks the setup fee paid
invoice.payment_failed Re-reads the subscription, now past due; a "payment failed" notice. Stripe's Smart Retries do the chasing, and a past-due shop keeps everything

Notices (PlatformBillingNotice) are posted to Badger's Slack with shop and subscription ids only.

A shop that stops paying is paused

When a subscription ends (cancelled, or the period ran out after cancelling) or goes unpaid after Stripe's retries, the shop is paused (site status PAUSED):

  • every storefront page shows a closed page ("closed for now", in the shop's language, from Nova's shopClosed template), answered 503 with Retry-After so search engines keep the shop's pages;
  • admin, System, signing in and out, the fulfiller portal and OAuth callbacks stay open, so the owner can pay;
  • Stripe's payment webhooks keep arriving (refunds and disputes on past orders), and the unsubscribe and confirmation links in emails already sent keep working;
  • nothing is deleted, and background work carries on as for any active shop.

Paying again, or Badger staff assigning a plan, makes the subscription entitled again and the shop is unpaused at once. The status always follows the subscription, whichever path saved it. An archived shop is never paused or unpaused; its visitors get the "shop not found" page (see Hosts that aren't a live shop).

Nightly reconcile

The worker (PlatformBillingReconcileJob, 03:40 by default, one worker at a time) repairs what lost webhooks left behind. It lists the subscription events Stripe recorded over the last 26 hours in one paged call and re-reads each platform billing subscription in them, plus any of ours whose trial or period ended over an hour ago without an update. Settings: badger.billing.reconcile-enabled, badger.billing.reconcile-schedule, badger.billing.reconcile-lookback-hours.

Application fee

The fee Badger takes on each paid order (the priceOrder pipeline's basicApplicationFeeCalculator) and each POS sale comes from one place, ApplicationFeeService:

  1. the site's own badgerApplicationFeePercentage / badgerApplicationFeeFixed settings, when set (a part left unset comes from the next step);
  2. otherwise the fees of the shop's platform plan, as written onto its entitlement (the hospitality plans: 0% + 10p; Enterprise: 0% + 5p; the Lite plans their all-in rate);
  3. otherwise, for a shop with no platform subscription, 2.4% + 20p as before.

Badger fee invoices

The application fee is VAT-inclusive, and a VAT-registered shop needs a VAT invoice to reclaim the VAT on it. Badger issues one itself (FeeInvoiceService, package billing.fees), once a month, when one of Badger's own Stripe payouts is paid: Badger's payouts are monthly, and each one pays Badger the fees taken since the last. The shop's own payouts are not involved.

What starts it. payout.paid is now registered on the platform account's webhook as well as the Connect one (StripeWebhookEvents, so add it to the account endpoint in Stripe). The worker's PayoutStatusHandler.Paid tells Badger's own payout from a connected account's (stripeConnect false) and calls FeeInvoiceService.run. FeeInvoiceCatchUpJob (04:10 daily, one worker at a time, badger.fees.invoice-catch-up-*) runs any paid payout of the last 40 days with no completed run: a webhook that never arrived, or a run one shop failed in (status FAILED; the shops already invoiced are skipped the second time). System › Billing › Fee invoices runs one by hand.

What a run does. PlatformFeeReader reads the payout's application_fee and application_fee_refund balance transactions from Stripe (the platform's Connect key, the same account the fees land on), grouped by the connected account each fee came from. It reads the rest of the payout too (PayoutFees.payments, stripeCharges, others): charges and refunds on Badger's own account, each a plan payment when it paid a Stripe Billing invoice, Stripe's charges on them and for its own services, and anything else. The run keeps that as its contents, with unexplained, what the deposit differs by from the sum; System's payout page shows it, and posting to Xero will refuse a payout that doesn't add up. For each account with a site:

  1. The sites on the account each get a line. An account serving one site gets one line for everything; one serving several (DMRT's dmrt and derbymrt-internal) is split by the Site ID each fee's charge carries, with anything unplaceable on the first site. A line also says what its sales came to ("234 sales totalling £3,912.40"): each fee's charge is read in the same Stripe call as the fee (expand data.source.charge), and the line keeps the sum as salesTotal. Refunds don't come off it. A line whose sales aren't all known, or aren't all in the fees' currency, keeps no total and shows the count alone, as do the invoices imported from Xero and any issued before sales totals were kept. Invoices raised in Xero before Badger issued its own keep their Xero numbers (INV-… from the agent, BADGER_DMRT_… and the like raised by hand from October 2018); one raised from a spreadsheet before that has a generated number (HIST-DMRT-001). A payout of a shop that has since gone is kept as a FeeInvoice with status HISTORIC, for the fee trend only.
  2. One invoice, numbered BF-<SITE ID>-<n> (BF-DMRT-1042) from the shop's own badgerFeeInvoice:<siteId> series (IDGeneratorService), which never repeats and tells a shop nothing about how many invoices Badger sends in all, dated the payout's arrival date (the tax point), for the month of the last fee in it. Gross is what Stripe took; VAT is worked out on each fee at the standard rate (the fee's net to the nearest penny, the VAT what is left) and added up, as Xero works it out a line at a time and as the invoices raised there were; with fees of a few pence that comes to pennies less than a sixth of the total. Net is the rest. Every shop is standard-rated for now: the record keeps the figures so reverse charge can be added per shop later. A refunded fee comes off the invoice of the payout it's refunded in; a shop whose fees net to nothing or less isn't invoiced.
  3. Supplier: the platform-legal-name, platform-registered-address, platform-company-number and platform-vat-number global settings (platform-billing-config). Without the VAT number the invoice says it isn't a VAT invoice yet. Customer: the shop's legal-entity-* settings, else its billing account's name and first tax id, else the site name.
  4. The email (Transactional email, template platform/email/fees/invoice), to the shop's fee-invoice-email setting, else its payout-notification-email; with neither the invoice is still issued, just not emailed, and the run says so. The email links to the invoice, a printable page under Plan & billing (/admin/settings/billing/invoices/BF-DMRT-…, template platform/email/invoice/feeInvoice); there is no PDF. Both say where the detail is: Finance › Payouts, where each payout lists its orders with the Badger fee taken from each (PayoutPayment.badgerFee).
  5. A summary to #badger-fees, unless the run had nothing new to say: every shop in the payout was invoiced already (a payout run again, or one whose invoices were imported), or the payout had no Badger fees in it. That run is recorded and logged, with nothing posted.

A shop already invoiced for the payout is skipped (unique index on payout and account), so a run is safe to repeat and a retried webhook can't invoice twice. One shop's failure is recorded on the run (feeInvoiceRuns) and the rest carry on; only Stripe being unreadable fails the webhook. Invoices are kept for good in feeInvoices and listed on the shop's Plan & billing page; System's Fee invoices page shows every payout, run and invoice, and a dry run of any payout.

Xero gets one summary invoice per payout (fees and plan payments by shop, plus a bill for Stripe's charges). Badger's Xero organisation is connected from System's Xero page; until posting is built on it, the run page shows the figures to type in. Plan: docs/implementation-plan/badger-fee-invoices.md.

The fee is only taken where the shop takes payment through a connected Stripe account. A shop on its own Stripe account (the older set-up, and a demo shop on the platform's test keys) has no platform to pay, and Stripe refuses a payment that carries a fee, so the one-page checkout and the card reader leave the fee off the payment and record none on the order.