ホーム

Blog

Laravel Cashier (Stripe)

Laravel Cashier (Stripe) is an official Laravel package that provides an expressive and fluent interface for managing subscriptions and billing services with Stripe

更新日:2025/10/24

Laravel Cashier (Stripe)

Introduction to Laravel Cashier (Stripe)

Laravel Cashier (Stripe) is an official Laravel package that provides an expressive and fluent interface for managing subscriptions and billing services with Stripe. It abstracts away the complexities of integrating Stripe’s API and makes it easy to handle payments, subscriptions, invoices, and receipts directly from your Laravel application.

In this comprehensive guide, we’ll cover everything from installation to advanced subscription management, complete with working examples.

1. Installation and Setup

Step 1: Install Laravel Cashier

To get started, install the laravel/cashier package using Composer:

composer require laravel/cashier

Step 2: Configure Stripe Keys

Next, add your Stripe API keys to the .env file:

STRIPE_KEY=pk_test_your_public_key
STRIPE_SECRET=sk_test_your_secret_key

Then, add them to your config/services.php file:

'stripe' => [
    'secret' => env('STRIPE_SECRET'),
    'key' => env('STRIPE_KEY'),
],

Step 3: Add Billable Trait to Your User Model

To make a model billable, add the Billable trait to it. Usually, this is the User model:

use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

Step 4: Run Database Migrations

Laravel Cashier adds several columns to your users table. Run the following migration command:

php artisan migrate

2. Creating and Managing Customers

When you first interact with Stripe through Cashier, it will automatically create a Stripe customer for the user if they don’t already exist.

$user = User::find(1);

// Create a new Stripe customer if not exists
$user->createOrGetStripeCustomer();

You can also update customer details:

$user->updateStripeCustomer([
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

3. Adding Payment Methods

Before creating subscriptions or charging users, you need to attach a payment method.

Frontend: Collecting Payment Method

Laravel Cashier provides a helper route for handling payment method setup via Stripe’s Elements.

// Example with Vue.js or plain JavaScript
const stripe = Stripe("{{ config('services.stripe.key') }}");
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');

Backend: Attaching Payment Method

$paymentMethod = $request->paymentMethod;
$user->addPaymentMethod($paymentMethod);
$user->updateDefaultPaymentMethod($paymentMethod);

4. Creating Subscriptions

Creating subscriptions in Laravel Cashier is extremely straightforward. You can define a plan in Stripe and refer to it by its ID.

$user->newSubscription('default', 'price_monthly_plan_id')
     ->create($paymentMethod);

Handling Free Trials

You can also provide free trial periods for new users:

$user->newSubscription('default', 'price_monthly_plan_id')
     ->trialDays(14)
     ->create($paymentMethod);

Checking Subscription Status

if ($user->subscribed('default')) {
    echo "User is subscribed.";
} else {
    echo "User is not subscribed.";
}

5. Changing Subscription Plans

Cashier allows seamless upgrading or downgrading of plans.

$user->subscription('default')->swap('price_premium_plan_id');

You can also prorate charges when switching:

$user->subscription('default')->swapAndInvoice('price_pro_plan_id');

6. Canceling Subscriptions

Cancel Immediately

$user->subscription('default')->cancelNow();

Cancel at End of Period

$user->subscription('default')->cancel();

Resuming Subscriptions

$user->subscription('default')->resume();

7. Invoices and Receipts

Invoices can be easily accessed or downloaded using Cashier’s built-in methods.

Listing Invoices

$invoices = $user->invoices();

foreach ($invoices as $invoice) {
    echo $invoice->id . " - " . $invoice->amount_due;
}

Downloading Invoice PDF

return $user->downloadInvoice($invoiceId, [
    'vendor' => 'Your Company',
    'product' => 'Laravel Cashier Subscription',
]);

8. Handling Webhooks

To handle Stripe events, such as failed payments or subscription updates, Cashier includes a webhook controller you can enable easily.

php artisan cashier:webhook

This creates a route at /stripe/webhook. You should register this route in Stripe’s dashboard as your webhook endpoint.

Customizing Webhook Handling

If you need to handle custom events:

use Laravel\Cashier\Http\Controllers\WebhookController;

class CustomWebhookController extends WebhookController
{
    public function handleInvoicePaymentFailed($payload)
    {
        // Custom logic when payment fails
        Log::info('Payment failed for user: ' . $payload['data']['object']['customer']);
    }
}

9. Single Charges (One-Time Payments)

Not all payments require a subscription. You can charge users directly.

$paymentMethod = $user->defaultPaymentMethod();

$user->charge(2500, $paymentMethod->id); // Charge $25.00

You can also add metadata:

$user->charge(1500, $paymentMethod->id, [
    'metadata' => ['order_id' => 1234],
]);

10. Stripe Checkout Integration

Cashier supports Stripe Checkout for hosted payment pages. This is useful for simple and secure billing flows.

$checkout = $user->newSubscription('default', 'price_basic_plan')
    ->checkout([
        'success_url' => route('checkout.success'),
        'cancel_url' => route('checkout.cancel'),
    ]);
    
return redirect($checkout->url);

11. Testing with Stripe

Stripe provides test card numbers you can use in your development environment.

4242 4242 4242 4242  // Success card
4000 0000 0000 9995  // Payment requires authentication
4000 0000 0000 0341  // Card declined

12. Advanced Features

Applying Coupons

$user->newSubscription('default', 'price_basic_plan')
     ->withCoupon('PROMO2025')
     ->create($paymentMethod);

Managing Tax Rates

$user->newSubscription('default', 'price_basic_plan')
     ->withTaxRates(['txr_123456789'])
     ->create($paymentMethod);

Metered Billing

If your product uses usage-based billing, you can record usage events:

$user->subscription('default')->reportUsage(100);

13. Displaying Subscription Information in Views

In your Blade templates, you can easily check the user’s subscription status.

@if (auth()->user()->subscribed('default'))
    <p>You have an active subscription.</p>
@else
    <p>Your subscription is inactive.</p>
@endif

14. Handling Subscription Trials and Grace Periods

if ($user->onTrial()) {
    echo "User is on a free trial.";
}

if ($user->subscription('default')->onGracePeriod()) {
    echo "Subscription will end soon.";
}

15. Using Cashier with Teams or Multi-User Accounts

If your app supports teams, you can create a billing system where one account manages payments for multiple users.

$team->createOrGetStripeCustomer();
$team->newSubscription('default', 'price_team_plan')->create($paymentMethod);

16. Handling Refunds

You can issue refunds using the Stripe API via Cashier’s underlying Stripe client.

\Stripe\Stripe::setApiKey(config('services.stripe.secret'));

\Stripe\Refund::create([
    'charge' => $chargeId,
    'amount' => 1000, // Refund $10
]);

17. Common Errors and Debugging

Error: No Such Payment Method

Occurs if you pass an invalid payment method ID.

Fix: Make sure you attach the payment method to the user first.

Error: Invalid Price ID

This happens when the Stripe price ID doesn’t match any existing plan.

Fix: Double-check your price_* ID in the Stripe dashboard.

Debugging Tips

  • Check storage/logs/laravel.log for Cashier errors.
  • Use \Log::info() in webhook handlers for debugging events.
  • Enable Stripe’s test mode to safely simulate transactions.

18. Best Practices

  • Always store Stripe customer IDs in your database.
  • Use webhook events to automatically react to subscription changes.
  • Do not rely solely on frontend for payment verification — always confirm from backend.
  • Test thoroughly in Stripe’s test environment before going live.
  • Secure your webhook routes using Stripe’s signature verification.

19. Example Workflow

// 1. User adds card
$user->addPaymentMethod($request->paymentMethod);

// 2. User subscribes to a plan
$user->newSubscription('default', 'price_basic_plan')->create($paymentMethod);

// 3. User changes plan
$user->subscription('default')->swap('price_premium_plan');

// 4. User views invoice
return $user->downloadInvoice($invoiceId);

20. Conclusion

Laravel Cashier (Stripe) simplifies subscription billing and one-time payments by providing an elegant API on top of Stripe’s powerful payment platform. It handles everything from customer management to invoice generation, making it an essential tool for SaaS developers and e-commerce applications built with Laravel.

By following this guide, you now have the knowledge to:

  • Integrate Stripe billing into your Laravel app.
  • Create, manage, and cancel subscriptions.
  • Handle invoices, receipts, and webhooks efficiently.
  • Implement secure payment flows with minimal effort.

For more information, you can visit the official Laravel Cashier documentation here: https://laravel.com/docs/cashier

With Cashier and Stripe, managing your users’ billing experience becomes a smooth, automated, and developer-friendly process.