Laravel Cashier Stripe inlined into Laravel PHP
This recipe replaces laravel/cashier with application-owned billing logic. Follow the target implementation below; this is implementation guidance, not a tested drop-in billing library.
Researched on 2026-12-03 against Cashier source declaring 16.11.0. The source repository is laravel/cashier-stripe; the Composer package is laravel/cashier. This does not cover Cashier Paddle. Implement the features the destination app actually uses, while retaining its existing Stripe customers, subscriptions, prices, and local billing records.
Preserve Cashier's MIT copyright and permission notice for copied or substantially derived code, including translations. Recipe approval does not replace verification of the destination app's billing migration.
Establish the app's contract before replacing Cashier
- Read the app's
composer.lock, Cashier configuration, published migrations, billable models, custom subscription/item classes, controllers, policies, jobs, notifications, webhook listeners, tests, and frontend payment flows. Inventory references toLaravel\Cashier,Billable,Cashier::, subscription builders, billing portal, Checkout, invoices, payment methods, tax, coupons, usage, and payment confirmation. Follow calls made through user/team models as well as imports. - Identify the billable owner. Cashier defaults to
App\Models\User, but apps can bill teams or another model. Preserve its table, primary-key type, foreign-key name, tenant/account boundaries, and soft-delete lookup behavior.Cashier::findBillableincludes soft-deleted owners; do not silently stop handling their cancellation webhooks. - Record each used operation's inputs, result shape, exception/error behavior, local writes, Stripe request options, and authorization rules. Port that contract; a successful SDK call alone does not replace Cashier. Mark unused features explicitly rather than leaving apparently working no-ops.
- Record test/live mode, any Stripe Connect account scope, secret/publishable key pairing, endpoint signing secret, endpoint URL, Stripe API version, SDK version, price IDs, trial policy, currency/locale, automatic tax, proration, incomplete/past-due flags, and configured payment notification. Never derive price or customer identity from an untrusted browser field.
- The SDK is still a dependency. Rust and Go replace Cashier's PHP logic with native code and a native Stripe client. PHP inlining removes
laravel/cashier, notstripe/stripe-phpor Laravel itself. Do not write a new card-processing or Stripe-signature protocol.
Pin API shapes, not just package names
Cashier at the inspected commit accepts stripe/stripe-php majors 17–21 and sets Cashier::STRIPE_VERSION from that SDK's Stripe\Util\ApiVersion::CURRENT. Its adapter recognizes Basil, Clover, and Dahlia; it does not recognize Endive. The inspected Stripe PHP and Go main branches and async-stripe source already target 2026-11-18.endive. Installing the newest SDK is not evidence that Cashier's adapters or the app's webhook fixtures support its shapes.
Preserve the app's locked SDK and endpoint version for the first PHP extraction. One verified compatible-family reference is stripe-php v21.3.0, whose constant is 2026-08-26.dahlia; this is a source fact, not an instruction to upgrade or downgrade the app. For a native port, select a released SDK supporting the app's required resources, record its generated API version, and either preserve compatible endpoint shapes or perform an explicit API migration with fixtures. Changing an existing Stripe webhook endpoint or account API configuration is a separate rollout action, not a local code edit.
Version-sensitive details to map from the source and actual payloads:
- Modern subscription billing periods are on subscription items. Cashier computes the earliest item period start and latest item period end. Do not require the old subscription-level
current_period_endfield. - Modern invoice subscription references use
parent.subscription_details.subscription; subscription Checkout metadata is underparent.subscription_details.metadata. Invoice payment confirmation involves invoicepayments, PaymentIntents, andlatest_invoice.confirmation_secret; do not assume the legacyinvoice.payment_intentorpayment_intent.invoiceshape. - Coupon and promotion-code nesting changes by API family. In Cashier's adapter, Basil reads
discount.couponandpromotion_code.coupon; Clover/Dahlia readdiscount.source.couponandpromotion_code.promotion.coupon. - Dahlia Checkout changes
hostedtohosted_page,embeddedtoembedded_page, andcustomtoelements. Use the mode accepted by the selected API, not a copied old example. - Usage reporting uses Billing Meter Events, including Cashier's V2 meter-event service, not the removed legacy subscription-item usage-record API.
Preserve Cashier's database projection
Stripe is the billing authority; the local tables project the state the app queries for entitlements. Do not recreate Stripe resources during migration. Preserve local IDs and Stripe IDs, nullability, UTC instants, timestamps, and indexes. Compare the real app schema with the five upstream migration files; older apps may lack the newer meter columns.
| Record | Upstream fields and constraints |
|---|---|
Billable owner, normally users | nullable indexed stripe_id; nullable pm_type; nullable 4-character pm_last_four; nullable timestamp trial_ends_at |
subscriptions | auto ID; owner FK column normally user_id; type; unique stripe_id; stripe_status; nullable stripe_price, integer quantity, timestamps trial_ends_at and ends_at; created_at, updated_at; index on owner FK + stripe_status |
subscription_items | auto ID; subscription_id; unique stripe_id; stripe_product; stripe_price; nullable meter_id, integer quantity, meter_event_name; created_at, updated_at; index on subscription_id + stripe_price |
Upstream uses foreignId columns without adding constrained cascading foreign keys. Do not accidentally introduce cascades or change owner identity while translating. Owner stripe_id is indexed, not unique upstream; audit duplicates before adding a stronger constraint. If several Connect accounts share the database, decide and test whether IDs and event deduplication need account scope rather than silently changing existing uniqueness assumptions.
The owner has many subscriptions ordered by newest created_at; selecting a subscription by type takes the newest matching one, not an arbitrary row or a globally unique type. Each subscription has many items. For exactly one item, project its price and quantity onto the subscription. For multiple items, both parent fields are null and price/product checks consult items. Null metered quantities are not zero or one. Keep the owner's generic trial separate from subscription trial dates.
For an existing database, add only missing columns and any explicitly chosen operational tables; do not replay create-table migrations against live data. Rust and Go migrations are forward-only, unlike PHP migrations with down(). Their migration runners also track names in a migrations table: plan the baseline/import on a disposable database copy so translated historical files do not rerun existing PHP schema changes. Do not use migrate:fresh, drop tables, or rewrite production migration history as a conversion shortcut. MySQL DDL may commit despite an outer transaction.
Reproduce entitlements and subscription transitions
Keep entitlement predicates separate from Stripe's literal status enum. The following describes inspected Cashier behavior, not a recommendation to redesign access policy during conversion. Freeze time in tests and compare the original app and replacement on the same records.
on_trial = trial_ends_at is not null and trial_ends_at > now
on_grace = ends_at is not null and ends_at > now
canceled = ends_at is not null
ended = canceled and not on_grace
active = not ended
and status != incomplete_expired
and status != unpaid
and (not deactivate_incomplete or status != incomplete)
and (not deactivate_past_due or status != past_due)
valid = active or on_trial or on_grace
subscribed = newest subscription of requested type exists and is valid
and (no requested price or subscription has that price)
Both deactivation flags default to true. A generic owner trial can satisfy the owner's trial helpers without a subscription; do not substitute subscribed() for those helpers. At exactly ends_at, grace is over. A scheduled cancellation can remain valid during grace. Cashier's active() does not simply whitelist active and trialing; a paused status with no ending date is not excluded by this predicate. Preserve the app's actual behavior first; any tighter policy for paused/unknown statuses is an explicit, separately tested behavior change.
Implement only used operations, with these semantics:
- Customer creation/retrieval: reuse
stripe_id; create once if absent, then persist the returned ID. Serialize concurrent creation per owner and use a durable operation ID as a Stripe idempotency key. A Stripe success followed by a DB failure must be recoverable without creating a second customer. - Payment methods: use Stripe.js/Elements and SetupIntents as appropriate. Verify the PaymentMethod belongs to or can be attached to the authenticated owner's customer, attach it if needed, and update
customer.invoice_settings.default_payment_method. Refresh local type/last-four from Stripe, including non-card methods and removal of a default. Never store card numbers or CVCs. - Subscription creation: ensure the customer/default method, pass approved prices/items, quantities, trial, metadata
type(and legacynamewhen needed), automatic tax/tax rates, collection method, billing anchor/mode, discounts, and payment behavior. Default Cashier behavior isdefault_incomplete, not unconditional access after creation. Persist subscription and all items from Stripe's response before reporting incomplete-payment action to the caller. Allow webhook reconciliation to find the same subscription by Stripe ID if it arrives first. - Changes: preserve
swap, add/remove price, quantity, pending-update, billing anchor, and explicit proration behavior where used. Identify a Stripe subscription ITEM by itssi_ID when changing it; aprice_ID is not an item ID. Do not overwrite all items when changing one. Reject mutations that the original app rejects while payment is incomplete. Reconcile the resulting item set and parent single-price projection. - Cancellation:
cancel()setscancel_at_period_end=true; localends_atis trial end while on trial, otherwise the latest item period end.cancelAt()uses the returned cancel time.cancelNow()cancels remotely then marks status canceled andends_at=now; invoicing immediately is a distinct option (cancelNowAndInvoice), not an accidental side effect.resume()is allowed only during grace and clears scheduled cancellation/ends_atafter Stripe succeeds, preserving a still-running trial. - SCA/payment failures: distinguish success, requires action, requires payment method, confirmation, decline, pending, and transport failure. Return the PaymentIntent/client confirmation information only to the authorized customer and keep the subscription incomplete until verified state permits access. Preserve any
cashier.paymentconfirmation route, notifications, and safe return-URL checks used by the app. Never treat a Checkout success URL as proof of payment, and do not log client secrets. - Checkout and portal: create sessions server-side for the authorized customer, validated prices, and allowlisted return URLs. Preserve subscription metadata so webhooks recover the type; client reference data alone is insufficient. The portal changes Stripe state asynchronously, so webhook reconciliation remains required. If using Cashier's subscription Checkout trials, preserve its minimum trial adjustment (48 hours plus 10 seconds at session creation) or explicitly replace it with an approved policy.
- Charges, refunds, invoices, coupons, tax, and meters: preserve these if callers use them. Use integer minor units and currency-specific rules rather than float dollars. Preserve refund amount/options, invoice pagination and authorization, discounts and promotion-code validation, tax configuration, and payment method flows. A Stripe-hosted invoice/PDF link can replace custom rendering only if callers accept that contract; otherwise port the renderer/template and formatting. For meters, retain meter ID/event name and send stable usage identifiers across retries, quantity as required by the endpoint, timestamps, and customer payload keys. Do not double-report usage after a timeout. Cashier's default generated UUID per call is not sufficient for retrying the same business usage event across calls.
For each remote write, persist a stable operation key before dispatch and reuse it on retry. Choose a new key only for a new business operation. Configure finite timeouts and bounded retries; preserve account scope and version on retries. A DB transaction cannot roll back a Stripe charge. Separate remote operations from the short local reconciliation transaction, and recover uncertain outcomes by the recorded operation/resource ID rather than blindly reissuing them. Reconcile ambiguous outcomes before the provider's idempotency retention window expires.
Webhooks replace the other half of Cashier
Keep the deployed endpoint path (normally /stripe/webhook), event subscriptions, API version, and signing secret unless rollout explicitly changes them. Verify the signature over the exact request bytes with the endpoint secret, not the API key. Require the secret in production: upstream conditionally installs verification only when configured; this recipe deliberately fails closed instead. Use the SDK verifier and a timestamp tolerance (Cashier default 300 seconds), reject invalid/missing signatures, reject malformed signed payloads, and exempt only this route from browser CSRF checks. Browser billing mutations still need authentication, authorization, and CSRF protection.
The eight events registered by Cashier's command and their responsibilities are:
customer.subscription.created: find the owner by Stripe customer; upsert subscription/items by Stripe IDs, using metadatatype, then legacyname, thendefault; clear the owner's generic trial. Existing subscriptions should not be duplicated by synchronous creation plus webhook delivery.customer.subscription.updated: synchronize status, trial dates, scheduled or immediate cancellation, all current items, removed items, and the parent single-price fields. Upstream deletes the local subscription and items forincomplete_expired; preserve that if matching its contract. Resolve cancellation periods through item periods, not an obsolete parent field.customer.subscription.deleted: clear trial, mark the matching local subscription canceled, and end it now. Do not wait for another invoice event.customer.updatedandpayment_method.automatically_updated: retrieve the current default method and refresh the owner's summary, including clearing absent method details.customer.deleted: end the owner's subscriptions, clear trials, customer ID, and method summaries. Preserve the local owner and audit history. A deleted customer may not be retrievable as an active resource.invoice.payment_action_required: if payment notifications are enabled, notify the authorized billable owner with the payment confirmation path; avoid duplicating the notification for on-session Checkout. The current source retrieves invoice payments and the corresponding PaymentIntent rather than reading a legacy invoice field.invoice.payment_succeeded: current Cashier specifically clears subscription metadatais_on_session_checkoutfor on-session subscription Checkout using the modern invoice parent structure. It is not a universal grant-access handler.
Port the app's custom WebhookReceived/WebhookHandled listeners too, retaining their observable payload/dispatch semantics if used. invoice.payment_failed, checkout.session.completed, asynchronous Checkout success/failure, refunds, disputes, and entitlement events are NOT among Cashier's eight defaults; register and handle them if the app relies on them. Avoid claiming the base controller fulfills arbitrary order-fulfillment needs.
Stripe delivery is at least once and unordered. Upstream's controller is not a durable event inbox. This recipe recommends adding one for all three targets; that is an intentional reliability improvement, not an upstream behavior claim:
- After verification, persist an inbox row with unique event ID (plus account/mode scope if needed), event type, object ID, receipt time, processing state, attempts, and the minimum replayable payload. Encrypt or restrict retained payloads, redact logs, and define retention. Do not mark a row processed before projection writes commit.
- Return 2xx only after durable acceptance, or after successful synchronous processing. If durability fails, return a retryable failure. Duplicate persisted events can return 2xx; failed/pending rows must remain eligible for processing. An unknown verified event can be acknowledged without altering billing state.
- Run a serialized reconciler per affected billing aggregate so two concurrent workers cannot apply snapshots out of order. Retrieve current Stripe subscription/customer state for ordinary updates and paginate full item collections before replacing items. A fetched snapshot outside serialization can become stale before it is written; a local row lock alone after the fetch does not solve that race. Do not rank subscription state by event ID or rely solely on second-resolution
event.createdtimestamps. - Use a short DB transaction to upsert the projection, reconcile removed items, and mark inbox completion atomically. Retry-safe side effects such as notifications/fulfillment need their own unique business keys and durable outbox, dispatched after commit. Delete events need explicit handling: use the verified deletion payload/current resource status and prevent an older update from resurrecting deleted billing state.
- Unknown owners are not a reason to create a user from webhook email. Upstream acknowledges them; a reliable replacement can retain them as unresolved for replay/reconciliation after customer mapping commits. Separate test/live/account events and alert on persistent mapping failures. Keep a repair command that reconciles a known owner/subscription from Stripe without charging it again.
Target implementation
Keep Laravel and the app's locked Stripe PHP SDK. Move only the needed Cashier behavior under application ownership, for example App\Billing; removing the Composer package alone removes traits, models, controllers, routes, configuration defaults, views, commands, bindings, and events it supplied.
Laravel PHP framework 13.x source was checked at 1b57d01aa866b042a75683bd9ef3517008c632fc (declares 13.45.0), including middleware configuration and Eloquent/provider infrastructure. Cashier's inspected manifest supports Laravel 12 and 13; keep the destination app's installed Laravel version rather than requiring an upgrade to the reference revision.
- Build the used-feature inventory above before removing the package. Choose either a narrow app billing service preserving the used contract, or copy the transitive closure of the exact installed Cashier classes for a broad API-compatible extraction. Do not copy just
Billable.php: it composes seven concerns which depend on subscription builders, wrappers, exceptions,Cashierstate, events, and other classes. Derive the closure from the installed version, including subclasses and string class names in configuration. - Rename copied namespaces/imports from
Laravel\CashiertoApp\Billingconsistently, including custom models,Cashier::$customerModel/subscription/item class references, type hints, event listeners, notification and queued job class names, route actions, Blade references, and config strings. Do not leave code referring to a removed vendor namespace or add an autoload alias that hides a missing implementation. Where queued serialized jobs still name the old classes, drain or migrate those jobs as a planned cutover step before removal. - Preserve the MIT copyright and permission notice from the exact Cashier source for copied/substantially derived code, including Rust/Go translations where applicable. Keep
stripe/stripe-phpas a direct Composer requirement compatible with the current lockfile. Keep transitive libraries now used directly by copied code (moneyphp/money, Carbon, polyfills, renderer dependencies) explicitly, rather than assuming they survive dependency removal. Do not copy Cashier's provider wholesale without auditing what it registers or copy the package's development-only dependency settings. - Rewire the billable model to the app-owned trait/service and models. Keep its relationships, casts, newest-subscription ordering, soft-delete lookup, generic trials, policy flags, and persisted schema. Published migrations remain application history; do not delete or rerun them. Add only verified missing columns. Preserve method return/exception contracts used by controllers and policies; do not replace
valid()with a simpler status test. - Register configuration, the reusable
Stripe\StripeClient, and any invoice renderer/logger in an app provider listed inbootstrap/providers.php(or that app's Laravel-version equivalent). PreserveSTRIPE_KEY,STRIPE_SECRET,STRIPE_WEBHOOK_SECRET, currency, locale, path, tolerance, notification configuration, tax flags, and safe logging. Explicitly set the chosen API version. Do not identify the app-owned extraction as upstream Laravel Cashier in Stripe app metadata. - Define the webhook and any payment-confirmation routes that were formerly package-owned. Preserve names such as
cashier.webhookandcashier.paymentif callers generate their URLs; preserving route names does not require preserving vendor classes. In Laravel 12, exempt only the webhook path withvalidateCsrfTokens(except: ['stripe/webhook'])inbootstrap/app.php; Laravel 13 providespreventRequestForgery(except: ['stripe/webhook'])and retains the earlier method as a deprecated alias. Alternatively, define the route outside browser middleware without changing the public path. Keep browser mutations under auth/policies/CSRF and retain safe redirect checks. - Verify the webhook with
Stripe\Webhook::constructEvent($request->getContent(), $request->header('Stripe-Signature'), $secret, $tolerance)or the pinned SDK signature verifier before decoding/dispatching it. Require a configured secret; retain the events and reconciliation semantics above. If copying the upstream controller, document that idempotent upserts alone do not provide durable replay/order handling; add the inbox/outbox design where required instead of claiming it came from Cashier. - Copy/rewrite needed payment and invoice Blade templates into app-owned views, replace
cashier::names or register an explicit view namespace, register notifications/jobs/events, and replace the webhook console command if operations use it. A custom invoice renderer and a Stripe-hosted PDF link are not automatically equivalent. Authenticate payment/invoice resource ownership before returning private data or client secrets. - Replace call sites and test while Cashier is still installed, ensuring tests actually instantiate app-owned classes rather than vendor ones. Then remove
laravel/cashierwith a lockfile update in a disposable/local environment. Rebuild Composer autoload/package discovery and clear/rebuild app config/route/view caches as appropriate. Verifycomposer show laravel/cashierreports not installed and search source/config/routes/views/tests for residual vendor namespace references; the command's expected absence exit code is not a failed migration. Historical migration comments/notices can still name the package. - Run the app's PHP unit/feature tests, static checks and
composer audit, inspectphp artisan route:list --path=stripe, and boot the app after package removal. Run the shared acceptance checks below through the real routes and jobs. Package removal is not complete if anything still relies on Cashier auto-discovery, a cached route, a pending old-namespace job, or a vendor view.
Acceptance checks for this target
Use a disposable copy of the app database and Stripe test mode. Record SDK/API versions and use signed fixtures captured for those versions; stripe-mock or happy-path HTTP stubs alone cannot prove real payment or webhook behavior. Do not run these against live customers or claim this recipe has executed them in the destination app.
- Existing-owner migration: load a non-default billable model/key, soft-deleted owner, generic trial, multiple same-type subscriptions with different creation times, single-price and multi-price subscriptions, null metered quantity, and older schema missing meter columns. Confirm IDs, row counts, uniqueness, dates, and entitlement results remain unchanged. Run baseline migration on a restored database, then run migrate again and expect no duplicate schema/data changes.
- Entitlements at one second before, exactly at, and one second after trial/grace end; active, trialing, incomplete, incomplete_expired, past_due, unpaid, canceled, and paused status; deactivation flags on/off; requested matching/nonmatching price. Compare public results with the original app, including canceled-yet-valid grace and the newest subscription of each type.
- Signed webhook security: correct raw JSON with whitespace and Unicode passes; reserialized/tampered bytes, missing/wrong secret/signature, stale timestamp, wrong account/mode, and malformed signed JSON do not mutate billing data. Browser CSRF still rejects unrelated unprotected mutations while the signed provider webhook reaches its handler.
- Replay/races: same event twice and concurrently yields one projection/notification; webhook arrives before synchronous subscription save; update before create; stale update after cancellation/deletion; missing owner becomes resolvable later; Stripe API failure, DB failure, process crash before/after inbox commit, and worker retry. Assert eventual state, no resurrection, no duplicated charges/customers/usage, and that a 2xx means durable acceptance. Test full item pagination and removal, not just an event containing one item.
- Stripe test-mode flows: create/reuse customer, SetupIntent/default method, subscription success, action-required and declined payment, one-to-many item transition, quantity/proration, cancel during trial, period-end cancel/resume, immediate cancel with/without invoicing, portal change, Checkout completion, and failed/async payment if used. Check both Stripe state and local entitlements; a redirect or 200 response is insufficient.
- Feature-specific checks for every used extra: exact minor-unit charge/refund amounts and currencies; private invoice access, PDF and pagination; coupon/promotion nesting for the chosen API; tax; stable usage event IDs and V2 support; notification suppression for on-session Checkout; metadata clearing after invoice success; custom webhook listeners and payment return URL restrictions.
- Document cutover: one active fulfillment path, no competing old/new listeners producing duplicate business side effects, backlog replay/repair ownership, secrets available in the new runtime, and a rollback that does not roll back Stripe charges or delete billing tables. Reusing the existing webhook URL avoids an endpoint migration; if a new endpoint is necessary, obtain approval and test its version/secret before switching delivery. Do not disable the working endpoint before the replacement accepts and durably processes events.
Sources and verification limits
The recipe was researched from source, not inferred from framework names. Its snippets are API/algorithm guidance, not a complete compiled billing implementation. No destination application or Stripe credentials were supplied, so no native port, PHP extraction, live payment, or end-to-end migration is claimed tested. The acceptance checks are work the implementing agent must execute in that app.
- Cashier source snapshot:
composer.json,src/Billable.php,src/Cashier.php,src/Subscription.php,src/SubscriptionItem.php,src/SubscriptionBuilder.php, concerns, service provider, config, routes, all five migrations, webhook/payment controllers and middleware,Console/WebhookCommand.php,UPGRADE.md, and unit/feature test cases. Webhook controller, API adapter, license. - Laravel Rust framework snapshot:
docs/models.md,model-relationships.md,migrations.md,queries.md,requests.md,csrf.md,routing.md,container.md; request implementationcrates/http/src/http/request.rsand database primitives undercrates/database/src/. - Laravel Go framework snapshot: the corresponding model/migration/query/request/CSRF/routing/service docs,
model/write.go,model/query.go,db/tx.go,web/request.go; Go application skeleton for layout and dependency/toolchain requirements (the destination app's lockfile remains authoritative). - Laravel PHP framework snapshot: Laravel 13.x framework reference, including
src/Illuminate/Foundation/Configuration/Middleware.php; the app's installed Laravel 12/13 version remains authoritative. Pinned Go skeleton for the checked toolchain and migration registration. - Stripe Go snapshot: README,
api_version.go,params.go,webhook/client.go. v84.1.0 API constant. - async-stripe snapshot: workspace/crate manifests, generated shared API version, modular resource features, async client,
async-stripe-webhook/src/webhook.rs, examples and webhook documentation. This is a community SDK and a release-candidate API at the inspected source. - Stripe PHP snapshot: generated API version; v21.3.0 API constant for the checked Dahlia family reference.
Before cutover, have the app's billing owner review entitlement parity, the deliberate fail-closed signature and durable-inbox choices, and the recorded acceptance-check results.