Let's dive into Laravel Cashier, a fantastic tool that simplifies subscription billing in your Laravel applications. If you're dealing with recurring payments, subscriptions, or handling invoices, Cashier is your go-to package. It provides an expressive, fluent interface to Stripe and Paddle, taking away the headache of managing the complexities of these services directly. This article will guide you through the ins and outs of using Laravel Cashier to create a seamless billing portal. This will significantly enhance your application's ability to manage subscriptions and provide a user-friendly experience for your customers.

    What is Laravel Cashier?

    Laravel Cashier is more than just a package; it's your billing assistant. It offers an elegant way to handle subscription billing services like Stripe and Paddle. Instead of getting bogged down in the intricate details of APIs and webhooks, Cashier provides a smooth, Laravel-esque syntax to manage subscriptions, handle coupons, generate invoices, and more. Whether you're building a SaaS platform, a membership site, or any application that requires recurring payments, Cashier abstracts the complexities, letting you focus on your core application logic. By integrating Cashier, you can easily define subscription plans, manage trials, process payments, and handle payment failures with minimal code. It supports features like proration, quantity subscriptions, and even switching between different subscription tiers, making it incredibly versatile for various business models. The package also includes built-in support for generating PDF invoices, which can be easily customized to match your brand. This automation of billing tasks not only saves you time but also ensures accuracy and consistency in your billing processes.

    Setting Up Laravel Cashier

    Before we get started, you'll need a fresh Laravel application. Once you have that, installing Cashier is a breeze. First, require the package via Composer:

    composer require laravel/cashier
    

    Next, you'll need to run Cashier's migrations to set up the necessary database tables. This command will create tables to store subscription information, such as the user's subscription status, payment methods, and more:

    php artisan migrate
    

    After running the migrations, you should add the Billable trait to your User model. This trait provides your user model with the methods necessary to interact with Cashier. Open your app/Models/User.php file and add the following:

    use Laravel\Cashier\Billable;
    
    class User extends Authenticatable
    {
        use Billable;
    
        // ...
    }
    

    Finally, configure your Stripe or Paddle API keys in your .env file. This is crucial for Cashier to communicate with the payment gateway. Make sure to keep your API keys secure and never commit them to your repository.

    STRIPE_KEY=your_stripe_public_key
    STRIPE_SECRET=your_stripe_secret_key
    

    With these steps completed, your Laravel application is now equipped with Cashier, ready to handle all your subscription billing needs. This setup process ensures that your application is correctly configured to manage user subscriptions and process payments securely.

    Creating Subscription Plans

    Creating subscription plans is a fundamental part of using Laravel Cashier. Subscription plans define the different tiers of service you offer and their corresponding prices. With Cashier, you can easily define these plans directly in Stripe or Paddle and then reference them in your application. Let's walk through how to create a subscription plan using Stripe as an example.

    First, log into your Stripe dashboard and navigate to the Products section. Here, you can create a new product, which represents the service or feature you're offering. Give your product a descriptive name, such as "Premium Subscription," and set any other relevant details.

    Next, create a price for your product. The price determines how much the customer will be charged and how often (e.g., monthly, yearly). You can set the currency, amount, and billing interval. For example, you might create a monthly subscription for $10.

    Once you've created your product and price in Stripe, take note of the price ID. This ID will be used in your Laravel application to reference the subscription plan. In your application, you can now subscribe a user to this plan using Cashier's methods. For instance, you can add a subscription form to your website where users can select a plan and enter their payment information. When a user submits the form, you can use the newSubscription method to create a new subscription:

    $user->newSubscription('premium', 'price_xxxxxxxx')
         ->create($paymentMethod);
    

    In this example, 'premium' is the name of the subscription (you can choose any name), and 'price_xxxxxxxx' is the ID of the price you created in Stripe. The $paymentMethod is the payment method token obtained from Stripe. This simple yet powerful method allows you to create subscriptions with ease, managing the complexities behind the scenes.

    Building the Billing Portal

    Now, let's get to the exciting part: building the billing portal. A billing portal allows your users to manage their subscriptions, update payment methods, and view their invoice history. With Laravel Cashier, creating this portal is surprisingly straightforward. The main goal of building the portal is to give users more autonomy over their billing details, thereby reducing the amount of support needed and enhancing user satisfaction.

    Displaying Subscription Information

    First, you'll want to display the user's current subscription information. This includes the subscription status (e.g., active, canceled), the current plan, and the next payment date. You can easily retrieve this information using Cashier's methods. For example:

    $subscription = $user->subscription('premium');
    
    if ($subscription && $subscription->valid()) {
        echo 'Subscription Status: Active';
        echo 'Plan: ' . $subscription->name;
        echo 'Next Payment Date: ' . $subscription->next_payment_date->format('Y-m-d');
    }
    

    This code snippet checks if the user has an active subscription and displays the relevant details. You can customize this to show additional information, such as the subscription price and the date the subscription started.

    Updating Payment Methods

    Allowing users to update their payment methods is crucial for maintaining uninterrupted service. Cashier provides a simple way to do this using Stripe Elements or Paddle's payment forms. You can create a form that securely collects the user's payment information and then update the payment method using Cashier's updateDefaultPaymentMethod method:

    $user->updateDefaultPaymentMethod($paymentMethod);
    

    This method updates the user's default payment method with the new payment information. It's essential to handle this securely, ensuring that sensitive payment data is never stored on your server.

    Viewing Invoice History

    Providing users with access to their invoice history is essential for transparency and compliance. Cashier makes it easy to retrieve a list of invoices for a user:

    $invoices = $user->invoices();
    
    foreach ($invoices as $invoice) {
        echo '<a href="' . $invoice->invoice_url() . '">Invoice #' . $invoice->id . '</a>';
        echo 'Date: ' . $invoice->date()->format('Y-m-d');
        echo 'Amount: ' . $invoice->total();
    }
    

    This code retrieves all the user's invoices and displays them in a list. Each invoice is linked to a PDF version that the user can download. You can customize the invoice display to include additional information, such as the line items and payment status.

    Handling Webhooks

    Webhooks are essential for handling asynchronous events, such as failed payments, subscription cancellations, and invoice creation. Stripe and Paddle send webhooks to your application to notify you of these events. Cashier provides a convenient way to handle these webhooks.

    First, you'll need to configure your Stripe or Paddle webhook URL in your account settings. This URL should point to a route in your Laravel application that is handled by Cashier. Cashier includes a middleware that verifies the webhook signature, ensuring that the webhook is legitimate.

    To define the route that will handle the webhooks, add the following to your routes/web.php file:

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

    Cashier automatically handles the most common webhook events, such as invoice.payment_succeeded and customer.subscription.deleted. However, you can also define your own webhook handlers to perform custom actions. To do this, define a method on your User model that corresponds to the webhook event name:

    public function handleInvoicePaymentSucceeded($payload)
    {
        // Perform custom actions here
    }
    

    In this example, the handleInvoicePaymentSucceeded method will be called when the invoice.payment_succeeded webhook is received. You can access the webhook payload via the $payload variable. Handling webhooks correctly ensures that your application stays in sync with Stripe or Paddle and can respond appropriately to billing events.

    Customizing the Billing Portal

    While Cashier provides a solid foundation for your billing portal, you'll likely want to customize it to match your brand and provide a unique user experience. Customization can range from styling the views to modifying the underlying logic.

    Styling the Views

    The easiest way to customize the billing portal is to style the views. Cashier's views are designed to be easily overridden. You can publish the views to your application using the following command:

    php artisan vendor:publish --tag=cashier-views
    

    This command will copy the Cashier views to the resources/views/vendor/cashier directory. You can then modify these views to match your application's styling. For example, you can change the colors, fonts, and layout to create a seamless integration with your existing design.

    Modifying the Logic

    For more advanced customization, you can modify the underlying logic of the billing portal. Cashier provides a flexible API that allows you to extend its functionality. For example, you can add custom fields to the subscription form, integrate with third-party services, or implement custom billing logic.

    To modify the logic, you can create your own controllers and models that extend Cashier's classes. This allows you to override the default behavior and add your own functionality. For example, you can create a custom subscription controller that handles the subscription process and integrates with your application's user management system.

    Adding Custom Features

    You can also add custom features to your billing portal, such as the ability to upgrade or downgrade subscriptions, pause or resume subscriptions, or offer discounts and coupons. Cashier provides the methods necessary to implement these features. For example, you can use the swap method to upgrade or downgrade a subscription:

    $user->subscription('premium')->swap('price_yyyyyyy');
    

    This code swaps the user's current subscription to a new plan with the ID 'price_yyyyyyy'. You can also use the cancel and resume methods to pause or resume a subscription:

    $user->subscription('premium')->cancel();
    $user->subscription('premium')->resume();
    

    By customizing the billing portal, you can create a unique and engaging experience for your users, enhancing their satisfaction and loyalty.

    Conclusion

    Laravel Cashier is a powerful tool that simplifies subscription billing in your Laravel applications. By providing an expressive, fluent interface to Stripe and Paddle, Cashier takes away the headache of managing the complexities of these services directly. Whether you're building a SaaS platform, a membership site, or any application that requires recurring payments, Cashier abstracts the complexities, letting you focus on your core application logic. This article has walked you through the process of setting up Cashier, creating subscription plans, building a billing portal, handling webhooks, and customizing the portal to match your brand. With Cashier, you can create a seamless billing experience for your users, enhancing their satisfaction and loyalty. So go ahead, leverage Cashier to streamline your billing processes and focus on building amazing applications!