{"id":395,"date":"2026-11-16T17:00:00","date_gmt":"2026-11-16T12:00:00","guid":{"rendered":"https:\/\/www.shaz3e.com\/blog\/?p=395"},"modified":"2026-11-20T21:41:19","modified_gmt":"2026-11-20T16:41:19","slug":"laravel-cashier-stripe","status":"publish","type":"post","link":"https:\/\/www.shaz3e.com\/blog\/laravel-cashier-stripe\/","title":{"rendered":"Subscription Billing with Laravel Cashier and Stripe"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Subscription billing is the part of a SaaS app you can&#8217;t ship half-done. <strong>Laravel Cashier Stripe<\/strong> integration gives you a clean API for the happy path (start a trial, charge monthly, swap plans), but the work that matters sits around it: who gets into the app while a card is failing, what happens when someone cancels in week two, and how your database finds out that Stripe changed something. This post builds that around Cashier, with original code and tests that run without touching Stripe.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s the billing side of the product architecture I described in the <a href=\"https:\/\/www.shaz3e.com\/blog\/multi-tenant-saas-architecture\/\">multi-tenant SaaS architecture guide<\/a>. I&#8217;ll cover plans, a trial, access gating, plan changes with proration, cancellation, and webhooks, including one event Cashier doesn&#8217;t handle for you. The official <a href=\"https:\/\/laravel.com\/docs\/billing\" target=\"_blank\" rel=\"noopener\">Cashier documentation<\/a> remains the reference for everything not shown here.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"contents\">What this post covers<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li><a href=\"#versions\">Tested versions<\/a><\/li>\n\n\n<li><a href=\"#setup\">Setting up Cashier<\/a><\/li>\n\n\n<li><a href=\"#plans\">Keeping plans in one place<\/a><\/li>\n\n\n<li><a href=\"#subscribe\">Starting a subscription with a trial<\/a><\/li>\n\n\n<li><a href=\"#gate\">Gating access: trials, grace periods and past due<\/a><\/li>\n\n\n<li><a href=\"#swap\">Changing plans and proration<\/a><\/li>\n\n\n<li><a href=\"#cancel\">Cancelling without cutting people off<\/a><\/li>\n\n\n<li><a href=\"#webhooks\">Webhooks and failed payments<\/a><\/li>\n\n\n<li><a href=\"#testing\">Testing without calling Stripe<\/a><\/li>\n\n\n<li><a href=\"#limits\">What I did not test<\/a><\/li>\n\n\n<li><a href=\"#faq\">FAQ<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"versions\">Tested versions<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Tool<\/th><th>Version<\/th><\/tr><\/thead><tbody><tr><td>Laravel Framework<\/td><td>13.43.0 (fresh <code>laravel\/laravel<\/code> skeleton)<\/td><\/tr><tr><td>Laravel Cashier<\/td><td>16.11.0<\/td><\/tr><tr><td>stripe\/stripe-php<\/td><td>21.3.3 (installed by Cashier)<\/td><\/tr><tr><td>PHP<\/td><td>8.4.27 CLI<\/td><\/tr><tr><td>PHPUnit<\/td><td>12.5.43: 22 billing tests passing (24 tests, 62 assertions in the whole app)<\/td><\/tr><tr><td>Database<\/td><td>SQLite in memory for tests<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">My test box had no <code>bcmath<\/code> extension, which Cashier&#8217;s money library requires, so I installed <code>phpseclib\/bcmath_compat<\/code> there to get past Composer&#8217;s check. On a real server, enable <code>ext-bcmath<\/code> instead and skip the polyfill. The tests never call Stripe&#8217;s servers, as explained in the testing section below.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"setup\">Setting up Cashier<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Install the package, publish its migrations, and migrate. The migrations add customer columns to <code>users<\/code> and create the <code>subscriptions<\/code> and <code>subscription_items<\/code> tables.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>composer require laravel\/cashier\nphp artisan vendor:publish --tag=\"cashier-migrations\"\nphp artisan migrate<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Add the <code>Billable<\/code> trait to the model that pays. Here it&#8217;s <code>User<\/code>, but if your customer is a team or workspace, put it there instead. That is a tenancy decision, not a billing one. Then add your keys to <code>.env<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>STRIPE_KEY=pk_test_...\nSTRIPE_SECRET=sk_test_...\nSTRIPE_WEBHOOK_SECRET=whsec_...\nSTRIPE_PRICE_STARTER=price_...\nSTRIPE_PRICE_GROWTH=price_...<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>#[Fillable(['name', 'email', 'password'])]\n#[Hidden(['password', 'remember_token'])]\nclass User extends Authenticatable\n{\n    \/** @use HasFactory&lt;UserFactory&gt; *\/\n    use Billable, HasFactory, Notifiable;\n\n    protected function casts(): array\n    {\n        return [\n            'email_verified_at' =&gt; 'datetime',\n            'password' =&gt; 'hashed',\n        ];\n    }\n\n    \/** The plan on the user's default subscription, or null. *\/\n    public function currentPlan(): ?Plan\n    {\n        return Plan::fromPriceId($this-&gt;subscription('default')?-&gt;stripe_price);\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>currentPlan()<\/code> helper at the bottom is mine, not Cashier&#8217;s. It turns the price ID stored on the subscription back into an enum, so the rest of the app never compares raw <code>price_...<\/code> strings.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"plans\">Keeping plans in one place<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A price ID belongs in config, not scattered through controllers. A small config file and a backed enum give you one place to look and one place to test:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\n\nreturn [\n    \/\/ One entry per plan. The Stripe price IDs come from your dashboard.\n    'plans' =&gt; [\n        'starter' =&gt; ['price' =&gt; env('STRIPE_PRICE_STARTER')],\n        'growth' =&gt; ['price' =&gt; env('STRIPE_PRICE_GROWTH')],\n    ],\n\n    'trial_days' =&gt; 14,\n];<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\n\nnamespace App\\Enums;\n\nenum Plan: string\n{\n    case Starter = 'starter';\n    case Growth = 'growth';\n\n    public function priceId(): string\n    {\n        return config(\"billing.plans.{$this-&gt;value}.price\")\n            ?? throw new \\RuntimeException(\"No Stripe price configured for {$this-&gt;value}.\");\n    }\n\n    public static function fromPriceId(?string $priceId): ?self\n    {\n        foreach (self::cases() as $plan) {\n            if ($priceId !== null &amp;&amp; config(\"billing.plans.{$plan-&gt;value}.price\") === $priceId) {\n                return $plan;\n            }\n        }\n\n        return null;\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If a price is missing from <code>.env<\/code>, <code>priceId()<\/code> throws straight away. I&#8217;d rather get a clear error than send a null price to Stripe.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"subscribe\">Starting a subscription with a trial<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The controller validates the plan against the enum, refuses to create a second subscription, and starts a card-on-file trial. Cashier creates the Stripe customer if there isn&#8217;t one, attaches the payment method, and creates the subscription:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function store(Request $request): RedirectResponse\n{\n    $data = $request-&gt;validate([\n        'plan' =&gt; ['required', Rule::enum(Plan::class)],\n        'payment_method' =&gt; ['required', 'string'],\n    ]);\n\n    $user = $request-&gt;user();\n\n    abort_if($user-&gt;subscribed('default'), 409, 'Already subscribed.');\n\n    try {\n        $user-&gt;newSubscription('default', Plan::from($data['plan'])-&gt;priceId())\n            -&gt;trialDays(config('billing.trial_days'))\n            -&gt;create($data['payment_method']);\n    } catch (IncompletePayment $e) {\n        \/\/ 3D Secure or similar: send them to Cashier's confirmation page.\n        return redirect()-&gt;route('cashier.payment', [\n            $e-&gt;payment-&gt;id,\n            'redirect' =&gt; route('billing.show'),\n        ]);\n    }\n\n    return redirect()-&gt;route('billing.show');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>IncompletePayment<\/code> is thrown when a charge needs extra confirmation, such as 3D Secure. Cashier ships a payment page for that, which is what the redirect points to. Because this is a trial, the first charge happens when the trial ends. Any extra confirmation needed then reaches you through the <code>invoice.payment_action_required<\/code> webhook, which Cashier has a handler for.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This test asserts what was actually sent to Stripe: the right price, a trial end about 14 days away, and a local subscription that reports as trialing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function test_subscribing_starts_a_trial_on_the_chosen_plan(): void\n{\n    $user = User::factory()-&gt;create();\n\n    $this-&gt;actingAs($user)\n        -&gt;post('\/billing\/subscribe', ['plan' =&gt; 'starter', 'payment_method' =&gt; 'pm_card_visa'])\n        -&gt;assertRedirect('\/billing');\n\n    $sent = $this-&gt;stripe-&gt;sent('post', '\/v1\/subscriptions')[0]['params'];\n    $this-&gt;assertSame('price_starter_test', $sent['items'][0]['price']);\n    $this-&gt;assertEqualsWithDelta(now()-&gt;addDays(14)-&gt;timestamp, $sent['trial_end'], 5);\n\n    $subscription = $user-&gt;fresh()-&gt;subscription('default');\n    $this-&gt;assertTrue($subscription-&gt;onTrial());\n    $this-&gt;assertSame(Plan::Starter, $user-&gt;fresh()-&gt;currentPlan());\n    $this-&gt;assertSame('cus_fake_1', $user-&gt;fresh()-&gt;stripe_id);\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"gate\">Gating access: trials, grace periods and past due<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Cashier&#8217;s <code>subscribed()<\/code> check is the right gate for most apps, because it already counts a trial and a cancellation grace period as valid. A thin middleware wraps it so you can return a redirect for browsers and a 402 for API clients:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class EnsureSubscribed\n{\n    public function handle(Request $request, Closure $next): Response\n    {\n        \/\/ subscribed() is true while trialing, active, or on a cancellation grace period.\n        if ($request-&gt;user()?-&gt;subscribed('default')) {\n            return $next($request);\n        }\n\n        if ($request-&gt;expectsJson()) {\n            return response()-&gt;json(['message' =&gt; 'An active subscription is required.'], 402);\n        }\n\n        return redirect()-&gt;route('billing.show')\n            -&gt;with('status', 'Choose a plan to keep using the app.');\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how the states I tested map to access:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Subscription state<\/th><th>Gets in?<\/th><\/tr><\/thead><tbody><tr><td>No subscription<\/td><td>No, redirected to billing (402 for JSON)<\/td><\/tr><tr><td><code>active<\/code><\/td><td>Yes<\/td><\/tr><tr><td><code>trialing<\/code> with a future <code>trial_ends_at<\/code><\/td><td>Yes<\/td><\/tr><tr><td>Cancelled, <code>ends_at<\/code> in the future (grace period)<\/td><td>Yes<\/td><\/tr><tr><td>Cancelled, <code>ends_at<\/code> in the past<\/td><td>No<\/td><\/tr><tr><td><code>past_due<\/code><\/td><td>No, by default<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The last row is a product decision. By default Cashier treats <code>past_due<\/code> as not valid, so a customer whose renewal failed loses access immediately. Some teams prefer a few days of leeway. Cashier has a static <code>Cashier::keepPastDueSubscriptionsActive()<\/code> switch for that, and the Cashier docs cover it. I kept the strict default and tested it, so the choice is visible instead of accidental.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep this gate for &#8220;is the account paid up&#8221; and nothing else. Per-plan features such as seat limits belong in a separate check, and gradual rollouts of those features belong with <a href=\"https:\/\/www.shaz3e.com\/blog\/feature-flags-saas\/\">feature flags<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"swap\">Changing plans and proration<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>swap()<\/code> moves a subscription to another price. By default Cashier asks Stripe to create prorations, so the customer is credited for the unused part of the old price and charged for the new one on the next invoice. The controller lets a caller opt out for downgrades, where you may prefer the new price to start cleanly at the next cycle:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function update(Request $request): RedirectResponse\n{\n    $data = $request-&gt;validate([\n        'plan' =&gt; ['required', Rule::enum(Plan::class)],\n        'prorate' =&gt; ['sometimes', 'boolean'],\n    ]);\n\n    $subscription = $request-&gt;user()-&gt;subscription('default');\n    abort_if($subscription === null, 404);\n\n    \/\/ Prorate by default. A downgrade can opt out and simply start on the next invoice.\n    if ($request-&gt;boolean('prorate', true) === false) {\n        $subscription-&gt;noProrate();\n    }\n\n    $subscription-&gt;swap(Plan::from($data['plan'])-&gt;priceId());\n\n    return redirect()-&gt;route('billing.show');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Two tests pin the behavior down. One asserts <code>proration_behavior<\/code> is <code>create_prorations<\/code> and the local price changes; the other asserts it is <code>none<\/code> when <code>prorate=false<\/code>. The <a href=\"https:\/\/docs.stripe.com\/billing\/subscriptions\/prorations\" target=\"_blank\" rel=\"noopener\">Stripe proration guide<\/a> describes what each option does on the invoice. Also note that swapping a subscription that is still in its trial keeps the original trial end, because Cashier passes it back to Stripe.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function test_changing_plan_prorates_by_default(): void\n{\n    $user = $this-&gt;subscribedUser();\n\n    $this-&gt;actingAs($user)-&gt;patch('\/billing\/plan', ['plan' =&gt; 'growth'])-&gt;assertRedirect('\/billing');\n\n    $params = $this-&gt;stripe-&gt;sent('post', '\/v1\/subscriptions\/sub_fake_1')[0]['params'];\n    $this-&gt;assertSame('create_prorations', $params['proration_behavior']);\n    $this-&gt;assertSame('price_growth_test', $params['items'][0]['price']);\n    $this-&gt;assertSame(Plan::Growth, $user-&gt;fresh()-&gt;currentPlan());\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"cancel\">Cancelling without cutting people off<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>cancel()<\/code> doesn&#8217;t end the subscription now. It sets <code>cancel_at_period_end<\/code> on Stripe and stores an <code>ends_at<\/code> locally, which is the end of the paid period, or the end of the trial if they were still on one. Until that date the user is on a grace period and still passes <code>subscribed()<\/code>. That is the behavior people expect from &#8220;cancel my plan&#8221;, and the test checks both halves: the flag that went to Stripe and the grace period that opened locally.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function test_cancelling_keeps_access_until_the_trial_ends(): void\n{\n    $user = $this-&gt;subscribedUser();\n\n    $this-&gt;actingAs($user)-&gt;delete('\/billing')-&gt;assertRedirect('\/billing');\n\n    $params = $this-&gt;stripe-&gt;sent('post', '\/v1\/subscriptions\/sub_fake_1')[0]['params'];\n    $this-&gt;assertSame('true', $params['cancel_at_period_end']);\n\n    $subscription = $user-&gt;fresh()-&gt;subscription('default');\n    $this-&gt;assertTrue($subscription-&gt;onGracePeriod());\n    $this-&gt;assertTrue($user-&gt;fresh()-&gt;subscribed('default'));\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"webhooks\">Webhooks and failed payments<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Your database only knows what Stripe tells it. Renewals, failed charges, cancellations from the Stripe dashboard and card updates all arrive as webhooks, so this is the part of laravel cashier stripe setups that deserves the most care. Cashier registers a <code>POST \/stripe\/webhook<\/code> route and mirrors subscription events into your tables. Three things to set up:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li>Exclude the route from CSRF checks: <code>$middleware->validateCsrfTokens(except: ['stripe\/*'])<\/code> in <code>bootstrap\/app.php<\/code>.<\/li>\n\n\n<li>Set <code>STRIPE_WEBHOOK_SECRET<\/code>. When it is set, Cashier verifies the signature and rejects anything unsigned. That&#8217;s the same idea as in my guide to <a href=\"https:\/\/www.shaz3e.com\/blog\/webhook-signature-verification\/\">verifying and processing webhooks safely<\/a>.<\/li>\n\n\n<li>Extend Cashier&#8217;s controller for anything it doesn&#8217;t cover.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Cashier has handlers for subscription created, updated and deleted, customer updates, <code>invoice.payment_succeeded<\/code> and <code>invoice.payment_action_required<\/code>, among others. It has no handler for <code>invoice.payment_failed<\/code>, which is the one that tells you a renewal charge was declined. Cashier finds a handler by turning the event name into a method name, so adding one is a single method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class StripeWebhookController extends CashierController\n{\n    \/**\n     * Cashier does not handle invoice.payment_failed, so we add it.\n     * Cashier finds this method by turning the event type into a name.\n     *\/\n    protected function handleInvoicePaymentFailed(array $payload): Response\n    {\n        $invoice = $payload['data']['object'];\n\n        if ($user = $this-&gt;getUserByStripeId($invoice['customer'])) {\n            $user-&gt;notify(new PaymentFailed(\n                attempt: (int) ($invoice['attempt_count'] ?? 1),\n                amountDue: (int) $invoice['amount_due'],\n                currency: $invoice['currency'],\n                invoiceUrl: $invoice['hosted_invoice_url'] ?? null,\n            ));\n        }\n\n        return $this-&gt;successMethod();\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To use the subclass, register the same method and URI in <code>routes\/web.php<\/code>. Your route is registered later than Cashier&#8217;s, so it replaces it, and the test below proves ours is the one that runs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Route::post('\/stripe\/webhook', [StripeWebhookController::class, 'handleWebhook'])\n    -&gt;name('cashier.webhook');<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The notification formats the amount from minor units and links to Stripe&#8217;s hosted invoice page, where the customer can fix their card. It is a plain notification, so you can implement <code>ShouldQueue<\/code> on it and let your <a href=\"https:\/\/www.shaz3e.com\/blog\/laravel-queue-workers\/\">queue workers<\/a> send the email.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function toMail(object $notifiable): MailMessage\n{\n    $amount = number_format($this-&gt;amountDue \/ 100, 2).' '.strtoupper($this-&gt;currency);\n\n    return (new MailMessage)\n        -&gt;subject('Your payment did not go through')\n        -&gt;line(\"We could not collect {$amount} (attempt {$this-&gt;attempt}).\")\n        -&gt;when($this-&gt;invoiceUrl, fn (MailMessage $m) =&gt; $m-&gt;action('Update your card', $this-&gt;invoiceUrl));\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The webhook tests build a real signed request, using the same <code>t=...,v1=...<\/code> HMAC format Stripe sends, and check five outcomes: a wrong signature gets a 403 and writes nothing; a dashboard-created subscription is mirrored locally; a deleted subscription ends access; an update to <code>past_due<\/code> closes the gate; and a failed payment emails the right customer with the right amount.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>private function sendEvent(string $type, array $object, ?string $secret = self::SECRET)\n{\n    $payload = json_encode(['id' =&gt; 'evt_1', 'type' =&gt; $type, 'data' =&gt; ['object' =&gt; $object]]);\n    $timestamp = time();\n    $signature = hash_hmac('sha256', \"{$timestamp}.{$payload}\", $secret);\n\n    return $this-&gt;call('POST', '\/stripe\/webhook', [], [], [], [\n        'CONTENT_TYPE' =&gt; 'application\/json',\n        'HTTP_STRIPE_SIGNATURE' =&gt; \"t={$timestamp},v1={$signature}\",\n    ], $payload);\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>public function test_a_failed_payment_emails_the_customer(): void\n{\n    Notification::fake();\n    $user = User::factory()-&gt;create(['stripe_id' =&gt; 'cus_wh_1']);\n\n    $this-&gt;sendEvent('invoice.payment_failed', [\n        'customer' =&gt; 'cus_wh_1',\n        'attempt_count' =&gt; 2,\n        'amount_due' =&gt; 4900,\n        'currency' =&gt; 'usd',\n        'hosted_invoice_url' =&gt; 'https:\/\/pay.example.test\/inv_1',\n    ])-&gt;assertOk();\n\n    Notification::assertSentTo($user, PaymentFailed::class, function (PaymentFailed $n) use ($user) {\n        $mail = $n-&gt;toMail($user);\n\n        return $n-&gt;attempt === 2\n            &amp;&amp; $n-&gt;amountDue === 4900\n            &amp;&amp; str_contains(implode(' ', $mail-&gt;introLines), '49.00 USD');\n    });\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Webhooks can arrive twice, or out of order. Cashier&#8217;s subscription handlers look rows up by Stripe ID, so a repeated event doesn&#8217;t create duplicates. If you add side effects of your own, such as sending that email, decide whether sending twice is acceptable or store the event ID and skip repeats.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"testing\">Testing without calling Stripe<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Cashier talks to Stripe through the official SDK, and the SDK lets you swap its HTTP client. My <code>FakeStripe<\/code> class implements that one-method interface, records every request, and returns canned JSON for the handful of endpoints the flow needs. Tests can then assert on what Cashier sent. This is the same idea as <a href=\"https:\/\/www.shaz3e.com\/blog\/laravel-http-fake\/\"><code>Http::fake<\/code><\/a> for Laravel&#8217;s own HTTP client, one level down.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class FakeStripe implements ClientInterface\n{\n    \/** @var list&lt;array{method: string, path: string, params: array}&gt; *\/\n    public array $requests = [];\n\n    private array $items = [];\n\n    public static function install(): self\n    {\n        $fake = new self;\n        ApiRequestor::setHttpClient($fake);\n\n        return $fake;\n    }\n\n    public function request($method, $absUrl, $headers, $params, $hasFile, $apiMode = 'v1', $maxNetworkRetries = null)\n    {\n        $path = parse_url($absUrl, PHP_URL_PATH);\n        $this-&gt;requests[] = ['method' =&gt; $method, 'path' =&gt; $path, 'params' =&gt; $params ?? []];\n\n        $body = match (true) {\n            $method === 'post' &amp;&amp; $path === '\/v1\/customers' =&gt; $this-&gt;customer(),\n            in_array($method, ['get', 'post'], true) &amp;&amp; str_starts_with($path, '\/v1\/customers\/') =&gt; $this-&gt;customer(),\n            str_starts_with($path, '\/v1\/payment_methods\/') =&gt; $this-&gt;paymentMethod($path),\n            $method === 'post' &amp;&amp; $path === '\/v1\/subscriptions' =&gt; $this-&gt;createSubscription($params),\n            $method === 'get' &amp;&amp; str_starts_with($path, '\/v1\/subscriptions\/') =&gt; $this-&gt;subscription('trialing'),\n            $method === 'post' &amp;&amp; str_starts_with($path, '\/v1\/subscriptions\/') =&gt; $this-&gt;updateSubscription($params),\n            $method === 'get' &amp;&amp; str_starts_with($path, '\/v1\/subscription_items\/') =&gt; $this-&gt;subscriptionItem(),\n            default =&gt; throw new \\RuntimeException(\"Unexpected Stripe call: $method $path\"),\n        };\n\n        return [json_encode($body), 200, []];\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A call it doesn&#8217;t know throws, which means a new Cashier call in a future version fails loudly instead of silently passing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"limits\">What I did not test<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li>Real Stripe responses. The fake returns the fields Cashier reads, not everything Stripe sends. Before launch, run the same flows once in Stripe&#8217;s test mode with its test cards.<\/li>\n\n\n<li>The 3D Secure path. <code>IncompletePayment<\/code> and Cashier&#8217;s confirmation page need Stripe&#8217;s real confirmation step.<\/li>\n\n\n<li>Stripe&#8217;s retry schedule for failed invoices. That is configured in the Stripe dashboard, not in your code, so your tests should only cover how you react to its events.<\/li>\n\n\n<li>Taxes, invoices as PDFs, and metered billing. Cashier supports them, and none are used here.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq\">FAQ<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-trial\">How do I add a free trial with Laravel Cashier?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Call <code>trialDays()<\/code> on the subscription builder before <code>create()<\/code>. Cashier sends the trial end to Stripe and stores <code>trial_ends_at<\/code> on the local subscription, so <code>onTrial()<\/code> and <code>subscribed()<\/code> are true until it passes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-webhook\">Do I need webhooks if Cashier already updates the subscription?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Cashier updates your database during requests you make, such as subscribing or swapping. Renewals, failed charges and dashboard changes happen without a request from your app, and only webhooks tell you about them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-failed\">What happens to access when a renewal payment fails?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The subscription becomes <code>past_due<\/code> after Stripe&#8217;s webhook arrives, and with Cashier&#8217;s default it stops counting as valid. You can keep it valid for a while with <code>Cashier::keepPastDueSubscriptionsActive()<\/code> if that fits your product.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-handler\">How do I handle a Stripe event Cashier doesn&#8217;t?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Extend Cashier&#8217;s <code>WebhookController<\/code> and add a <code>handle...<\/code> method named after the event, such as <code>handleInvoicePaymentFailed<\/code>. Then point <code>POST \/stripe\/webhook<\/code> at your subclass.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"faq-dto\">Should I pass Stripe payloads around as arrays?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">I&#8217;d map the few fields you need into a small typed object at the edge, the way I did for webhooks in <a href=\"https:\/\/www.shaz3e.com\/blog\/laravel-dto\/\">using data transfer objects in Laravel<\/a>. This post keeps arrays to stay close to Cashier&#8217;s own handlers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>I&#8217;m <a href=\"https:\/\/shaz3e.com\" target=\"_blank\" rel=\"noopener\">Shahrukh Akhtar (Shaz3e)<\/a>, CTO &amp; Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive &amp; Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on <a href=\"https:\/\/x.com\/shaz3e\" target=\"_blank\" rel=\"noopener\">X<\/a>, <a href=\"https:\/\/linkedin.com\/in\/shaz3e\" target=\"_blank\" rel=\"noopener\">LinkedIn<\/a>, <a href=\"https:\/\/peerlist.io\/shaz3e\" target=\"_blank\" rel=\"noopener\">Peerlist<\/a> and <a href=\"https:\/\/github.com\/Shaz3e\" target=\"_blank\" rel=\"noopener\">GitHub<\/a>.<\/em><\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>A Laravel Cashier Stripe setup with trials, plan swaps and proration, access gating for grace and past-due states, and a failed-payment webhook. Original code, 22 tests, Laravel 13.43 and Cashier 16.11.<\/p>\n","protected":false},"author":2,"featured_media":396,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[7],"tags":[28,93,25,63],"class_list":["post-395","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel-php","tag-laravel","tag-laravel-testing","tag-php","tag-saas"],"jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/phsTKQ-6n","jetpack_featured_media_url":"https:\/\/i0.wp.com\/www.shaz3e.com\/blog\/wp-content\/uploads\/2026\/11\/laravel-cashier-stripe-1200x630-1.jpg?fit=1200%2C630&ssl=1","_links":{"self":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts\/395","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/comments?post=395"}],"version-history":[{"count":4,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts\/395\/revisions"}],"predecessor-version":[{"id":419,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/posts\/395\/revisions\/419"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/media\/396"}],"wp:attachment":[{"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/media?parent=395"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/categories?post=395"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shaz3e.com\/blog\/wp-json\/wp\/v2\/tags?post=395"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}