Laravel Cashier Stripe for Laravel Rust
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
Use the official laravel/rust-framework and the destination app's pinned revision, not an unrelated Laravel-inspired Rust framework. At inspected revision 8e5cd9b7918d1bc53e1bda85065f3d4a66903118, Laravel supplies the ORM, schema builder, transactions, routing, queues, notifications, and raw body access; no Cashier implementation was found in the inspected framework source/manifests. Stripe examples in its docs demonstrate service wiring, not billing parity.
- Add an app-owned billing module (for example
src/billing/) and model types undersrc/models/. Attach methods or a small billing service to the actual billable model rather than emulating PHP dynamic traits globally. Use#[model],#[has_many]/HasMany<T>, and#[belongs_to]/BelongsTo<T>with explicit foreign keys if the billable owner is not the conventionally named user. - Use
Option<String>for nullable Stripe IDs/summary fields,Option<i64>for nullable quantities, andOption<Timestamp>for nullable dates. Match the existing primary-key type. Rust'stypekeyword needs a mapped field such as#[column("type")] pub subscription_type: String. Includemeter_idandmeter_event_namein the item model. Model serialization derives automatically: hide payment/customer details unless the frontend needs them. - Generate migrations using
laravel make:migration; migration files indatabase/migrationsexposepub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()>, usingtx.schema().create/alter(...).await. Register them through the app's existing build-time migration discovery. They compile into the binary and are forward-only. Preserve schema/baseline rules above. Usedb::transaction(async |_| { ... })andlock_for_update()where needed; SQLite does not provide the same row-lock behavior as production Postgres/MySQL, so test concurrency on the deployed database engine. - Stripe's Rust option inspected here is the community-maintained
arlyon/async-stripe, not an official Stripe Rust SDK. Its current source is modular 1.0.0-rc.10: packageasync-stripeexportsstripe::Client; resource packages includeasync-stripe-core,async-stripe-billing,async-stripe-checkout,async-stripe-payment, andasync-stripe-webhook(librarystripe_webhook). The crates.io sparse index confirms non-yanked rc.10 releases for the client, core, billing, and webhook packages on the research date. Pin a tested compatible release family and commitCargo.lock; do not mix legacy 0.x examples with the modular 1.0 API or copy the README's older rc.5 dependency example unquestioned. - Pin one compatible release family across selected crates and enable resource features for customer, subscriptions/items, invoices/payments, setup/payment intents, portal, Checkout, and meters as actually used. Select the async Tokio-compatible TLS backend; do not use the
blockingfeature on request workers. Instantiate a reusablestripe::Clientthrough Laravel'swith_services/singletonregistration and inject it withInject<T>; keep customer/account/operation information per call, not mutable global state. The SDK's request builders use asynchronoussend(&client).await; verify resource methods against the pinned release. If a required V2 meter endpoint is absent, add only that typed HTTP call through the existing HTTP client with matching auth/version/idempotency semantics rather than stubbing it. - The inspected generated Rust billing-meter request uses
/billing/meter_eventsunder the V1 API, whereas Cashier's usage concern uses/v2/billing/meter_events. No V2 meter-event binding was found in this SDK snapshot. For apps using that Cashier operation, implement and test a narrow JSON POST to the V2 endpoint with the selected Stripe version, authentication/account headers, timeout, stableidentifier, and retry policy; do not silently substitute the differently typed V1 response. This gap does not block apps that do not report usage. - A Laravel handler taking
Requestcan readrequest.content()asOption<&Bytes>andrequest.header("stripe-signature")asOption<&str>. Obtain those before any reserialization; convert UTF-8 without trimming or normalizing. The inspected modular webhook crate exposesstripe_webhook::Webhook::construct_event(payload, signature, secret)and validates HMAC plus an absolute 300-second timestamp window. It warns on API-version mismatch rather than rejecting all mismatches: enforce the app's supported event API contract yourself. Enable webhook resource features for events you match, handle unknown event variants, and translate verification errors to a non-2xx response without panicking. - Keep
/stripe/webhookat its existing path. If registered in the web group, use.without_middleware::<PreventRequestForgery>()for that route only; putRequestlast in the handler argument list. A route in the API group has no CSRF but may acquire an/apiprefix, so do not silently move the endpoint. Keep signature verification even when CSRF is disabled. - Represent payment/incomplete/decline/transport errors as explicit results that the existing frontend can handle. Preserve original entitlement behavior and all used operation/webhook semantics above. Run
cargo fmt --check,cargo check --locked, and the app's tests; test the compiled HTTP route and production-engine transaction behavior, not only detached SDK examples.
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.