更新日:2025/10/24
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.
To get started, install the laravel/cashier package using Composer:
composer require laravel/cashier
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'),
],
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;
}
Laravel Cashier adds several columns to your users table. Run the following migration command:
php artisan migrate
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',
]);
Before creating subscriptions or charging users, you need to attach a 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');
$paymentMethod = $request->paymentMethod;
$user->addPaymentMethod($paymentMethod);
$user->updateDefaultPaymentMethod($paymentMethod);
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);
You can also provide free trial periods for new users:
$user->newSubscription('default', 'price_monthly_plan_id')
->trialDays(14)
->create($paymentMethod);
if ($user->subscribed('default')) {
echo "User is subscribed.";
} else {
echo "User is not subscribed.";
}
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');
$user->subscription('default')->cancelNow();
$user->subscription('default')->cancel();
$user->subscription('default')->resume();
Invoices can be easily accessed or downloaded using Cashier’s built-in methods.
$invoices = $user->invoices();
foreach ($invoices as $invoice) {
echo $invoice->id . " - " . $invoice->amount_due;
}
return $user->downloadInvoice($invoiceId, [
'vendor' => 'Your Company',
'product' => 'Laravel Cashier Subscription',
]);
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.
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']);
}
}
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],
]);
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);
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
$user->newSubscription('default', 'price_basic_plan')
->withCoupon('PROMO2025')
->create($paymentMethod);
$user->newSubscription('default', 'price_basic_plan')
->withTaxRates(['txr_123456789'])
->create($paymentMethod);
If your product uses usage-based billing, you can record usage events:
$user->subscription('default')->reportUsage(100);
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
if ($user->onTrial()) {
echo "User is on a free trial.";
}
if ($user->subscription('default')->onGracePeriod()) {
echo "Subscription will end soon.";
}
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);
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
]);
Occurs if you pass an invalid payment method ID.
Fix: Make sure you attach the payment method to the user first.
This happens when the Stripe price ID doesn’t match any existing plan.
Fix: Double-check your price_* ID in the Stripe dashboard.
// 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);
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:
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.
Laravel Cashier (Stripe)
オフショア開発のご紹介資料