Billing
On this page
Introduction#
Billing sells subscriptions on two rails and keeps one entitlement for both. The card rail is Stripe through Laravel Cashier, and the store rail is the App Store and Google Play through RevenueCat. Whichever rail charged last writes the same columns on the billable (plan, plan_status, plan_provider, plan_product_id, and the rest of the provenance set), and a rail may only revoke what it granted.
Everything you sell is described once, in config('magic-starter.billing'). The package never writes to Stripe, App Store Connect, Google Play or RevenueCat: billing:manifest prints what each of them has to hold, and billing:doctor checks that they do. An LLM agent with the vendor CLIs can apply the manifest from the billing setup reference.
Throughout this document {prefix} is config('magic-starter.route_prefix').
Feature: Features::billing(). No billing route, command or webhook is registered while the feature is off.
Requirements#
Features::billing()inmagic-starter.features, thenphp artisan magic-starter:install --features=billingfor the migrations. Do not runvendor:publish --tag=cashier-migrations: the package ships its own three, which resolve the billable table and the key type from config.- Already ran Cashier's own migrations? Set
MAGIC_STARTER_PACKAGE_SUBSCRIPTION_MODELS=false(billing.package_subscription_models, defaulttrue). Cashier'ssubscriptionsandsubscription_itemsare keyed by a bigint, and the package'sSubscriptionandSubscriptionItemmodels key byuse_uuids; with UUIDs on, every subscription write fails and the Stripe webhook answers 500 until Stripe gives up. With the switch off the package hands Cashier neither model, so Cashier's own integer-keyed models stay.billing:doctorreports the mismatch asschema.subscription_keys. billing.billableis'user'(the default) or'team'.'team'needs the teams feature, and boot refuses it without. The billable is the subject the entitlement is written to, and its key is the RevenueCatapp_user_id.- Cashier's
Billabletrait on the billable model for the card rail. A store-only application can leave it off. - Stripe:
STRIPE_SECRETandSTRIPE_WEBHOOK_SECRET. The webhook is Cashier's own path,stripe/webhook. - Stores:
REVENUECAT_SECRET_API_KEYandREVENUECAT_WEBHOOK_SECRET, see RevenueCat Webhook.REVENUECAT_API_V2_KEYandREVENUECAT_PROJECT_IDare read only bybilling:doctor --remote.
The catalogue is validated at boot while the feature is on. A catalogue that could sell the wrong thing throws a LogicException naming the key, product or tier, instead of booting.
The Catalogue#
Four keys describe what you sell. One product entry carries everything every rail needs.
'billing' => [
'billable' => 'user',
'tier_order' => ['free', 'pro', 'business'],
'tiers' => [
'free' => ['name' => 'Free', 'features' => ['One project']],
'pro' => ['name' => 'Pro', 'recommended' => true, 'limits' => ['seats' => 5]],
'business' => ['name' => 'Business', 'limits' => ['seats' => 50]],
],
'products' => [
'pro_monthly' => [
'type' => 'subscription',
'tier' => 'pro',
'cycle' => 'monthly',
'prices' => [
'web' => ['USD' => 2900, 'TRY' => 49900],
'app_store' => ['TRY' => 59999],
],
'refs' => [
'stripe_price' => env('CASHIER_PRICE_PRO_MONTHLY'),
'app_store' => 'com.example.app.pro.monthly',
'play' => 'pro:monthly',
],
],
],
'pricing' => [
'currency' => 'USD',
'country_header' => null,
'country_currencies' => [],
'commission' => ['mode' => 'absorb', 'rate' => 0.15],
],
],
| Key | Meaning |
|---|---|
tier_order |
Your tier ids, cheapest first. Required. The first entry is the free floor: what a billable holds when nobody pays, so no product may sell it. It is the only list of tiers that exist, and the order every cross-rail decision reads. |
tiers |
Display copy per tier id: name, tagline, features, recommended, and anything else you add. Copy is passed through __() per request, so author it as English source strings or translation keys (see Translating tier copy). cycles and products are reserved: they are derived and written over. |
products |
What you sell, keyed by product key. |
pricing |
The base currency a screen falls back to, the country_header and country_currencies that choose a caller's web currency, and the commission rule that derives store prices. |
A product entry:
| Field | Meaning |
|---|---|
type |
subscription, consumable, non_consumable or physical. Only subscriptions are sold today; the other types validate, and nothing sells them yet. |
tier |
A tier_order id. Required for a subscription. |
cycle |
monthly or annual. Required for a subscription. |
credits |
Optional integer a one-off purchase grants. |
prices |
channel => currency => amount in minor units. See Prices. |
refs |
Each rail's id for the product: stripe_price, app_store, play. See Store Ids. |
trial_days |
Optional whole number of free days a subscription starts with, default 0 (no trial). 0 to 730: anything above 730 (the longest trial Stripe accepts), a negative or non-integer value and any non-zero value on a product that is not a subscription stops boot. Sent to Stripe as trial_period_days, so the trial starts when the customer completes Checkout. Only the web (Stripe) rail honours it, and it is the length offered, not a promise to everybody. See Trials. |
sellable |
Boolean, default true. false keeps the product mapped for webhooks, reconciliation and entitlement reads (a grandfathered price still bills people). billing/plans lists it with sellable: false so a client can place what a subscriber holds; a client must offer only sellable products. It cannot be checked out or swapped to (422 product_not_sellable), and is left out of billing:manifest and billing:doctor. Anything but a boolean stops boot. |
What boot refuses#
- A leftover
plans,pricesorstore_productskey, even empty. The message names where its content moved:tiersandtier_order,refs.stripe_price, andrefs.app_storeandrefs.play. There is no alias. - An empty
tier_order. - A product with an unknown
typeor asellablethat is not a boolean, or a subscription with no tier, a tier outsidetier_order, or acyclethat is notmonthlyorannual. - A
trial_daysthat is not a whole number of 0 or more, is above730(Stripe's longest trial), or is non-zero on a product that is not a subscription.1is accepted; the trial is sent astrial_period_days, so it starts when the customer completes Checkout. - A
pricesentry that is not a known channel (web,app_store,play) mapping a three-letter currency code to a whole amount of 0 or more. - A
refs.playthat is not exactly<subscription_id>:<base_plan_id>, or arefs.app_storecontaining:. - A
pricing.commission.modeother thanabsorborgross_up, or aratethat is not a number of at least 0 and below 1. - A
pricing.country_headerthat is not a string or null, apricing.country_currenciesthat is not a map of two-letter country to three-letter currency, or a mapped currency no product prices on the web channel. - A product that sells the free floor.
- Two sellable subscriptions on the same tier and cycle, since the plans screen would list one offer twice. Keep one sellable and mark a retired price
sellable: false. - One Stripe price or one store id on two products. The message names both.
- One Play subscription whose base plans sell two different tiers. Play reports a base-plan change inside a subscription as a renewal of the same purchase, so the tier would move with nobody deciding.
Every other process stops at boot on these, artisan commands included, so a deploy fails before the web serves a broken catalogue. billing:doctor is the one exception: it logs the refusal, boots, and reports it as catalogue.valid.
Product Keys#
A product key is <tier>_<cycle>, for example pro_monthly or business_annual. Write one product per tier and cycle and put every rail's ref on it. The key is the same everywhere:
| Where | The key is |
|---|---|
POST billing/checkout, POST billing/swap |
the product field |
GET billing |
product, the catalogue key behind the stored rail id |
| Stripe | the price's lookup_key, and the product's env variable CASHIER_PRICE_<KEY> |
| RevenueCat | the package lookup_key in the default offering |
The price env variable is the key uppercased with every run of non-alphanumeric characters turned into _: pro_monthly reads CASHIER_PRICE_PRO_MONTHLY. billing:manifest prints the variable beside each Stripe price so an agent knows what to fill after creating it.
A reverse lookup (a Stripe price or a store id back to its product) is exact, and boot guarantees one product per ref. A stored id (plan_product_id) is tried as a Stripe price first and a store id second, by GET billing and entitledProduct() alike. An empty ref is no ref: an unset env variable writes an empty string, and a lookup honouring it would name the empty string as the price of a paid tier.
Prices#
prices are display figures, never a charge: each rail charges what its own dashboard says. Amounts are integers in the currency's minor unit under ISO 4217 (2900 is 29.00 USD, 3400 is 3400 JPY, 1500 is 1.500 KWD).
- Write the web price. Any currency you write there is a currency the product sells in.
- A store channel (
app_store,play) derives each remaining currency from the same currency's web price underpricing.commission:absorb: the store charges the web figure and you net less.gross_up: the store chargesceil(web / (1 - rate)), so you net the web figure. With a0.15rate, 2900 becomes 3412.
- An explicit store price always wins over the derivation.
- A currency the web channel does not price is absent on a store channel. The package never converts between currencies: a rate frozen into config is wrong the day after it is written.
Currency#
A caller is shown each product in one web currency, and the checkout charges in that same currency, so the screen and the charge never disagree. The caller's currency is, in order:
- The billable's
billing_currencypin: the currency Stripe already bills it in. - The country in the request header
pricing.country_headernames, mapped throughpricing.country_currencies. A missing header, an unknown location (XX), a Tor exit (T1) and an unmapped country go to step 3. - The base
pricing.currency.
'pricing' => [
'currency' => 'USD',
'country_header' => 'CF-IPCountry',
'country_currencies' => [
'TR' => 'TRY',
],
],
country_header is null by default, which turns the country rule off. Behind Cloudflare it is CF-IPCountry, with the Add visitor location headers managed transform on; an origin reachable without Cloudflare in front of it accepts the header from anybody.
Per product, the caller's currency falls back to the base, then to the first web currency the product carries, so an unpinned caller can buy every product, in the currency the screen showed. A product with no web price names no currency and checks out with none, as before.
The pin is different, because Stripe bills a customer in one currency. A pinned caller sees a product not priced in the pin flagged sellable: false, at its base price, with its cycle dropped from the tier's cycles, and checkout and swap refuse it with 422 currency_unpriced. The pin is written only by the Stripe webhook, from the first default subscription event (customer.subscription.created or .updated) that carries a currency, and is never overwritten; a checkout writes nothing, since an abandoned one has billed nobody. A subject with no pin yet is held to the same rule by its Stripe customer: a subscriber from before the column existed, or one the webhook has not reached, is billed in the currency the customer already carries. So billing/plans, checkout and swap all take the fixed currency, the pin else the customer's, and the country never overrides it. checkout and swap read the customer from Stripe on the request, only for a subject that has one and no pin (and, for checkout, only for a product with a web price), and a Stripe failure fails them. billing/plans reads it at most once per ten minutes per billable, in the application cache (a currency or its absence), and a Stripe failure there is logged, remembered for a minute and leaves the caller unfixed, so the screen never fails because Stripe does and a deleted customer costs one call a minute, not one per load. A subject nothing has billed has no fixed currency: plans and checkout use the caller's, and swap checks the target against the base currency.
A custom ResolvesBillingCurrency is asked only of a caller with no fixed currency.
The column comes from add_billing_currency_to_billable_table.php. Without it nothing is pinned and the webhook skips the pin rather than failing; billing:doctor reports it as schema.billing_currency while country_header is set.
Store Ids#
| Rail | Ref | Form |
|---|---|---|
| Stripe | refs.stripe_price |
The price id, price_.... Read from CASHIER_PRICE_<KEY>. |
| App Store | refs.app_store |
The product id, for example com.example.app.pro.monthly. |
| Google Play | refs.play |
<subscription_id>:<base_plan_id>, the whole id. |
A store id names one product, matched exactly. RevenueCat's store_identifier for a Play product is the same <subscription_id>:<base_plan_id> string.
When RevenueCat's subscriber read reports a Play purchase, the store rail resolves it in this order: the composed <subscription_id>:<base_plan_id>, then the raw id exactly (every App Store id), then, on Play only, the bare subscription id. The bare id names no base plan, so it resolves the tier only: GET billing then answers product and cycle as null. A catalogue keyed on the bare subscription id misses on every Android renewal, so write the composed id.
One Play subscription sells one tier. Give each tier its own Play subscription and one base plan per cycle.
Reading the Entitlement#
HasEntitlement adds read-only checks to the billable model that answer for every rail. Cashier's subscribed() answers for Stripe alone, so a store buyer would read as free.
use FlutterSdk\MagicStarter\Traits\HasEntitlement;
class User extends Authenticatable
{
use HasEntitlement;
}
Under team billing the trait belongs on the team model instead.
| Method | Answers |
|---|---|
entitled() |
Whether somebody is paying for a tier above the floor right now. Dunning statuses count. |
onTier('pro') |
Whether the held tier is exactly that one. A lapsed customer holds the floor. |
tierAtLeast('pro') |
Whether the held tier ranks at or above it in tier_order. A tier outside the ranking answers false on either side. |
onGracePeriod() |
Whether plan_grace_period_ends_at is still in the future. |
entitlementProvider() |
The BillingProvider behind the plan: none, stripe, app_store, play_store or manual. |
entitledProduct() |
The catalogue key the entitlement was bought as, or null when not entitled or the stored id matches no product. |
A finished or paused plan reads as the floor even if the tier is still stored, so a gate on tierAtLeast() cannot be passed by a lapsed customer.
Endpoints#
Middleware: auth:sanctum. Reads are open to any member of the billable team; writes belong to its owner.
| Endpoint | Purpose |
|---|---|
GET {prefix}/billing |
The entitlement. |
GET {prefix}/billing/plans |
The catalogue, one row per tier. |
POST {prefix}/billing/checkout |
Start a Stripe Checkout session. |
POST {prefix}/billing/swap |
Move the card subscription to another product. |
POST {prefix}/billing/cancel |
Cancel at the end of the paid period. |
GET {prefix}/billing/portal, invoices, payment-method |
Stripe portal URL, invoice page, default card. |
GET {prefix}/billing/store-funded-team |
See Refusals. |
GET {prefix}/billing/usage |
Registered only while your app binds Contracts\ReportsUsage. |
Checkout and swap#
{
"product": "pro_monthly",
"success_url": "https://app.example.com/billing/done",
"cancel_url": "https://app.example.com/billing"
}
swap takes product alone. The key fixes the tier and the cycle together, so the customer is charged the figure the screen showed. A product this rail cannot sell answers 422 with code: "product_not_sellable": an unknown key, a product that is not a subscription, the free floor, one with no refs.stripe_price, or one marked sellable: false. A product not priced in the currency Stripe bills this subject in answers 422 with code: "currency_unpriced"; see Currency.
A product with trial_days starts a trial for a caller who is eligible, and a checkout always collects a card. An ineligible caller is not refused: they buy at the full price. See Trials.
Plans#
data is a list of tier rows in tier_order order, each carrying its tiers definition plus the derived cycles (the cycles a sellable product with a Stripe price sells it on) and products, every subscription product of the tier:
{
"data": [
{
"id": "pro",
"name": "Pro",
"cycles": ["monthly"],
"products": [
{
"key": "pro_monthly",
"type": "subscription",
"tier": "pro",
"cycle": "monthly",
"sellable": true,
"trial_days": 14,
"store_ids": { "app_store": "com.example.pro.monthly", "play": "pro:monthly" },
"currency": "USD",
"prices": {
"web": { "USD": { "amount_minor": 2900, "display": "29.00 USD" } }
}
},
{
"key": "pro_monthly_2025",
"type": "subscription",
"tier": "pro",
"cycle": "monthly",
"sellable": false,
"trial_days": 0,
"store_ids": { "app_store": "com.example.pro.monthly.2025", "play": "pro:monthly-2025" },
"currency": "USD",
"prices": {
"web": { "USD": { "amount_minor": 1900, "display": "19.00 USD" } }
}
}
]
}
]
}
A product with sellable: false is listed so a client can rank what a subscriber already holds; offer only the sellable ones. store_ids carries null for a store the product is not on. prices.web holds the one currency currency names, the one the checkout charges (Currency); a product with no web price carries "currency": null and "web": {}.
trial_days is the trial THIS caller would get, not the configured length: it is 0 for a caller who is not eligible (and for a caller with no billing subject), so a screen never offers "Free for 14 days" to somebody the checkout would charge on day one. While no product offers a trial, the endpoint makes no billing_trials query. See Trials.
An application that has published nothing gets an empty list, not a 404.
Translating tier copy
Copy is passed through __() per request, so author it as English source strings or translation keys. Every top-level string of a tier except id, and every string inside a list such as features, is translated into the request locale; a line with no translation comes back unchanged. An associative array such as limits, and any value that is not a string, is served as configured. A Turkish plan grid is then one entry per line in lang/tr.json:
{
"Kick the tires.": "Bir deneyin.",
"Everything you need to try it": "Denemek için gereken her şey"
}
The entitlement#
GET billing answers plan, plan_status, subscribed, renews, cycle, provider, provider_status, product_id (the rail's own id), product (the catalogue key), manage_via, manage_url, current_period_end, trial_ends_at, grace_period_ends_at, and three collections that are never null: owned (always [] for now), balances (always {} for now) and allowances (your ReportsUsage answer, or {}). A null plan means the billable holds nothing; this package names no free tier.
Refusals#
Each refusal drives a different next step in the client, so they carry a machine-readable reason and the client never reads the sentence.
Across rails and stores#
| Status | Reason | Meaning |
|---|---|---|
| 409 | managed_by_store |
A store is billing the subject. checkout, swap, cancel and portal refuse, and billing.provider names app_store or play_store. Manage it where it was bought. |
| 409 | subscription_exists |
The card rail already bills the subject, including a cancelled subscription still inside its paid period. A second checkout would bill twice. Use swap, which un-cancels. |
| 409 | no_billing_account |
There is nothing to manage: no Stripe customer, or the billable has no Cashier trait. |
| 404 | none | swap or cancel with no card subscription (checked after the store guard, so it never claims there is nothing to cancel while a store charges), or no billing subject at all. |
| 403 | none | The caller is a member and not the owner. |
| 422 | product_not_sellable |
See Checkout and swap. |
| 422 | currency_unpriced |
The product has no web price in the currency Stripe bills this subject in. See Currency. |
Two store SKUs share a subscription group, and a store account holds one active subscription per group, so a second purchase from the same account moves the subscription instead of opening another. GET billing/store-funded-team returns {"store_funded_team": {"id": ..., "name": ...}} for another subject the caller owns that a store is already funding, or null, so a client can refuse a store purchase by name before it moves one.
At the entitlement write, a rail may only revoke what it granted. A cross-rail write that would leave the billable with less access is dropped and logged. A cross-rail upgrade lands and logs a warning, because two rails claiming one customer means somebody is paying twice.
Identity#
RevenueCat's app_user_id is the billable's key: the user's id under 'user', the team's under 'team'. The client must log in to RevenueCat with it before purchasing. Deliveries whose identity cannot be resolved leave the entitlement untouched and log a warning, and still answer 200:
- an
app_user_idthat cannot be a billable key (an anonymous$RCAnonymousID:...), unless exactly one alias can; - an id with no billable behind it;
- several aliases that could each be a billable, which the job cannot choose between.
A TRANSFER event re-reads both the transferred_from and the transferred_to side, since a subscription moved between two billables. Set the RevenueCat transfer behaviour to "Transfer if there are no active subscriptions". Sequential integer keys are guessable and collide between environments sharing a project, so billing:doctor warns and recommends use_uuids.
Trials#
A product with a trial_days of 1 or more starts a free trial on the web rail (Stripe Checkout through Cashier). Whether a given customer still gets it is decided per user and billable, never by the catalogue alone.
'pro_monthly' => [
'type' => 'subscription',
'tier' => 'pro',
'cycle' => 'monthly',
'trial_days' => 14,
// ...
],
Who is eligible#
TrialEligibility::allows($user, $billable) answers it, from the local database only (no Stripe call). The user is always the signed-in person, and the billable is the subject the trial would bill: the user itself, or their current team under team billing. It refuses:
| Refused | Why |
|---|---|
| A guest | A guest account costs one tap to make. Asked only where the application applied HasGuestSupport; without it there are no guests. |
A user with any billing_trials row |
One trial per person, so a person cannot trial on their account and again on every team they create. |
A billable with any billing_trials row |
One trial per subject, so a team one member trialed is not trialed again by the next member. |
A billable holding a default Cashier subscription, in any status |
A returning paid customer is not a new one, and a current subscriber would meet subscription_exists straight after a "Start free trial" button. |
A row the card check refused still counts, so a refusal never resets eligibility. While the billing_trials table is missing, nobody is eligible: the plans show trial_days: 0, checkout sells at the full price, and a warning names the table, instead of both answering 500. An application with its own rules (a domain allow-list, a sales-led exception) binds a subclass of TrialEligibility in the container.
Checkout#
POST billing/checkout starts the trial for an eligible caller by sending subscription_data.trial_period_days to Stripe and tags the subscription with the metadata magic_starter_trial_user, the acting user's key. The tag is how the webhook learns the person, since under team billing the Stripe customer is the team. An ineligible caller is not refused: they buy at the full price, which is what GET billing/plans showed them.
Every checkout, trial or not, sends payment_method_collection=always. A trial's first invoice is zero, and a session that skipped the card would end the trial on a customer with nothing to charge. The card is also what the check below reads.
The card check#
- The
customer.subscription.createdwebhook records abilling_trialsrow for atrialingdefaultsubscription carrying the metadata tag, in the same transaction as the entitlement write, and queuesCheckTrialCardafter that transaction commits. A trial started anywhere else (the Stripe dashboard, another integration) carries no tag and is not this package's to police. CheckTrialCardreads the card's fingerprint outside the webhook: the subscription's default payment method first, then the customer's invoice default. Checkout may not have attached the card yet, so the job asks again a minute later, for about six minutes (six attempts), and then keeps the trial; a trial recorded more than six hours ago is kept on its first attempt, which is what ends the wait on thesyncqueue. A payment method that is not a card, or a card Stripe reports without a fingerprint, also keeps the trial: there is nothing to compare.- Under a cache lock (
magic-starter:billing-trials), the job walks every trial that shares a person, a billed subject or a card with this one, earliest first, and keeps the trial Stripe created first (itscreated, then the row key), never the job that happened to run first. A later trial whose local Cashier row is stilltrialingis refused, and cancelled in Stripe with no proration and no invoice only while Stripe's live status also saystrialing. One that already converted to paying is kept, and a refusal whose cancel was still owed when it converted is withdrawn, because this check refuses trials and never customers. One Stripe has already ended is marked done without a cancel. - A refused trial on the same subject as the surviving one also loses its local Cashier row, so
subscription('default')keeps answering the survivor, and the subject's entitlement is re-projected from the survivor's row: the refused trial's owncustomer.subscription.createdhad written its tier and product.
The lock is fleet-wide only on a shared cache store (redis, memcached, database); on file or array each server locks for itself.
The refusal reason is card_reused when the card is the only thing two trials share, and duplicate when they share a person or a subject. The refusal is written before the cancel, and a refused row with no checked_at is a cancel still owed that any later check of its set finishes. While it is owed, the webhook keeps applying the subscription's customer.subscription.updated events, so its local status stays true; once the refusal is finished they are skipped.
On the sync queue the job cannot release itself for a retry, so it never retries there. billing:reconcile covers that, a dispatch lost after the commit, and a cancel that failed on the job's last attempt: a full run re-dispatches the check of every trial still unchecked after 30 minutes, refused or not. It does so only while a product offers trial_days and the billing_trials table exists.
The sweep runs on billing:reconcile's cadence (magic-starter.billing.reconcile.cadence, daily by default), not on a cadence of its own. While a product offers a trial, set MAGIC_STARTER_BILLING_RECONCILE_CADENCE=hourly, or a stranded check waits up to a day.
A check settles the trials one hop from its own row. A chain (A shares a card with B, B a person with C) is settled by the checks of the rows in it, each against its own neighbours, so C is compared with B and not with A. This is a known limitation.
The refusal mail#
TrialRefusedNotification is mailed only for card_reused: the person's card had already taken a trial, no trial was opened, nothing was charged, and they can still subscribe without one. A duplicate sends nothing, since the trial they meant to have is the surviving one. The mail goes out after the cancel is confirmed, so a mail failure never causes a second cancel. Its "View plans" action links to the frontend base (magic-starter.frontend_url, or url('/') when that is unset) followed by magic-starter.billing.client_path.
| Config key | Env | Default |
|---|---|---|
magic-starter.billing.trial_refused_notification |
MAGIC_STARTER_TRIAL_REFUSED_NOTIFICATION |
true |
magic-starter.billing.client_path |
none | /teams/billing |
client_path is the client's billing screen path, linked from the refusal mail. A published billing array replaces the package's whole array and may predate the key, in which case the mail falls back to /teams/billing.
Set trial_refused_notification false to send your own message instead. The sentences are magic-starter::billing.trial_refused.* in en and tr; a published lang/vendor/magic-starter/ copy wins over the package's own.
Lifecycle mails#
Two opt-in mails follow the Stripe subscription lifecycle. Both are off by default.
| Config key | Env | Default |
|---|---|---|
magic-starter.billing.trial_ending_notification |
MAGIC_STARTER_TRIAL_ENDING_NOTIFICATION |
false |
magic-starter.billing.payment_failed_notification |
MAGIC_STARTER_PAYMENT_FAILED_NOTIFICATION |
false |
TrialEndingNotification is sent from the Stripe webhook on customer.subscription.trial_will_end, which Stripe fires three days before a trial ends (the Dashboard's "Trial ending events" setting). It goes out only for the default subscription while it is still trialing with a trial end in the future, for a trial the card check did not refuse (finished or with its cancel still owed), and for a price mapped to a tier. It has two variants. When the saved card will be charged, the mail says so. When cancel_at_period_end is true, or cancel_at falls on or before the trial end, the mail says nothing will be charged and the account returns to the free plan. The date is rendered in the recipient's timezone attribute when it is valid, otherwise in the app timezone, and in the mail locale.
PaymentFailedNotification is sent on invoice.payment_failed for the first attempt (attempt_count 1) of a cycle invoice (billing_reason subscription_cycle: a renewal, or the first charge after a trial) with a positive amount due, on the default subscription, once per invoice. Stripe counts only automatic retries in attempt_count, so a payer who retries the same invoice by hand fails again at attempt 1; the per-invoice claim keeps that to one mail. A declined card on a plan swap is reported inline, and a Checkout failure happens in front of the payer, so neither mails. The invoice's subscription is read from parent.subscription_details, where Stripe's basil API versions and later put it: an endpoint pinned to an older API version, which still sends a top-level subscription, sends no payment mail.
The recipient is BillingRecipient::for(): the team owner for a team billable, the user for a user billable, and no mail when there is neither. This matches BillingPolicy::manage. Both mails are queued after the webhook transaction commits and use the recipient's locale. A replayed Stripe event sends nothing, because the webhook dedup already claimed it. Neither mail carries a price or an upsell, and neither appears in the notification preference matrix.
Enable both events on the Stripe endpoint. Cashier's default cashier:webhook list does not include them, so add them to cashier.webhook.events:
customer.subscription.trial_will_endinvoice.payment_failed
Then turn off Stripe's own "trial ending reminder" and "failed payment" customer emails in the Dashboard under Billing settings, Customer emails. Leave them on and the customer is mailed twice for the same event.
The sentences are magic-starter::billing.trial_ending.* and magic-starter::billing.payment_failed_mail.* in en and tr. A published lang/vendor/magic-starter/ copy wins over the package's own.
billing:doctor --remote checks the endpoint as stripe.webhook_events, one check for every event the package acts on. It runs only while a lifecycle mail or campaigns are on, and requires the events of what is on: customer.subscription.trial_will_end while trial_ending_notification is on, invoice.payment_failed while payment_failed_notification is on, and checkout.session.completed while campaigns are on. It reports ERROR when STRIPE_SECRET is unset or Stripe refuses the read. It reports WARN when no route is named cashier.webhook, when no enabled endpoint posts to route('cashier.webhook') (urls are compared without a trailing slash and with the scheme and host case-insensitive), or when a required event is missing (* covers all). The route check follows APP_URL, so APP_URL must be the host the endpoint posts to.
The table#
billing_trials has one row per trialing subscription a package checkout opened, and is the anti-abuse record behind the rules above. A fresh magic-starter:install --features=billing publishes create_billing_trials_table.php with the other billing migrations; an existing application copies it in, see Upgrading. Keys follow use_uuids. billing:doctor reports a table missing while a product offers a trial as schema.billing_trials.
| Column | Holds |
|---|---|
user_id |
The person who started the trial. Nullable foreign key to users, set to null when the user is deleted. |
billable_type, billable_id |
The subject, as getMorphClass() and its key. No foreign key, so deleting a team keeps the record that it trialed. |
stripe_subscription_id |
The Stripe subscription, unique. |
subscription_created_at |
Stripe's own created, the order "earliest wins" is decided on. |
card_fingerprint |
The card's fingerprint, indexed, null until read. |
checked_at |
Stamped once the check finished, whether or not it found a fingerprint. |
refused_at, refusal_reason |
Set on a refused trial: card_reused or duplicate. |
Limits#
- A wallet card (Apple Pay, Google Pay) can carry a different fingerprint than the same card entered plainly, so one card can reach a second trial through the wallet. This is an accepted limitation.
- Web and store trials are separate.
trial_daysreaches Stripe only. A store (intro offer) trial is configured in App Store Connect or Google Play Console, and is not recorded, checked or counted here, so a customer can take one on each rail.
Promotion Codes#
Stripe Checkout can show a promotion code field. It is off by default, and it is a web rail feature: a store purchase is priced by the store and is unaffected.
| Config key | Env | Default |
|---|---|---|
magic-starter.billing.promotion_codes |
MAGIC_STARTER_BILLING_PROMOTION_CODES |
false |
MAGIC_STARTER_BILLING_PROMOTION_CODES=true
With it true, every POST billing/checkout session, trial or not, is created with allow_promotion_codes through Cashier's allowPromotionCodes(), and Stripe Checkout renders its own code field. With it false the key is not sent at all. The package never creates a code: coupons and promotion codes are made by the operator in the Stripe dashboard (or API).
A code is a Stripe coupon plus a customer-facing string, so the coupon's settings decide what it does. Stripe accepts allow_promotion_codes together with subscription_data.trial_period_days, an explicit currency and payment_method_collection=always, the options a package checkout sends; redeeming a code in a browser on such a session was not exercised. What follows was measured against the Stripe API (version 2026-08-26.dahlia, test mode, test clocks) unless a Stripe page is named. The measurements attached each code when the subscription was created through the Subscriptions API, which is what Checkout does when the customer completes it; the swap used proration_behavior=always_invoice and billing_cycle_anchor=now.
Before you hand out a code#
- Prefer
percent_off. Anamount_offcoupon needscurrency_optionsfor every currency you sell in, andcurrency_optionsexists only onamount_off(Stripe: create a coupon). A percentage is currency-neutral. - A code discounts an annual invoice in full. Even a 3 month
repeatingcode at 50% took half of the whole year's charge off the first annual invoice, not half of one month. - A
repeatingcode survives a monthly to annual swap. A customer who swaps to annual inside the window keeps the discount on the annual line, and the window is not reset by the swap. A swap after the window has closed is full price. - To keep codes off annual, give annual its own Stripe product. Set the coupon's
applies_toto the monthly product only. Stripe states that a promotion code inherits the product restrictions of its parent coupon (Stripe: coupons). This restriction was not exercised in the measurement; the catalogue it ran on had one product for both cycles. - Under a trial,
onceis not spent on the trial. The trial's invoice is zero and carries a zero discount line, so nothing is spent; the coupon stays on the subscription, and the first paid invoice is discounted. After it the subscription holds no discount. - Under a trial, a
repeatingwindow starts at creation. It counts from when the subscription is created, not from the first charge. A trial shorter than a month costs no discounted charge: a 3 month code on a 14 day trial discounted three paid charges and the fourth was full price. A trial of a month or more does use up discounted charges, since the window keeps running while it lasts. - Do not put
minimum_amounton a code that a trial product can see. Through the Subscriptions API, Stripe refused such a code on a trialling subscription at creation ("This promotion code cannot be redeemed because the associated purchase does not meet the minimum amount requirement."), since the first invoice is zero. Redemption through Checkout itself was not measured, nor was aminimum_amountcode on a subscription without a trial, so treat both as unverified. first_time_transactionexcludes anyone who trialed or paid before. Stripe does not count a customer with earlier payments or non-void invoices as first-time (Stripe: discounts in Checkout), and it names customers who "Subscribed to a trial period, even if it subsequently canceled" among those the setting refuses (Stripe: coupons).
The checkout_started row of the audit log records promotion_codes, a boolean that says whether codes were allowed on that session. It does not say whether a code was entered or which one.
Campaigns#
A campaign is a time-boxed Stripe promotion code that staff offer on some catalogue products. It is a web rail feature: a store purchase is priced by the store. It is off by default.
\FlutterSdk\MagicStarter\Features::campaigns(),
php artisan magic-starter:install --features=campaigns publishes the create_campaigns_table.php migration; an existing application copies it in, see Upgrading. The billing feature has to be on as well.
Lifecycle#
Staff create campaigns in the admin panel (resource key campaigns). A campaign has a name, a window, the catalogue products it covers (the ones checkout sells: sellable subscriptions with a Stripe price on a ranked tier above the free floor), a headline and a body per supported locale, and the id of a Stripe promotion code (promo_..., not the string customers type). The default locale's copy is required; a blank locale is served with the default's text. There is no delete: a campaign that should stop is switched off, which keeps the record of what ran.
- Running means enabled, with
starts_at <= now < ends_at. The clock starts and ends a campaign; nothing has to be saved at either moment. Back-to-back windows never both run. - One enabled campaign at a time. Saving an enabled campaign whose window overlaps another enabled one is refused, naming the other.
- The code is checked in Stripe on save, only when the saved state is enabled and the campaign was not enabled before or its code, end or products changed. Editing copy or the start never calls Stripe, and neither does switching a campaign off. A refusal leaves the stored campaign as it was. The save refuses a code that is inactive, has no expiry or expires before the campaign ends, is limited to first-time transactions (a team that trialled or paid already has prior transactions), has a minimum amount (a trial checkout never meets one), is limited to one customer, belongs to the other Stripe mode, or sits on a coupon that Stripe no longer marks valid, that does not cover every campaign product or, for an amount off, that has no amount in every currency the campaign products sell in.
- A
repeatingcoupon has to outlast the trial. Stripe counts a repeating coupon's months from the subscription's start, which is the trial's start, so a repeat that ends within the trial ends before the first paid invoice and the buyer is never discounted. The save refuses arepeatingcoupon whoseduration_in_monthstimes 28 days is not longer than the longesttrial_daysamong the campaign's products. Aonceorforevercoupon survives a trial and lands on the first paid invoice. - The discount is a snapshot. The coupon's percentage, or its amount per currency, is stored when the code is checked and is what the panel and the client show. It does not follow later edits to the coupon in Stripe: switch the campaign off and on again, or change its code, to read the coupon afresh.
Audience and the banner#
GET billing/campaign answers the campaign running now, or {"data": null}:
{
"data": {
"id": "camp-1",
"starts_at": "2026-11-01T00:00:00+00:00",
"ends_at": "2026-11-08T00:00:00+00:00",
"products": ["pro_monthly", "pro_annual"],
"discount": { "type": "percent", "value": 20, "currency": null, "currency_options": null },
"headline": { "en": "Pro is 20% off this week" },
"body": { "en": "Upgrade before Sunday to keep the price." }
}
}
discount.type is percent or amount; currency is set only for an amount. currency_options is, for an amount, the amount off in each further currency, keyed by uppercase ISO code like currency and in the same minor unit as value ({"TRY": 15000}); it is null for a percent or for an amount given in one currency only. headline and body hold one key per supported locale.
It is offered to a caller only when the billed subject holds the free floor (a trialing or paying subject never sees it) and the caller may manage that subject's billing, which is the team owner under team billing. Anyone else gets {"data": null}, not a 403. The client additionally shows it only on the web rail. While Features::campaigns() is off the route does not exist and answers 404.
The running campaign is cached (rebuilt after every save, and at most an hour old otherwise) and filtered by the clock on every read, so a campaign appears and disappears on time without a write.
Checkout#
When a campaign is running, POST billing/checkout for a product it covers, from a caller in the audience, applies the code by itself. The campaign is read from the table at that moment, never from the cached feed, so a campaign staff just switched off cannot discount a session. The session carries:
- the campaign's promotion code as the session discount, and no
allow_promotion_codes, even whenpromotion_codesis on: Stripe refuses a discount beside that key, so a campaign session shows no code field; client_reference_id,campaign:followed by the campaign's id, which is how the completed session is attributed;expires_at, the campaign's end held between 31 minutes and 23 hours 55 minutes from now, a margin inside the 30 minutes to 24 hours Stripe accepts so a server clock slightly ahead of Stripe's never crosses either limit. A campaign ending in ten minutes still gives the customer 31; one ending next week gives nearly a day. A session opened in the last half hour of a campaign therefore outlives it; whether Stripe still honours the code after its own expiry was not measured.
The checkout_started row then carries campaign_id, and promotion_codes is false.
A refused campaign code never blocks the purchase. Stripe's refusal does not reliably name the code: promotion_code_inactive or promotion_code_customer_not_first_time do, a coupon missing the session's currency names the discount parameter, and an exhausted or deleted coupon behind an active code does neither. So any invalid-request refusal of a campaign session opens the session once more without the campaign, at the price the customer would pay anyway, with promotion_codes applying as it does without a campaign. When that session opens, the package logs a warning and records a campaign_code_refused row (a refusal, so an alert on refusals sees a failing campaign) whose reason is Stripe's code, or campaign_code when Stripe named only a parameter. When the second session is refused too, the error was not the campaign's: it propagates as it always did and no refusal row is written.
Attribution#
A completed checkout is recorded from Stripe's checkout.session.completed webhook. When the session's client_reference_id names a campaign (campaign:<id>, as checkout writes it; an unknown id, a bare id without the prefix, or another integration's reference is ignored) the delivery leaves one campaign_redeemed row for the billable behind customer, with the campaign id, the redeemed promotion code and the discount in the currency's minor unit. The code is read from the payload's discounts; when the payload carries no discounts the session is retrieved from Stripe with expand[]=discounts, inside the delivery, and a failed read answers 500 so Stripe retries it. A session with no promotion code on it records nothing. Like every Stripe delivery it runs once per event id, so a re-delivery adds no second row.
A $0 trial checkout counts: the admin panel's Campaign checkouts column counts these rows per campaign, whatever the first charge was. That is checkouts that redeemed the code, not revenue or conversions to paid. The payload shape of a completed session was exercised against fake Stripe payloads; completing a live Checkout needs a browser and was not measured.
Add the event to the endpoint in the Stripe dashboard. cashier.webhook.events shapes only the endpoint php artisan cashier:webhook creates, and that command never updates an existing one:
// config/cashier.php
use Laravel\Cashier\Console\WebhookCommand;
'webhook' => [
'secret' => env('STRIPE_WEBHOOK_SECRET'),
'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),
'events' => [
...WebhookCommand::DEFAULT_EVENTS,
'checkout.session.completed',
],
],
php artisan billing:doctor --remote checks it while campaigns are on, in the same stripe.webhook_events check as the lifecycle mails: a WARN names checkout.session.completed when the enabled endpoint posting to this application's route('cashier.webhook') lacks it (an endpoint listening to * does not). An application that called MagicStarter::ignoreRoutes() and names no cashier.webhook route gets a WARN instead: name your webhook route cashier.webhook, or confirm the event on your own endpoint in the Stripe dashboard.
RevenueCat Webhook#
The endpoint is POST {app.url}/webhooks/revenuecat. Change REVENUECAT_WEBHOOK_PATH only together with the dashboard, since a webhook URL cannot move with a deploy.
The endpoint verifies HMAC signing and nothing else. A static Authorization header, which is RevenueCat's baseline, is refused.
- In the RevenueCat dashboard, open the webhook integration and turn on HMAC signing.
- Copy the signing secret it shows. It is shown once.
- Put it in
REVENUECAT_WEBHOOK_SECRET.
RevenueCat then signs each delivery in X-RevenueCat-Webhook-Signature: t=<unix>,v1=<hex>, an HMAC-SHA256 over "{t}.{raw body}". The signing time must be within five minutes of now. A signature that does not verify answers 403, and it is the only non-200 answer: an unknown billable, an ignored event type and an unreadable body all answer 200, because a retry cannot improve them.
A delivery is only a signal. The job it queues re-reads the subscriber from RevenueCat with REVENUECAT_SECRET_API_KEY and decides what is owed from that read. With the API key set and no webhook secret, the route is not registered, boot logs the reason once, and magic-starter:install refuses to complete. SANDBOX events are acted on only when REVENUECAT_ACCEPT_SANDBOX is true, which production never sets.
The billing:reconcile schedule heals a dropped delivery. Its cadence is daily by default; an application selling mostly through the stores should set MAGIC_STARTER_BILLING_RECONCILE_CADENCE=hourly, because RevenueCat abandons a delivery after about three hours.
Sandbox allowlist#
REVENUECAT_ACCEPT_SANDBOX is all or nothing, and production never sets it. App Review is the case it cannot serve: Apple tests with a sandbox purchase, and the reviewer's account has to reach the tier it bought. REVENUECAT_SANDBOX_APP_USER_IDS (billing.revenuecat.sandbox_app_user_ids) is the narrow form: a comma-separated list of billable keys, the user or team ids behind the review accounts (the same key as the RevenueCat app_user_id, see Identity).
REVENUECAT_ACCEPT_SANDBOX=false
REVENUECAT_SANDBOX_APP_USER_IDS=2f6c1e0a-9d44-4b7e-8a53-0c1d5e7f9a21
- The webhook accepts a
SANDBOXdelivery when any identity the event carries (app_user_id,original_app_user_id,aliases,transferred_from,transferred_to) is a listed key. That only lets the re-read happen. - The job then counts sandbox subscriptions per billable, and only for a billable whose own key is listed. An event that named a listed key in an alias cannot carry that permission to the subscriber it resolved, and the reconciler, which runs the job once per billable, is bound by the same list.
- Everybody else still reads sandbox purchases as no evidence in either direction.
- With
REVENUECAT_ACCEPT_SANDBOX=truethe list is pointless.billing:doctorreportsrevenuecat.sandbox_allowlistasokwith the number of entries (the keys are never printed), as awarningwhen both are on, and says nothing while the list is empty.
A store record that holds sandbox purchases only is never revoked by the store job. The panel's Revoke grant action ends such a record by hand.
Stripe test mode#
A Stripe test key accepts test cards, so a public server left on one would sell a paid tier to anybody who types 4242 4242 4242 4242. The guard refuses that, and lets named people through so a reviewer can still try a purchase.
It is active when STRIPE_SECRET (cashier.secret) is not provably live and the application environment is not local or testing. Only sk_live_ and rk_live_ prove a live key; sk_test_, rk_test_ and any prefix that names no mode (an organisation key, a key a platform manages) are guarded. Any environment name other than local and testing (staging, production, prod) is guarded. A live key, or no key, never activates it.
The allowlist trusts email_verified_at, so keep the emailVerification feature on while the guard is in force: with it on, changing an email address clears the verification, and a user cannot move onto a listed address that nobody verified.
While it is active, POST billing/checkout and POST billing/swap answer 409 for everybody except the allowlist, and record a request_refused row:
{
"message": "Purchases are not open yet; this server is running on Stripe test keys.",
"billing": { "reason": "stripe_test_mode", "provider": "stripe" }
}
MAGIC_STARTER_BILLING_STRIPE_TEST_EMAILS (billing.stripe_test_mode.emails) is a comma-separated list of email addresses, trimmed and compared lower-cased.
MAGIC_STARTER_BILLING_STRIPE_TEST_EMAILS=reviewer@example.com,qa@example.com
- A caller passes only when their email is listed and verified (a user model that does not implement
MustVerifyEmailis judged on the list alone). A guest never passes. - Cancel and the billing portal are never gated: a customer who already holds a subscription can always leave it.
- With an empty list on a guarded server, every checkout and swap is refused.
billing:doctorreportsstripe.test_mode: silent without a Stripe secret,okon a live key,okon a test key inlocalortesting, awarningon a guarded server with an empty list (naming the environment and the variable above), andokwith the number of entries otherwise. The addresses are never printed.
Agent Commands#
Both commands only read. Neither prints a secret, only whether it is set.
billing:manifest#
php artisan billing:manifest --json
php artisan billing:manifest --json --section=play
Prints every vendor object the catalogue needs. --section is one of app_store, play, revenuecat, stripe, env. The JSON carries a schema_version and these sections:
| Section | Holds |
|---|---|
app_store |
One subscription_group and a product per subscription: product_id, reference_name, period (ONE_MONTH, ONE_YEAR), group_level (the highest tier is level 1) and prices. |
play |
A subscription per tier, base_plans per cycle with billing_period (P1M, P1Y) and prices. |
revenuecat |
apps, products (one per store id), an entitlements row per paid tier (lookup key is the tier id), the default offering with one package per product key, and the webhook URL with its HMAC instruction. |
stripe |
A product per tier and, per product key, a price whose lookup_key is that key, with currency, unit_amount, currency_options, recurring.interval and the env_key to fill. |
env |
Each rail variable as present or absent. |
Only subscriptions appear, and a product marked sellable: false is left out.
billing:doctor#
php artisan billing:doctor --json
php artisan billing:doctor --json --remote
Without --remote it checks the configuration: the catalogue validates, the rail secrets that a sold product needs are set, REVENUECAT_WEBHOOK_SECRET exists while the store rail is on, every web-sold product has a Stripe price id, store ids are listed, billable keys are UUIDs, the subscription tables are keyed the way their models write them (schema.subscription_keys), the billing_trials table exists while a product offers a trial (schema.billing_trials), the billing_events table exists (schema.billing_events), the billing_grants table exists (schema.billing_grants), the billable table carries billing_currency while pricing.country_header is set (schema.billing_currency), the sandbox allowlist is consistent (revenuecat.sandbox_allowlist), the Stripe test-mode guard is accounted for (stripe.test_mode), and the reconcile cadence suits the store rail. With --remote it also reads Stripe and RevenueCat and diffs them against the manifest: a Stripe price per lookup key (id, interval, amounts), and the RevenueCat apps, products, entitlements, default offering, packages and webhook (that one delivers to this application's URL), and, while a lifecycle mail or campaigns are on, the events the Stripe webhook endpoint is subscribed to (stripe.webhook_events, see Lifecycle mails). RevenueCat returns a webhook's signing secret only when it is rotated, so whether HMAC signing is on cannot be read: the doctor reports it as an agent_check for a person to confirm in the dashboard.
REVENUECAT_API_V2_KEY is a separate secret key scoped to project_configuration:{apps,products,entitlements,offerings,packages,integrations}:read, and REVENUECAT_PROJECT_ID names the project. Neither is needed to sell.
The JSON is {"schema_version": 1, "ok": true, "checks": [...]}. Each check has a stable id, a status of ok, warning, error or agent_check, and a message. agent_check is vendor state this package cannot read (App Store Connect, Play Console) and names the command to run in command. Any error exits 1.
Audit Log#
Every billing outcome leaves one row in billing_events and dispatches one Laravel event, so "why did this subscriber lose access" is answered after the webhook that did it is long gone. A new install publishes the migration with the other billing ones; an existing application copies it in, see Upgrading.
| Column | Holds |
|---|---|
type |
What happened, one of the values below. Indexed. |
source |
Which path acted: webhook (a Stripe or RevenueCat delivery), reconcile (billing:reconcile), request (an authenticated API call), trial_check (the queued card check), admin (an operator in the admin panel, or the hourly grant expiry). |
provider |
The rail (stripe, app_store, play_store), or null. |
billable_type, billable_id |
The subject, as getMorphClass() and its key. Plain nullable strings with no foreign key: a refusal may have no billable, and a raw store id must fit. |
actor_user_id |
The signed-in user who caused it, or null for a rail-driven outcome. Nullable foreign key to users, set to null when the user is deleted. |
reason |
A stable snake_case rule name, never prose, or null. |
external_id |
The rail's own id: a Stripe event id, a RevenueCat event id (without the rc: prefix the dedup table uses), a Checkout session or Stripe subscription id. Null on a reconcile write. Indexed. |
properties |
JSON with whatever else the outcome needs, never a secret. |
created_at |
There is no updated_at. |
What is recorded#
type |
Source | reason |
Properties |
|---|---|---|---|
entitlement_applied |
webhook, reconcile, trial_check |
none | before, after, changed, direction, cross_rail. |
entitlement_dropped |
any feeder | stale, same_instant_revocation, undecidable_tier_order, cross_rail_revocation, projected_cross_rail_takeover |
The log context and incoming_status. |
checkout_started |
request |
none | product, price_id, trial_days, promotion_codes, and campaign_id on a campaign session. |
campaign_code_refused |
request |
Stripe's code, or campaign_code |
campaign_id, promotion_code_id, stripe_code. |
campaign_redeemed |
webhook |
none | campaign_id, promotion_code, amount_discount. The external_id is the checkout.session.completed event id. |
subscription_swapped |
request |
none | product, price_id. |
subscription_cancelled |
request |
none | ends_at. |
portal_opened |
request |
none | none. |
request_refused |
request |
managed_by_store, no_billing_account, subscription_exists, currency_unpriced |
none for the 409s of Refusals; product and currency for currency_unpriced. |
delivery_refused |
webhook |
See below. | Per reason. |
trial_recorded |
webhook |
none | stripe_subscription_id, trial_ends_at. |
trial_refused |
trial_check |
card_reused, duplicate |
billing_trial_id, user_id. |
trial_cancelled |
trial_check |
none | billing_trial_id, user_id, cancelled_by (this_check when this run cancelled it, already_ended when Stripe had already ended it). |
trial_refusal_withdrawn |
trial_check |
refused_trial_converted |
stripe_status. |
grant_added |
admin |
none | grant_id, plan, reason, expires_at. |
grant_revoked |
admin |
none | grant_id, plan, reason; a store record revoked by hand carries reason and store_sandbox_only instead. |
grant_expired |
admin |
none | grant_id, plan, expires_at, entitlement_written. No actor: the expiry command wrote it. |
trial_extended |
admin |
none | until. |
trial_ended |
admin |
none | note (stripe_bills_now). |
subscription_resumed |
admin |
none | stripe_status. |
invoice_refunded |
admin |
none | invoice_id, amount, currency, reason. One row per refund id. |
entitlement_synced |
admin |
none | rail (stripe or store), changed. |
request_refused |
admin |
The refusal keys of the admin panel. | operation, and rail_message on a rail_error. |
An operator's cancel is a subscription_cancelled row with source admin, and every entitlement write an admin action makes is an entitlement_applied or entitlement_dropped row with source admin.
An apply writes entitlement_applied only when what the entitlement means changed: plan, plan_status, plan_provider, plan_current_period_end or plan_renews. changed names those fields and before and after carry the five values. An apply that only refreshed provenance (a renewal, a reconcile read) writes no row, since that would be one row per delivery that says nothing. direction is upgrade, same, downgrade, unknown, no-order or nothing-stored, and cross_rail is true when a rail holding the record handed it to another.
delivery_refused is a verified delivery the package decided not to act on:
- Stripe:
unmapped_price(a granting price with no tier mapping) andrevocation_skipped(a deleted subscription while another still grants). - RevenueCat endpoint:
unreadable_event, andnon_production_environmentfor an event type that can change an entitlement (a sandboxPAYWALL_IMPRESSIONis logged and leaves no row). - RevenueCat job, on the webhook source:
malformed_app_user_id(for the event's own subscriber, never for a transfer side),unknown_billable,ambiguous_aliases,sandbox_only_subscriber,undated_subscriptions,unmapped_productandnothing_to_revoke.released_burnt_event_idis also recorded when the job gives up after its last attempt and releases the dedup claim. Each is one row per delivery and reason, de-duplicated across retries: a refusal first reached on a retry (the read failed on attempt 1) is still recorded, and a later retry does not write it again.
trial_cancelled is written once per subscription: a re-run that finds Stripe already ended it does not write a second one.
Deliberately not recorded: Stripe and RevenueCat signature failures (unauthenticated input must not write rows), the reconciler's per-run skips, Stripe's silent skips (a duplicate delivery, no billable, a non-default subscription type), a 422 other than currency_unpriced or a 404 (the caller's own mistake, or an honest absence), the RevenueCat family_shared_entitlement (the tier was granted) and unfed_store (another rail's subscription), and a RevenueCat job refusal on the reconcile source or a second time for the same delivery.
Append-only, and recording never breaks billing#
A row is written once. BillingEvent throws a LogicException on update() and delete(), and the only code that removes rows is the prune command, which deletes by age through the query builder.
Recording sits inside the Stripe webhook's own transaction, so the insert runs in a savepoint and only a QueryException is caught: it is logged at error level and the entitlement write goes on. A missing table logs one warning per process and skips the row. In both cases the event is still dispatched, with an unsaved model.
billing_events survives deletion: deleting a user clears actor_user_id, and the billable has no foreign key, so deleting a user or team keeps its rows.
Listening#
Each outcome is one class in FlutterSdk\MagicStarter\Events\Billing (EntitlementApplied, EntitlementDropped, CheckoutStarted, CampaignCodeRefused, CampaignRedeemed, SubscriptionSwapped, SubscriptionCancelled, PortalOpened, RequestRefused, DeliveryRefused, TrialRecorded, TrialRefused, TrialCancelled, TrialRefusalWithdrawn, GrantAdded, GrantRevoked, GrantExpired, TrialExtended, TrialEnded, SubscriptionResumed, InvoiceRefunded, EntitlementSynced), and all of them implement BillingOutcome. They are dispatched after the surrounding transaction commits, so an outcome that rolled back never fires. The package registers no listener of its own.
A synchronous listener runs in the billing path, inside the webhook, request or job that produced the outcome. A listener that throws is reported through your exception handler and never propagated, so the delivery still answers 200 and the request still answers what it would have, but that listener's work is lost. Prefer a ShouldQueue listener for anything that can fail or take time.
use FlutterSdk\MagicStarter\Events\Billing\BillingOutcome;
use Illuminate\Support\Facades\Event;
Event::listen(BillingOutcome::class, function (BillingOutcome $event): void {
$record = $event->record();
if ($record->type->isRefusal()) {
// alert, count, notify...
}
});
record() is the BillingEvent, unsaved (exists false) when the row could not be written, so read its attributes and not its key. type and source cast to the BillingEventType and BillingSource enums, and provider to BillingProvider. Listen to one concrete class for a single outcome.
Logs and retention#
Billing log lines (webhook outcomes, reconciler runs, drops, refusals) go to the channel named by magic-starter.billing.log_channel, and successes are logged at info level. Null or blank, the default, uses the application's default channel. Boot-time messages and the trial eligibility warning keep using the default channel.
| Config key | Env | Default |
|---|---|---|
magic-starter.billing.log_channel |
MAGIC_STARTER_BILLING_LOG_CHANNEL |
null |
magic-starter.billing.webhook_retention_days |
MAGIC_STARTER_BILLING_WEBHOOK_RETENTION_DAYS |
90 |
magic-starter.billing.events_retention_days |
MAGIC_STARTER_BILLING_EVENTS_RETENTION_DAYS |
null (keep forever) |
php artisan magic-starter:billing:prune deletes processed_webhook_events rows older than webhook_retention_days, and billing_events rows older than events_retention_days when it is a number of days. A blank or non-numeric value keeps every row and says so in one line. It runs daily while the billing feature is on. The webhook retention is never taken below 31 days: a dedup claim is the only thing that stops a resent event from running twice, and Stripe's CLI can resend an event up to 30 days old. The history is financial, so keep events_retention_days null unless your retention policy demands a number.
billing:doctor reports a missing billing_events table as an error with the id schema.billing_events.
A refused request still leaves a request_refused row, so put a throttle on the billing routes: name it in magic-starter.route_middleware (which wraps every package API route) or in the route group your application loads them from.
Admin Panel#
With the admin panel mounted, a Billing tab appears on the billable's edit page: the user's under billing.billable 'user', the team's under 'team'. It shows what the billable holds (plan, status, provider, period end, the open grant and its expiry, the Stripe trial end), its billing_events history, and eight actions. Every action goes through Contracts\AdministersBilling, which writes the entitlement through WritesEntitlement and leaves a billing_events row with source admin; nothing in the tab calls Stripe, RevenueCat or the entitlement writer directly.
An action is shown only to an admin billing authorization allows and only in the state it applies to. The contract re-checks the state and refuses on its own, so a crafted request meets the same answer.
| Action | Shown when | Refused with |
|---|---|---|
| Grant plan | No paid rail grants. | paid_rail_active, unknown_plan, expiry_in_past, entitlement_refused |
| Revoke grant | An open manual grant is on record, or a store record while the store rail is configured. | not_manual, rail_error, entitlement_refused |
| Extend trial | The Stripe subscription is trialing and not cancelled. | no_subscription, not_trialing, already_cancelled, date_in_past, not_later, rail_error |
| End trial | The Stripe subscription is trialing and not cancelled. | no_subscription, not_trialing, already_cancelled, rail_error |
| Cancel subscription | The subscription runs and is not cancelled. | no_subscription, already_cancelled, rail_error |
| Resume subscription | Cancelled and still inside its paid period. | no_subscription, not_on_grace_period, scheduled_cancel, rail_error |
| Refund last invoice | A Stripe customer with a local subscription. | no_subscription, invalid_reason, nothing_refundable, stale_target, rail_error |
| Sync now | A local Stripe subscription, or the store rail is configured and the record is a store's, or nobody's or a manual one no open grant holds. | nothing_to_sync, unmapped_price, rail_error |
The sentences are magic-starter::admin_billing.refusals.* in en and tr. A refusal is recorded as a request_refused row (source admin, the key as reason) before it is thrown, outside any transaction the action opened, and the panel halts the action without rolling its own transaction back, so the row survives. rail_error keeps the rail's own message on the row.
Manual grants#
A grant gives the billable a plan with no payment behind it, until an optional expiry or a revoke. The plan is a tier of tier_order, the expiry must be in the future, and the reason is kept on the grant. It is how a plan no rail sells (an enterprise contract invoiced outside the panel, a partner, a comp) is set up.
A grant is made from the billable's Billing tab, or from Grant a plan on the Manual plans and Subscriptions lists, which asks for the customer as well (searched by name or email, a team by its own name or the name or email of its owner or any member, and labelled with the owner's email). Both go through the same AdministersBilling::grant(), are shown only to an admin the billing list allows, and refuse with the same sentences. Manual plans (billing_grants key, Billing group) lists every grant, open or ended, with its customer, plan, reason, status, expiry and who made it; a grant is revoked from the customer's Billing tab.
- A grant is refused while a paid rail grants: the record names Stripe or a store on a granting status, or the local Cashier
defaultsubscription grants and has not ended. The check runs again under a row lock inside the write, because a checkout can land in between, and the grant is written as a projection that yields to anybody paying. - There is one open grant per billable. A new grant closes the previous one as
superseded. The grant's row id travels inplan_product_idasgrant:{id}, which is how a revoke or an expiry knows the billable is still on it. - Revoke ends only a manual grant, or a store record whose RevenueCat subscriber holds no production subscription (sandbox purchases only), which the store job never revokes on its own. Sandbox purchases count as production for a billable whose key is in
sandbox_app_user_ids, and for everybody whileaccept_sandboxis on, as they do for the store job, so such a record is refused too: the store job would put it straight back. Anything else isnot_manual: a paid rail's record is cancelled through that rail. magic-starter:billing:expire-grantsruns hourly while billing is on (withoutOverlapping()andonOneServer(), so the application's scheduler must run). It resolves the concreteActions\AdministerBilling, not the contract, and visits every open grant: an expired one the billable is still on is revoked and closed asexpired, one the billable has moved off (a paid rail or a newer grant took the record) is closed assupersededwith no write. A grant that fails to settle is reported through the exception handler and skipped, the sweep goes on to the next, and the run exits non-zero. A table not migrated yet is skipped with a line.- After a grant ends, by revoke or expiry, the paid rails are re-projected: the Stripe
defaultsubscription through the reconciler, and the store through the authoritative RevenueCat re-read where the rail is configured. A checkout made during the comp was dropped while the comp held the record, and the reconciler never walks a manual record to find it. A store read that fails here leaves the record manual; Sync now is the way back, since it re-reads the store for a manual record no open grant holds.
billing_grants keeps one row per grant (plan, reason, expires_at, granted_by, ended_at, end_reason of expired, revoked or superseded) and outlives the operator and the billable: neither has a cascading foreign key. A fresh magic-starter:install --features=billing publishes create_billing_grants_table.php; an existing application copies it in, see Upgrading. billing:doctor reports it missing as schema.billing_grants.
Stripe operations#
Trial, cancel, resume and refund act on the billable's local default Cashier subscription, whatever plan_provider says: a checkout over a comp leaves the record naming somebody else while Cashier bills the card. Without one they refuse no_subscription. They change Stripe and Cashier's row and leave the entitlement to the webhook that follows, as the customer's own billing endpoints do. A Stripe or Cashier failure is a recorded rail_error.
- Extend trial and End trial work only while the subscription is trialing and not cancelled; a cancelled trial is
already_cancelled, because its end date would go stale. Extend moves the trial end to a future date later than the current one (not_laterotherwise); the date picker starts at the day after the current trial end. End trial ends the trial now, so Stripe bills the customer immediately. - Resume sends
cancel_at_period_end=falseand nothing else. It is deliberately not Cashier'sresume(), which off trial also sendstrial_end: nowand can invoice the customer and move their billing date when all the operator asked for was to lift a cancellation. The live subscription is read first: one cancelled on a fixedcancel_atdate rather than at its period's end would survive that flag, so it is refusedscheduled_canceland is resumed in Stripe. - Refund returns the newest invoice of the local
defaultsubscription withamount_paidabove zero whose payment is a paid payment intent, in full, with the reasonrequested_by_customerorduplicate(fraudulentis not offered: it feeds Stripe's fraud signals and is not a support decision). A one-off invoice, or one of another subscription, is never the target; the invoice's subscription is read fromparent.subscription_details.subscription. That invoice or nothing: if its payment was recorded out of band, or its charge is already refunded in full, an older invoice is never refunded in its place (nothing_refundable). The amount shown and refunded is that payment's own, not the invoice total. The modal reads Stripe once when it opens to name the amount and the invoice, and the refund is bound to the invoice it showed: when a newer one was paid in between, nothing is refunded and the refusal isstale_target. The refund is created under the idempotency keyadmin-refund:{invoice}:{reason}, so a second click or a retry after a timeout is answered with the first refund instead of refunding twice, and theinvoice_refundedrow is written once per refund id with the refund's own amount and currency. The subscription is left as it is. - Sync now reads the rail live: for Stripe, the subscription from the API, which heals the local Cashier row (status, price, quantity, trial end, end date) and its items, and then writes the claim it makes as an authoritative write, like a webhook, so Stripe may take the record over from a comp or a store. The claim is stamped when the read starts, so a webhook landing while it is in flight wins. A granting subscription on a price the catalogue does not map is refused
unmapped_priceand nothing is written. Where the store rail is configured it runs the store job's authoritative re-read under the operator, for a store record and for a record of nobody or a manual one no open grant holds: a store payer can sit behind an ended comp. Each rail leaves anentitlement_syncedrow saying whether the entitlement changed.
Billing authorization#
Billing actions are narrower than panel access: the panel gate has already admitted the admin, and billing authorization only takes actions away. It does not hide data: the Billing tab's history and the two read-only resources below are visible to every panel admin.
MAGIC_STARTER_ADMIN_BILLING_EMAILS(admin.billing_emails), a comma-separated list. Empty, the default, lets every panel admin run the actions. Otherwise only the listed addresses do, compared trimmed and lowercased.MagicStarterPlugin::authorizeBillingUsing(?Closure $callback)replaces the list entirely. The callback receives the panel user and the panel, and only a literaltrueallows.
MagicStarterPlugin::make()
->authorizeBillingUsing(fn (Authenticatable $admin): bool => $admin->can('manage-billing'));
A hidden action cannot be mounted or called, so the check also holds against a crafted Livewire request. Reading the tab is not restricted by it.
Billing events and webhook deliveries#
The plugin registers two read-only resources while billing is on, under the keys billing_events and webhook_deliveries, which MagicStarterPlugin::resource() can replace like any other. Every panel admin sees them; the billing authorization list governs the billing actions only.
- Billing events lists
billing_eventswith its filters (type, source, provider, date range) and a view page with the properties. A row is a reading and is never edited or deleted from the panel; retention is the prune command's job. - Webhook deliveries lists the
processed_webhook_eventsclaims. The table has no provider column, so RevenueCat is derived from the claim prefix and everything else is Stripe. The view page lists the billing events recorded under the delivery id. That join has limits: a delivery that changed nothing has no rows, and rows keyed on a Checkout session or a Stripe subscription id (checkout_started,trial_recorded) never join.
Account Deletion#
A user who owns a team that a rail is still billing, or who is billed directly under user billing, is refused until the subscription ends. The 422 body names the rail per team in team_providers. See Account Deletion.
Upgrading#
The catalogue replaces plans, prices and store_products, and checkout and swap take product instead of plan and cycle. The changelog carries the migration steps.
An application that installed before trials existed and wants to sell one copies vendor/fluttersdk/magic-starter-laravel/database/migrations/create_billing_trials_table.php into database/migrations/ under a timestamp later than your latest migration and runs php artisan migrate, before it sets a trial_days. Do not re-run magic-starter:install for this. An application that sets no trial_days never reads the table and needs neither.
The audit log needs two migrations. Copy create_billing_events_table.php and add_processed_at_index_to_processed_webhook_events_table.php from vendor/fluttersdk/magic-starter-laravel/database/migrations/ into database/migrations/ under timestamps later than your latest migration (or re-run the install command's billing publish) and run php artisan migrate. Until you do, billing keeps working and each worker logs one warning that billing_events is missing; billing:doctor reports it as schema.billing_events.
The admin panel's manual grants need one more migration. Copy create_billing_grants_table.php from vendor/fluttersdk/magic-starter-laravel/database/migrations/ into database/migrations/ under a timestamp later than your latest migration (or re-run the install command's billing publish) and run php artisan migrate. Until you do, a grant cannot be recorded and magic-starter:billing:expire-grants skips with a line; billing:doctor reports it as schema.billing_grants. The command is scheduled hourly by the package, so your scheduler has to be running.
Campaigns need their own migration. Copy create_campaigns_table.php from vendor/fluttersdk/magic-starter-laravel/database/migrations/ into database/migrations/ under a timestamp later than your latest migration (or run php artisan magic-starter:install --features=campaigns) and run php artisan migrate before you add Features::campaigns(); then add checkout.session.completed to your Stripe webhook endpoint (see Attribution).
The per-caller currency needs one more migration. Copy add_billing_currency_to_billable_table.php from vendor/fluttersdk/magic-starter-laravel/database/migrations/ into database/migrations/ under a timestamp later than your latest migration and run php artisan migrate, then set pricing.country_header (see Currency). Every product row of billing/plans now carries currency and only that currency's web price, whether or not you set a header.
The operator side is overridable: Contracts\AdministersBilling is bound to Actions\AdministerBilling unconditionally, so an application binds its own class over the contract to change what the panel's billing actions do. An implementation of the contract takes refundLastInvoice(Authenticatable $actor, Model $billable, string $reason, ?string $expectedInvoiceId = null); the panel passes the invoice its modal showed. The expiry command resolves Actions\AdministerBilling itself (settling a grant is the sweep's step, not an operator's act, and is not on the contract), so bind a subclass over that class as well when the sweep must use yours; its constructor takes the reconciler (ReconcileBillingEntitlements) after the RevenueCat client.
Filament\Support\ContractAction now catches BillingAdministrationRefused: it shows the refusal as a danger notification and halts the action without rolling back the surrounding transaction, since the request_refused row is the only record of the refusal. A custom panel action that runs an AdministersBilling call through ContractAction::run() gets the notification instead of an exception.
Code that builds on the package internals changes in these places:
EntitlementWritenow requiressource:(aBillingSource), andeventId:is optional. An adopter-builtEntitlementWritewithoutsource:throws anArgumentCountError.- A custom
WritesEntitlementrecords throughBillingEventRecorderitself, or the writes it makes leave no row. - A subclass of
StripeWebhookControllerthat overridessubscriptionClaim,revokeEntitlement,reaffirmEntitlementFromInvoiceorwarnUnmappedPriceadds thestring $eventIdparameter those methods gained. Its constructor, likeBillingController's, now takes aBillingEventRecorder. CheckTrialCard::handletakes aBillingEventRecorderparameter, andReconcileBillingEntitlements::reconcileStripeSubjecttakes an optionalBillingSource.BillingController::abortWithBillingConflict()takesModel $billablefirst;StripeWebhookController::existingUserKey()is nowexistingUser()and returns?Model; aWriteEntitlementsubclass with its own constructor callsparent::__construct()so the recorder is set.