What is Laravel Cashier - The Complete Guide

Updated: Feb 16, 2023

Are you looking for a reliable and easy-to-use billing system for your web application? Laravel Cashier is the perfect solution for your needs. It is a popular package for Laravel, a PHP framework, that makes billing a breeze. It's important to note that it's not the only package available for Laravel applications. For example, Laravel Breeze is a lightweight starter kit that can help you quickly set up a new Laravel project, if you're interested in deploying your Laravel application to a serverless environment, Laravel Vapor provides a streamlined experience for deploying your application to AWS Lambda.

What is Laravel Cashier?

Laravel Cashier is a billing and subscription management system that integrates with Stripe, a popular payment gateway. It provides an easy-to-use API that allows developers to handle the complexities of billing and subscription management, without the need to develop their own system from scratch.

With Laravel Cashier, developers can easily handle tasks such as creating plans, managing subscriptions, handling cancellations and issuing refunds. It also includes features such as proration, invoicing, and the ability to handle multiple payment methods.

What is Laravel Cashier

What is Laravel Cashier

How to Install Laravel Cashier

To use Laravel Cashier, you first need to install it. The easiest way to do this is through Composer, a dependency management tool for PHP. Here are the steps to install Laravel Cashier:

1. Open your terminal or command prompt and navigate to your Laravel project directory.

2. Run the following command to install Laravel Cashier:

composer require laravel/cashier

3. Once the installation is complete, run the following command to publish the Laravel Cashier configuration file:

php artisan vendor:publish --tag=braintree-config

4. You can now configure Laravel Cashier by modifying the config/braintree.php file.

How to Setup Strip in Laravel Cashier

To use Laravel Cashier, you need to have a Stripe account. Here's how to set up Stripe:

  1. Go to the Stripe website and create an account.
  2. Once you've created an account, navigate to the Stripe dashboard and click on the "Developers" tab.
  3. Click on "API keys" to access your API keys. You will need your "Publishable key" and "Secret key" to use Laravel Cashier.

Display Stripe Plans

Now that you've installed Laravel Cashier and set up Stripe, you can start creating plans for your web application. A plan is a subscription that your customers can sign up for. Here's how to create a plan:

1. Open the config/services.php file in your Laravel project.

2. Add the following lines to the file:

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

3. Open the routes/web.php file in your Laravel project.

4. Add the following route to the file:

Route::get('/plans', function () {
    $plans = \Stripe\Plan::all();
    return view('plans', ['plans' => $plans]);
});

5. Create a view file called plans.blade.php in the resources/views directory of your Laravel project.

6. In the plans.blade.php file, add the following code to display the list of plans:

<ul>
    @foreach ($plans['data'] as $plan)
        <li>{{ $plan->nickname }} - ${{ $plan->amount / 100 }} / {{ $plan->interval }}</li>
    @endforeach
</ul>

7. Run the web server and navigate to http://localhost:8000/plans to see a list of your plans.

How to Manage Subscriptions in Laravel Cashier

With Laravel Cashier, managing subscriptions is easy.

Here's how to create a subscription for a customer:

1. Open the routes/web.php file in your Laravel project.

2. Add the following route to the file:

Route::post('/subscribe', function (Request $request) {
    $user = $request->user();
    $user->newSubscription('default', $request->plan)
        ->create($request->stripeToken);
    return redirect('/')->with('success', 'Subscription successful');
});

3. Create a view file called subscribe.blade.php in the resources/views directory of your Laravel project.

4. In the subscribe.blade.php file, add the following code to display a form for creating a subscription:

<form action="/subscribe" method="POST">
    @csrf
    <label for="plan">Select a Plan:</label><select name="plan">
        @foreach ($plans['data'] as $plan)
            <option value="{{ $plan->id }}">{{ $plan->nickname }} - ${{ $plan->amount / 100 }} / {{ $plan->interval }}</option>
        @endforeach
    </select><br><label for="card-element">
        Credit or debit card
    </label><div id="card-element"><!-- A Stripe Element will be inserted here. --></div><!-- Used to display form errors. --><div id="card-errors" role="alert"></div><br><button>Subscribe</button>
</form>

5. Install Stripe.js to handle card tokenization. To do this, run the following command:

npm install stripe

6. Add the following script to the subscribe.blade.php file:

<script src="https://js.stripe.com/v3/"></script>
<script>var stripe = Stripe('{{ env('STRIPE_KEY') }}');
    var elements = stripe.elements();
    var cardElement = elements.create('card');
    cardElement.mount('#card-element');
    var cardErrors = document.getElementById('card-errors');
    cardElement.addEventListener('change', function(event) {
        if (event.error) {
            cardErrors.textContent = event.error.message;
        } else {
            cardErrors.textContent = '';
        }
    });
</script>

7. Run the web server and navigate to http://localhost:8000/subscribe to see the subscription form.

What is Laravel Cashier

What is Laravel Cashier

Handling Webhooks

Stripe webhooks allow you to receive notifications when events occur in your Stripe account, such as when a subscription is canceled or a payment fails. Laravel Cashier provides a simple way to handle Stripe webhooks.

Here's how to set up webhooks:

1. Open the config/services.php file in your Laravel project.

2. Add the following lines to the file:

'stripe' => [
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
    'webhook' => [
        'secret' => env('STRIPE_WEBHOOK_SECRET'),
        'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),
    ],
],

3. Generate a Stripe webhook secret key by running the following command:

php artisan stripe:webhook-secret

4. Add the following line to your .env file:

STRIPE_WEBHOOK_SECRET=whsec_...

5. Open the App\Http\Middleware\VerifyCsrfToken middleware class in your Laravel project.

6. Add the following line to the $except array:

'stripe/*',

7. Create a new controller called StripeWebhookController in the app/Http/Controllers directory of your Laravel project.

8. In the StripeWebhookController, add the following code to handle the customer.subscription.deleted event:

public function handleSubscriptionDeleted($payload)
{
    $subscription = Subscription::where('stripe_id', $payload['data']['object']['id'])->first();
    if ($subscription) {
        $subscription->cancel();
    }
}

9. Add the following code to the StripeWebhookController to handle the invoice.payment_failed event:

public function handlePaymentFailed($payload)
{
    $subscription = Subscription::where('stripe_id', $payload['data']['object']['subscription'])->first();
    if ($subscription) {
        $user = $subscription->user;
        $user->notify(new PaymentFailed($subscription));
    }
}

10. Add the following route to your routes/api.php file:

Route::post('stripe/webhook', '\App\Http\Controllers\StripeWebhookController@handleWebhook');

11. Run the web server and navigate to http://localhost:8000/stripe/webhook to see the Stripe webhook endpoint.

Conclusion

In this article, we've covered the basics of Laravel Cashier and how it can be used to handle subscription billing for your Laravel application. We've discussed how to create plans and subscriptions, as well as how to handle webhooks for events such as subscription cancellations and failed payments.

By following the steps outlined in this guide, you should be well on your way to implementing subscription billing in your Laravel application using Laravel Cashier. If you have any questions or run into any issues, feel free to consult the official Laravel Cashier documentation or seek help from the Laravel community.

FAQs

Q: What is Laravel Cashier?

A: Laravel Cashier is a package for Laravel that provides an easy-to-use interface for handling subscription billing. It integrates with Stripe, a popular payment processing service, to handle payment processing and subscription management.

Q: Can I use Laravel Cashier with other payment processors besides Stripe?

A: No, Laravel Cashier is specifically designed to work with Stripe and cannot be used with other payment processors.

Q: What kind of subscriptions can I create with Laravel Cashier?

A: With Laravel Cashier, you can create simple subscriptions with fixed billing intervals (e.g. monthly or yearly) and fixed prices. You can also create metered subscriptions that bill based on usage (e.g. per API request or per GB of data transferred).

Q: Can I customize the user interface for subscription management?

A: Yes, Laravel Cashier provides a set of default views that you can customize to match the look and feel of your application.

Q: Does Laravel Cashier handle taxes and invoicing?

A: No, Laravel Cashier does not handle taxes or invoicing. These features must be implemented separately in your application or using a third-party service.