Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 67 ยท Projects

Project: Subscriptions, Billing and an Admin Panel

Add paid subscriptions to a Laravel 13 app with Cashier, from checkout, webhooks, subscription gates, invoices and a Filament admin panel, with tested logic.

Sooner or later most web apps want to charge money: a monthly plan, a free trial, a customer who cancels and another whose card expires. This project walks through the pieces of a small subscription product: Laravel Cashier for the billing provider, a checkout page, a webhook endpoint that keeps your database in step with the provider, a gate that protects paid features, invoice downloads, and a Filament admin panel for your own team.

Billing is the one place where "it mostly works" is not good enough, so the lesson spends its time on the rules: what the provider decides, what your app decides, and what to do when events arrive twice or in the wrong order.

Laravel, Cashier and Filament cannot run on this site, and this lesson never touches a real payment provider. The Laravel code is read-only and written for Cashier with Stripe, so copy it into a test-mode project of your own (never use real cards while learning). The runnable examples are plain PHP stand-ins for the logic you must get right: the subscription state machine and a webhook receiver with signature checks. Each section says which is which. Package APIs evolve, so check the current Cashier and Filament documentation before you copy anything into production.

Who does what

flowchart LR
    U["Customer"] -->|"pays on hosted checkout"| P["Billing provider<br/>(Stripe)"]
    P -->|"signed webhooks"| W["Your webhook route"]
    W --> DB[("subscriptions table")]
    A["Your app"] -->|"subscribed()?"| DB
    AD["Admin panel"] --> DB

The provider handles cards, taxes on invoices and retries. Your app only reads its own copy of the subscription state, kept current by webhooks.

The core principle: the provider is the source of truth for money, your database is a cache of that truth. When a customer returns from checkout, you do not know yet whether the payment went through. When a card expires next month, nothing visits your site at all. In both cases the provider tells you through a webhook, an HTTP request it sends to your server. Cashier gives you the plumbing for all of this, and the Billable trait adds billing methods to your User model.

If you plan to sell worldwide, a merchant of record such as Paddle (Laravel has the separate laravel/cashier-paddle package) takes over sales tax and VAT filings for you. The concepts in this lesson, statuses, webhooks, gates, are the same.

Setup

Terminal
composer require laravel/cashier
php artisan vendor:publish --tag="cashier-migrations"
php artisan migrate

Add the keys from your provider's test mode to .env and use the Billable trait:

Terminal
STRIPE_KEY=pk_test_...
STRIPE_SECRET=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
PHP
use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable, HasFactory, Notifiable;
}

The migrations add Stripe columns to users and create subscriptions and subscription_items tables. Keep secrets in .env only (never in git), and map price IDs to plan names in a config file such as config/billing.php, so the rest of the code says config('billing.prices.pro'), not a magic string.

Checkout

Stripe Checkout is a payment page hosted by the provider, so card numbers never touch your server. Starting one takes a single route:

PHP
use Illuminate\Http\Request;

Route::middleware('auth')->group(function () {
    Route::get('/subscribe', function (Request $request) {
        return $request->user()
            ->newSubscription('default', config('billing.prices.pro'))
            ->trialDays(14)
            ->checkout([
                'success_url' => route('billing.success'),
                'cancel_url' => route('pricing'),
            ]);
    })->name('subscribe');

    Route::get('/billing/portal', function (Request $request) {
        return $request->user()->redirectToBillingPortal(route('dashboard'));
    })->name('billing.portal');
});

The 'default' is just the name of this subscription; an app that sells several independent products can use more names. The checkout() result is a response that redirects the browser to the hosted page. The billing portal, also hosted by the provider, lets customers update cards, view invoices and cancel without you writing any of that UI.

The page behind billing.success should say "Thanks, we are confirming your payment" and not unlock anything by itself. The browser reaching that URL proves nothing: anyone can type it. Access is unlocked by the webhook.

Webhooks

Cashier registers a POST /stripe/webhook route for you (named cashier.webhook) and updates the subscriptions table when events such as customer.subscription.updated or customer.subscription.deleted arrive. You need to do three things:

Terminal
php artisan cashier:webhook        # registers the endpoint with the provider
PHP
// bootstrap/app.php: the provider cannot send a CSRF token
->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/*',
    ]);
})

and set STRIPE_WEBHOOK_SECRET so Cashier verifies the signature of every request. Without verification, anybody could POST a fake "payment succeeded" to your server. While developing locally, a forwarding tool from the provider (the Stripe CLI's stripe listen) delivers test events to your machine.

To react to an event with your own logic, such as emailing the customer when a payment fails, listen for Cashier's event:

PHP
use Laravel\Cashier\Events\WebhookReceived;

class HandleBillingEvents
{
    public function handle(WebhookReceived $event): void
    {
        if ($event->payload['type'] === 'invoice.payment_failed') {
            // look up the customer, notify them, log it
        }
    }
}

Because providers retry deliveries when your server is slow or errors, the same event can arrive more than once, and events can arrive out of order. Your handlers must therefore be idempotent, and they should ask "what is the current state?" rather than "what did this one event say?". The next stand-in shows two of these ideas: signature verification with a replay window, and skipping events whose ID was already processed. The signature format is a simplification of what real providers use, built on the same principle: an HMAC of the timestamp and the body with a shared secret.

PHP A webhook receiver: signatures and idempotency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the payment is counted exactly once even though it was delivered twice, the tampered body is rejected before anything is parsed, and hash_equals() compares signatures in constant time. Cashier does the signature check for you; the idempotency rule is yours to follow in any listener you write.

The subscription lifecycle

A subscription is not a yes-or-no flag. It moves through states, and the access rules depend on the state:

stateDiagram-v2
    [*] --> trialing: checkout completed with trial
    trialing --> active: first invoice paid
    trialing --> past_due: first payment failed
    active --> past_due: renewal payment failed
    past_due --> active: customer fixes the card
    past_due --> ended: retries exhausted
    active --> canceling: customer cancels
    trialing --> canceling: customer cancels
    canceling --> active: customer resumes
    canceling --> ended: paid period runs out
    ended --> [*]

"Canceling" means canceled but still paid up: the customer keeps access until the end of the period they already paid for.

Cashier names these ideas with methods you will use constantly: $user->subscribed('default') (does this user currently have a valid subscription), onTrial(), onGracePeriod() on the subscription (canceled but still within the paid period), pastDue(), canceled() and ended(). By default Cashier does not treat a past_due subscription as active, and it offers a configuration switch if you would rather give customers a few days to fix their card, which is a business decision, not a technical one.

This stand-in models the state machine and the access rule, driven by a timeline of webhook-style events and a fake clock in days. Events that make no sense in the current state are ignored, which is also how you cope with out-of-order delivery.

PHP A subscription state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the table row by row. The trial gives access from day 0. The first invoice on day 14 makes the subscription active for 30 days. A failed renewal on day 44 removes access, and the successful retry on day 47 restores it. The cancellation on day 50 keeps access until day 77, the end of the paid period; after that the state quietly becomes ended, and a stray late invoice.paid changes nothing.

Protecting paid features

A small middleware turns the state into a gate. Create it with php artisan make:middleware EnsureUserIsSubscribed:

PHP
class EnsureUserIsSubscribed
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()?->subscribed('default')) {
            return redirect()->route('pricing')
                ->with('status', 'That feature needs an active subscription.');
        }

        return $next($request);
    }
}
PHP
// bootstrap/app.php
$middleware->alias(['subscribed' => EnsureUserIsSubscribed::class]);

// routes/web.php
Route::middleware(['auth', 'subscribed'])->group(function () {
    Route::get('/reports', [ReportController::class, 'index']);
});

For plans with different features, use $user->subscribedToPrice(config('billing.prices.team'), 'default'), or better, define a gate such as use-reports that holds the rule in one place. Then both routes and Blade (@can('use-reports')) ask the same question. Gate the server side only: hiding a button is a courtesy, never protection.

Invoices

Customers expect to find past invoices. Cashier lists them straight from the provider:

PHP
Route::get('/billing/invoices', function (Request $request) {
    return view('billing.invoices', ['invoices' => $request->user()->invoices()]);
})->middleware('auth');

Route::get('/billing/invoices/{invoice}', function (Request $request, string $invoice) {
    return $request->user()->downloadInvoice($invoice, [
        'vendor' => 'Your Company',
        'product' => 'Pro plan',
    ]);
})->middleware('auth');

downloadInvoice() looks the invoice up through the signed-in user's own customer record, so one user cannot download another's invoice by guessing IDs. Generating the PDF needs the dompdf/dompdf package. Alternatively, send customers to the provider's hosted invoice page and skip the PDF work entirely.

The admin panel with Filament

Your team needs to look up customers, see who is subscribed and fix problems. Instead of building screens by hand, a package such as Filament generates an admin panel from your models:

Terminal
composer require filament/filament
php artisan filament:install --panels
php artisan make:filament-user
php artisan make:filament-resource User

The panel lives at /admin by default, and the resource command creates list, create and edit pages for the model, which you then trim and extend: search the email column, add a column showing the subscription status, add filters. The important part is access. Filament only lets a user in when the model says so:

PHP
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;

class User extends Authenticatable implements FilamentUser
{
    public function canAccessPanel(Panel $panel): bool
    {
        return $this->is_admin;
    }
}

An admin panel is a very attractive target. Keep is_admin out of $fillable, so nobody can promote themselves through a profile form. Prefer a role system from roles and permissions when you have more than one kind of staff, require two-factor authentication for admins, and never let a support screen show full card details (you do not have them, and that is the point of a hosted checkout).

Tests

Billing logic is full of branches, so test it. For your own rules you do not need the provider at all:

PHP
it('redirects users without a subscription away from reports', function () {
    $this->actingAs(User::factory()->create())
        ->get('/reports')
        ->assertRedirect(route('pricing'));
});

it('lets subscribed users in', function () {
    $user = User::factory()->create();
    $user->subscriptions()->create([
        'type' => 'default',
        'stripe_id' => 'sub_test_1',
        'stripe_status' => 'active',
        'stripe_price' => 'price_pro',
        'quantity' => 1,
    ]);

    $this->actingAs($user)->get('/reports')->assertOk();
});

it('keeps non-admins out of the panel', function () {
    $this->actingAs(User::factory()->create(['is_admin' => false]))
        ->get('/admin')
        ->assertForbidden();
});

Creating a subscriptions row directly is a fast way to put a user into any state. Test the rest of your webhook listeners by building the payload yourself and posting it to your handler class, or by calling the listener with a WebhookReceived event. Do not make tests call the real provider: they would be slow, flaky and dependent on network access. See HTTP and database tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A customer returns from the hosted checkout to your success URL. What should your app do?

    Anyone can visit a success URL. The signed webhook from the provider is the reliable signal that the payment really happened.
  2. 2. Why must webhook handlers be idempotent?

    A slow response or an error makes the provider send the event again. Processing it twice must not, for example, double-count a payment.
  3. 3. What does a subscription in the canceling state (on its grace period) mean?

    Canceling stops future renewals. Because the current period is already paid, access continues until that period ends.
  4. 4. Why does the webhook route need to be excluded from CSRF verification?

    CSRF protects browser sessions. A webhook has no session, so you verify the provider's signature instead.
  5. 5. Which line of defense actually protects an admin panel?

    Hidden links and secret URLs are not security. The server must check who the user is on every request, and users must not be able to grant themselves the admin flag.

Summary

  • The billing provider is the source of truth for money; your database is a copy kept current by signed webhooks.
  • Use hosted checkout and the billing portal so card data never touches your server; unlock features from webhooks, not from the success redirect.
  • Verify webhook signatures, exclude the route from CSRF and make every handler idempotent and order-tolerant.
  • Model the lifecycle (trialing, active, past due, canceling, ended) and keep the access rule in one gate or middleware.
  • Let users download invoices through their own customer record, and test your rules without calling the provider.
  • Protect the Filament admin panel with canAccessPanel(), non-fillable admin flags and two-factor authentication.

Next: Practice Exercises with Solutions