Hey guys! Ever felt like managing subscriptions and billing in your Laravel app is like wrestling an octopus? It's messy, complicated, and you're never quite sure where all the tentacles are going. Well, fear not! Laravel Cashier is here to be your trusty sidekick, turning that octopus into a friendly, manageable goldfish. Let's dive into how Laravel Cashier can simplify your billing portal and make your life as a developer way easier.

    What is Laravel Cashier?

    Laravel Cashier provides an expressive, fluent interface to Stripe's and Paddle's subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. Seriously, it takes care of coupons, swapping subscriptions, subscription "quantities", cancellation grace periods, and even generates invoice PDFs. Think of it as a shield against the complexities of modern subscription billing.

    Why Use Laravel Cashier?

    • Simplicity: It makes complex billing operations feel like a breeze. No more tangled code!
    • Stripe & Paddle Support: Whether you're team Stripe or team Paddle, Cashier has your back.
    • Feature-Rich: From handling trials to managing taxes, it's got all the features you need.
    • Laravel Integration: It's designed to fit seamlessly into your Laravel application. Like a glove!

    Setting Up Laravel Cashier

    Okay, let's get our hands dirty and set up Cashier. Don't worry, it's not as daunting as it sounds. Follow these steps, and you'll be up and running in no time.

    Installation

    First things first, you need to install the Cashier package via Composer. Open up your terminal and run:

    composer require laravel/cashier
    

    This command pulls in the Cashier package and adds it to your project's dependencies. Easy peasy!

    Configuration

    Next, you'll need to configure Cashier. Publish the Cashier configuration file using:

    php artisan vendor:publish --tag="cashier-config"
    

    This command creates a config/cashier.php file in your application. Open it up and configure your Stripe or Paddle API keys. You'll find these keys in your Stripe or Paddle dashboard. Make sure to keep these keys safe and sound!

    Database Setup

    Cashier needs a place to store subscription information, so let's run the migrations. This will create the necessary tables in your database:

    php artisan migrate
    

    Billable Model

    Now, let's prepare your User model to be billable. Use the Billable trait in your App\Models\User model:

    namespace App\Models;
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Laravel\Cashier\Billable;
    
    class User extends Authenticatable
    {
        use Billable;
    
        // ...
    }
    

    This trait adds several helpful methods to your User model, such as subscribe(), subscribed(), and onTrial(). These methods make it super easy to manage subscriptions.

    Building Your Billing Portal

    Alright, now for the fun part: building your billing portal! We'll cover the basics, but remember, you can customize this to fit your specific needs.

    Displaying Subscription Status

    First, let's show the user their subscription status. In your Blade template, you can use the subscribed() method to check if the user is subscribed to a particular plan:

    @if (Auth::user()->subscribed('premium'))
        <p>You are subscribed to the Premium plan!</p>
    @else
        <p>You are not subscribed to the Premium plan.</p>
        <a href="{{ route('subscribe') }}">Subscribe Now!</a>
    @endif
    

    This code snippet checks if the user is subscribed to the premium plan. If they are, it displays a friendly message. If not, it prompts them to subscribe. Simple and effective!

    Handling Subscriptions

    Let's create a route and controller method to handle subscriptions. First, define a route in your routes/web.php file:

    Route::get('/subscribe', [SubscriptionController::class, 'show'])->name('subscribe');
    Route::post('/subscribe', [SubscriptionController::class, 'store']);
    

    Then, create a SubscriptionController with the show and store methods:

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Auth;
    
    class SubscriptionController extends Controller
    {
        public function show()
        {
            return view('subscribe');
        }
    
        public function store(Request $request)
        {
            Auth::user()->newSubscription('premium', $request->stripeToken)->create();
    
            return redirect('/home')->with('success', 'You are now subscribed to the Premium plan!');
        }
    }
    

    In the show method, you can display a form with the Stripe Elements payment form. The store method handles the subscription creation. It uses the newSubscription() method to create a new subscription for the user. The first argument is the name of the subscription, and the second argument is the Stripe token. The create() method then creates the subscription in Stripe.

    Cancelling Subscriptions

    Allowing users to cancel their subscriptions is crucial. Add a cancel button to your billing portal:

    <form action="{{ route('cancel') }}" method="POST">
        @csrf
        <button type="submit">Cancel Subscription</button>
    </form>
    

    Create a route and controller method to handle subscription cancellations:

    Route::post('/cancel', [SubscriptionController::class, 'cancel'])->name('cancel');
    
    public function cancel()
    {
        Auth::user()->subscription('premium')->cancel();
    
        return redirect('/home')->with('success', 'Your subscription has been cancelled.');
    }
    

    The cancel() method cancels the user's subscription. The subscription() method retrieves the subscription instance, and the cancel() method cancels the subscription in Stripe.

    Handling Webhooks

    Webhooks are essential for handling subscription events, such as cancellations, payments, and invoice creation. Cashier makes it easy to handle webhooks. First, expose a route that Cashier can use to handle webhooks. Register this route by adding the following to your routes/web.php file:

    Route::post('/stripe/webhook', '\Laravel\Cashier\Http\Controllers\WebhookController@handleWebhook');
    

    Make sure to configure the webhook URL in your Stripe dashboard. Cashier automatically handles the following webhook events:

    • customer.subscription.updated
    • customer.subscription.deleted
    • invoice.payment_succeeded
    • invoice.payment_failed

    If you need to handle additional webhook events, you can define them in your App\Providers\EventServiceProvider:

    protected $listen = [
        'Laravel\Cashier\Events\WebhookReceived' => [
            'App\Listeners\StripeEventListener',
        ],
    ];
    

    Advanced Features

    Cashier is packed with advanced features to handle even the most complex billing scenarios.

    Subscription Trials

    Offer free trials to entice new users. You can specify a trial period when creating a subscription:

    Auth::user()->newSubscription('premium', $request->stripeToken)->trialDays(14)->create();
    

    This code snippet creates a new subscription with a 14-day trial period.

    Coupons

    Offer discounts with coupons. First, create a coupon in your Stripe dashboard. Then, apply the coupon when creating a subscription:

    Auth::user()->newSubscription('premium', $request->stripeToken)->withCoupon('SUMMER20')->create();
    

    This code snippet creates a new subscription with the SUMMER20 coupon applied.

    Taxes

    Handle taxes effortlessly. Cashier automatically calculates and applies taxes based on the user's location. You can configure tax rates in your Stripe dashboard.

    Invoice PDFs

    Generate invoice PDFs with ease. Cashier can automatically generate invoice PDFs for your users. You can customize the invoice template to match your brand.

    Best Practices

    To make the most of Laravel Cashier, follow these best practices:

    • Test Thoroughly: Test your billing portal thoroughly to ensure everything works as expected.
    • Handle Errors: Implement proper error handling to gracefully handle any issues that may arise.
    • Secure Your API Keys: Keep your Stripe and Paddle API keys safe and secure.
    • Monitor Webhooks: Monitor your webhooks to ensure they are being processed correctly.
    • Stay Updated: Keep Cashier and its dependencies up to date to benefit from the latest features and security patches.

    Conclusion

    So there you have it, guys! Laravel Cashier is a fantastic tool for simplifying your billing portal. It takes the headache out of subscription management, allowing you to focus on building awesome features for your application. With its simple setup, feature-rich functionality, and seamless Laravel integration, Cashier is a must-have for any Laravel developer dealing with subscriptions. So go ahead, give it a try, and say goodbye to billing woes! Happy coding!