Laravel Cashier

Introduction

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs.

Configuration

Composer

First, add the Cashier package to your composer.json file:

  1. "laravel/cashier": "~2.0"

Service Provider

Next, register the Laravel\Cashier\CashierServiceProvider in your app configuration file.

Migration

Before using Cashier, we'll need to add several columns to your database. Don't worry, you can use the cashier:table Artisan command to create a migration to add the necessary column. For example, to add the column to the users table use php artisan cashier:table users. Once the migration has been created, simply run the migrate command.

Model Setup

Next, add the BillableTrait and appropriate date mutators to your model definition:

  1. use Laravel\Cashier\BillableTrait;
  2. use Laravel\Cashier\BillableInterface;
  3. class User extends Eloquent implements BillableInterface {
  4. use BillableTrait;
  5. protected $dates = ['trial_ends_at', 'subscription_ends_at'];
  6. }

Stripe Key

Finally, set your Stripe key in one of your bootstrap files:

  1. User::setStripeKey('stripe-key');

Subscribing To A Plan

Once you have a model instance, you can easily subscribe that user to a given Stripe plan:

  1. $user = User::find(1);
  2. $user->subscription('monthly')->create($creditCardToken);

If you would like to apply a coupon when creating the subscription, you may use the withCoupon method:

  1. $user->subscription('monthly')
  2. ->withCoupon('code')
  3. ->create($creditCardToken);

The subscription method will automatically create the Stripe subscription, as well as update your database with Stripe customer ID and other relevant billing information. If your plan has a trial configured in Stripe, the trial end date will also automatically be set on the user record.

If your plan has a trial period that is not configured in Stripe, you must set the trial end date manually after subscribing:

  1. $user->trial_ends_at = Carbon::now()->addDays(14);
  2. $user->save();

Specifying Additional User Details

If you would like to specify additional customer details, you may do so by passing them as second argument to the create method:

  1. $user->subscription('monthly')->create($creditCardToken, [
  2. 'email' => $email, 'description' => 'Our First Customer'
  3. ]);

To learn more about the additional fields supported by Stripe, check out Stripe's documentation on customer creation.

No Card Up Front

If your application offers a free-trial with no credit-card up front, set the cardUpFront property on your model to false:

  1. protected $cardUpFront = false;

On account creation, be sure to set the trial end date on the model:

  1. $user->trial_ends_at = Carbon::now()->addDays(14);
  2. $user->save();

Swapping Subscriptions

To swap a user to a new subscription, use the swap method:

  1. $user->subscription('premium')->swap();

If the user is on trial, the trial will be maintained as normal. Also, if a "quantity" exists for the subscription, that quantity will also be maintained.

Subscription Quantity

Sometimes subscriptions are affected by "quantity". For example, your application might charge $10 per month per user on an account. To easily increment or decrement your subscription quantity, use the increment and decrement methods:

  1. $user = User::find(1);
  2. $user->subscription()->increment();
  3. // Add five to the subscription's current quantity...
  4. $user->subscription()->increment(5);
  5. $user->subscription()->decrement();
  6. // Subtract five to the subscription's current quantity...
  7. $user->subscription()->decrement(5);

Cancelling A Subscription

Cancelling a subscription is a walk in the park:

  1. $user->subscription()->cancel();

When a subscription is cancelled, Cashier will automatically set the subscription_ends_at column on your database. This column is used to know when the subscribed method should begin returning false. For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the subscribed method will continue to return true until March 5th.

Resuming A Subscription

If a user has cancelled their subscription and you wish to resume it, use the resume method:

  1. $user->subscription('monthly')->resume($creditCardToken);

If the user cancels a subscription and then resumes that subscription before the subscription has fully expired, they will not be billed immediately. Their subscription will simply be re-activated, and they will be billed on the original billing cycle.

Checking Subscription Status

To verify that a user is subscribed to your application, use the subscribed command:

  1. if ($user->subscribed())
  2. {
  3. //
  4. }

The subscribed method makes a great candidate for a route filter:

  1. Route::filter('subscribed', function()
  2. {
  3. if (Auth::user() && ! Auth::user()->subscribed())
  4. {
  5. return Redirect::to('billing');
  6. }
  7. });

You may also determine if the user is still within their trial period (if applicable) using the onTrial method:

  1. if ($user->onTrial())
  2. {
  3. //
  4. }

To determine if the user was once an active subscriber, but has cancelled their subscription, you may use the cancelled method:

  1. if ($user->cancelled())
  2. {
  3. //
  4. }

You may also determine if a user has cancelled their subscription, but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was scheduled to end on March 10th, the user is on their "grace period" until March 10th. Note that the subscribed method still returns true during this time.

  1. if ($user->onGracePeriod())
  2. {
  3. //
  4. }

The everSubscribed method may be used to determine if the user has ever subscribed to a plan in your application:

  1. if ($user->everSubscribed())
  2. {
  3. //
  4. }

The onPlan method may be used to determine if the user is subscribed to a given plan based on its ID:

  1. if ($user->onPlan('monthly'))
  2. {
  3. //
  4. }

Handling Failed Payments

What if a customer's credit card expires? No worries - Cashier includes a Webhook controller that can easily cancel the customer's subscription for you. Just point a route to the controller:

  1. Route::post('stripe/webhook', 'Laravel\Cashier\[email protected]');

That's it! Failed payments will be captured and handled by the controller. The controller will cancel the customer's subscription after three failed payment attempts. The stripe/webhook URI in this example is just for example. You will need to configure the URI in your Stripe settings.

Handling Other Stripe Webhooks

If you have additional Stripe webhook events you would like to handle, simply extend the Webhook controller. Your method names should correspond to Cashier's expected convention, specifically, methods should be prefixed with handle and the name of the Stripe webhook you wish to handle. For example, if you wish to handle the invoice.payment_succeeded webhook, you should add a handleInvoicePaymentSucceeded method to the controller.

  1. class WebhookController extends Laravel\Cashier\WebhookController {
  2. public function handleInvoicePaymentSucceeded($payload)
  3. {
  4. // Handle The Event
  5. }
  6. }

Note: In addition to updating the subscription information in your database, the Webhook controller will also cancel the subscription via the Stripe API.

Invoices

You can easily retrieve an array of a user's invoices using the invoices method:

  1. $invoices = $user->invoices();

When listing the invoices for the customer, you may use these helper methods to display the relevant invoice information:

  1. {{ $invoice->id }}
  2. {{ $invoice->dateString() }}
  3. {{ $invoice->dollars() }}

Use the downloadInvoice method to generate a PDF download of the invoice. Yes, it's really this easy:

  1. return $user->downloadInvoice($invoice->id, [
  2. 'vendor' => 'Your Company',
  3. 'product' => 'Your Product',
  4. ]);