Gating features with entitlements
An entitlement is a named number: instances, seats, storage_gb. Each product grants some per unit, and a user's
entitlements are the sums over their active items: subscriptions that are paid, trialing, or past due while the
processor retries the card; paid one-time orders (partly refunded ones too); and manual grants that haven't ended. A cancelled subscription keeps counting until its paid period ends; a refunded order
stops counting at once.
Read them
// pb_pages/projects/new.ts
module.exports = {
load(ctx) {
if (!ctx.auth) return ctx.res.redirect('/login')
const { totals } = $billing.entitlements(ctx.auth)
const used = ctx.app.countRecords('projects', $dbx.hashExp({ owner: ctx.auth.id }))
if (used >= (totals.projects ?? 0)) return ctx.res.redirect('/pricing')
return {}
},
}
ent, err := billing.For(app).Entitlements("users", userId)
if err != nil {
return err
}
if ent.Totals["projects"] <= used {
return apis.NewForbiddenError("Upgrade to add more projects", nil)
}
A name the user has none of is missing from totals, so read it with a default (?? 0 in TypeScript; Go's map gives
0). sources lists where each total comes from: one entry per item and entitlement.
From the browser:
const { totals } = await pb.send('/api/_c/billing/v1/entitlements')
List purchases
items lists a user's subscriptions, orders and grants, newest first, with product, quantity, status, active,
renewsAt and endsAt. Use it for an account page:
const items = $billing.items(ctx.auth)
// [{ product: "pro", status: "active", renewsAt: "2027-01-03T...", ... }]
React when something changes
OnItemChanged runs after every change to an item, from a webhook, an action in the dashboard, a grant or the daily
reconcile. It carries the item before and after and the owner's entitlements before and after, so you can provision or
tear down what was paid for:
billingv1.OnItemChanged(app).BindFunc(func(e *billingv1.ItemEvent) error {
before, after := e.EntitlementsBefore["instances"], e.EntitlementsAfter["instances"]
if after < before {
// stop the owner's instances above the new limit
}
return e.Next()
})
In pb_hooks, the item records themselves have the usual record hooks:
onRecordAfterUpdateSuccess((e) => {
const owner = $app.findRecordById(e.record.getString('owner_collection'), e.record.getString('owner'))
const { totals } = $billing.entitlements(owner)
// ...
e.next()
}, '_billing_items')
A webhook delivered twice runs the hook twice with the same result, so compare before and after rather than act on every call.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.