Laravel Cashier Paddle

Introduction

Laravel Cashier Paddle provides an expressive, fluent interface to Paddle’s subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading. In addition to basic subscription management, Cashier can handle: coupons, swapping subscription, subscription “quantities”, cancellation grace periods, and more.

While working with Cashier we recommend you also refer to Paddle’s user guides and API documentation.

Upgrading Cashier

When upgrading to a new version of Cashier, it’s important that you carefully review the upgrade guide.

Installation

First, require the Cashier package for Paddle with Composer:

  1. composer require laravel/cashier-paddle

{note} To ensure Cashier properly handles all Paddle events, remember to set up Cashier’s webhook handling.

Database Migrations

The Cashier service provider registers its own database migration directory, so remember to migrate your database after installing the package. The Cashier migrations will create a new customers table. In addition, a new subscriptions table will be created to store all of your customer’s subscriptions. Finally, a new receipts table will be created to store all of your receipt information:

  1. php artisan migrate

If you need to overwrite the migrations that ship with the Cashier package, you can publish them using the vendor:publish Artisan command:

  1. php artisan vendor:publish --tag="cashier-migrations"

If you would like to prevent Cashier’s migrations from running entirely, you may use the ignoreMigrations provided by Cashier. Typically, this method should be called in the register method of your AppServiceProvider:

  1. use Laravel\Paddle\Cashier;
  2. Cashier::ignoreMigrations();

Configuration

Billable Model

Before using Cashier, you must add the Billable trait to your user model definition. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons and updating payment method information:

  1. use Laravel\Paddle\Billable;
  2. class User extends Authenticatable
  3. {
  4. use Billable;
  5. }

If you have billable entities that are not users, you may also add the trait to those classes:

  1. use Laravel\Paddle\Billable;
  2. class Team extends Model
  3. {
  4. use Billable;
  5. }

API Keys

Next, you should configure your Paddle keys in your .env file. You can retrieve your Paddle API keys from the Paddle control panel:

  1. PADDLE_VENDOR_ID=your-paddle-vendor-id
  2. PADDLE_VENDOR_AUTH_CODE=your-paddle-vendor-auth-code
  3. PADDLE_PUBLIC_KEY="your-paddle-public-key"

Paddle JS

Paddle relies on its own JavaScript library to initiate the Paddle checkout widget. You can load the JavaScript library by placing the @paddleJS directive right before your application layout’s closing </head> tag:

  1. <head>
  2. ...
  3. @paddleJS
  4. </head>

Currency Configuration

The default Cashier currency is United States Dollars (USD). You can change the default currency by setting the CASHIER_CURRENCY environment variable:

  1. CASHIER_CURRENCY=EUR

In addition to configuring Cashier’s currency, you may also specify a locale to be used when formatting money values for display on invoices. Internally, Cashier utilizes PHP’s NumberFormatter class to set the currency locale:

  1. CASHIER_CURRENCY_LOCALE=nl_BE

{note} In order to use locales other than en, ensure the ext-intl PHP extension is installed and configured on your server.

Core Concepts

Pay Links

Paddle lacks an extensive CRUD API to perform state changes. Therefore, most interactions with Paddle are done through its checkout widget. Before we can display the checkout widget, we will generate a “pay link” using Cashier:

  1. $user = User::find(1);
  2. $payLink = $user->newSubscription('default', $premium = 34567)
  3. ->returnTo(route('home'))
  4. ->create();
  5. return view('billing', ['payLink' => $payLink]);

Cashier includes a paddle-button Blade component. We may pass the pay link URL to this component as a “prop”. When this button is clicked, Paddle’s checkout widget will be displayed:

  1. <x-paddle-button :url="$payLink" class="px-8 py-4">
  2. Subscribe
  3. </x-paddle-button>

By default, this will display a button with the standard Paddle styling. You can remove all Paddle styling by adding the data-theme="none" attribute to the component:

  1. <x-paddle-button :url="$payLink" class="px-8 py-4" data-theme="none">
  2. Subscribe
  3. </x-paddle-button>

The Paddle checkout widget is asynchronous. Once the user creates or updates a subscription within the widget, Paddle will send our application webhooks so that we may properly update the subscription state in our own database. Therefore, it’s important that you properly set up webhooks to accommodate for state changes from Paddle.

After a subscription state change, the delay for receiving the corresponding webhook is typically minimal but you should account for this in your application by considering that your user’s subscription might not be immediately available after completing the checkout.

For more information, you may review the Paddle API documentation on pay link generation.

Inline Checkout

If you don’t want to make use of the “overlay” style checkout widget, Paddle also has an option to display the widget inline. While this approach does not allow you to adjust any of the checkout’s HTML fields, it allows you to embed the widget within your application.

To make it easy for you to get started with inline checkout, Cashier includes a paddle-checkout Blade component. To get started, you should generate a pay link and pass the pay link to the component’s override attribute:

  1. <x-paddle-checkout :override="$payLink" class="w-full" />

To adjust the height of the inline checkout component, you may pass the height attribute to the Blade component:

  1. <x-paddle-checkout :override="$payLink" class="w-full" height="500" />

Inline Checkout Without Pay Links

Alternatively, you may customize the widget with custom options instead of using a pay link:

  1. $options = [
  2. 'product' => $productId,
  3. 'title' => 'Product Title',
  4. ];
  5. <x-paddle-checkout :options="$options" class="w-full" />

Please consult Paddle’s guide on Inline Checkout as well as their Parameter Reference for further details on available options.

{note} If you would like to also use the passthrough option when specifying custom options, you should provide a key / value array since Cashier will automatically handle converting the array to a JSON string. In addition, the customer_id passthrough option is reserved for internal Cashier usage.

User Identification

In contrast to Stripe, Paddle users are unique across the whole of Paddle, not unique per Paddle account. Because of this, Paddle’s API’s do not currently provide a method to update a user’s details such as their email address. When generating pay links, Paddle identifies users using the customer_email parameter. When creating a subscription, Paddle will try to match the user provided email to an existing Paddle user.

In light of this behavior, there are some important things to keep in mind when using Cashier and Paddle. First, you should be aware that even though subscriptions in Cashier are tied to the same application user, they could be tied to different users within Paddle’s internal systems. Secondly, each subscription has its own connected payment method information and could also have different email addresses within Paddle’s internal systems (depending on which email was assigned to the user when the subscription was created).

Therefore, when displaying subscriptions you should always inform the user which email address or payment method information is connected to the subscription on a per-subscription basis. Retrieving this information can be done with the following methods on the Subscription model:

  1. $subscription = $user->subscription('default');
  2. $customerEmailAddress = $subscription->paddleEmail();
  3. $paymentMethod = $subscription->paymentMethod();
  4. $cardBrand = $subscription->cardBrand();
  5. $cardLastFour = $subscription->cardLastFour();
  6. $cardExpirationDate = $subscription->cardExpirationDate();

There is currently no way to modify a user’s email address through the Paddle API. When a user wants to update their email address within Paddle, the only way for them to do so is to contact Paddle customer support. When communicating with Paddle, they need to provide the paddleEmail value of the subscription to assist Paddle in updating the correct user.

Prices

Paddle allows you to customize prices per currency, essentially allowing you to configure different prices for different countries. Cashier Paddle allows you to retrieve all of the prices for a given product using the productPrices method:

  1. use Laravel\Paddle\Cashier;
  2. // Retrieve prices for two products...
  3. $prices = Cashier::productPrices([123, 456]);

The currency will be determined based on the IP address of the request; however, you may optionally provide a specific country to retrieve prices for:

  1. use Laravel\Paddle\Cashier;
  2. // Retrieve prices for two products...
  3. $prices = Cashier::productPrices([123, 456], ['customer_country' => 'BE']);

After retrieving the prices you may display them however you wish:

  1. <ul>
  2. @foreach ($prices as $price)
  3. <li>{{ $price->product_title }} - {{ $price->price()->gross() }}</li>
  4. @endforeach
  5. </ul>

You may also display the net price (excludes tax) and display the tax amount separately:

  1. <ul>
  2. @foreach ($prices as $price)
  3. <li>{{ $price->product_title }} - {{ $price->price()->net() }} (+ {{ $price->price()->tax() }} tax)</li>
  4. @endforeach
  5. </ul>

If you retrieved prices for subscription plans you can display their initial and recurring price separately:

  1. <ul>
  2. @foreach ($prices as $price)
  3. <li>{{ $price->product_title }} - Initial: {{ $price->initialPrice()->gross() }} - Recurring: {{ $price->recurringPrice()->gross() }}</li>
  4. @endforeach
  5. </ul>

For more information, check Paddle’s API documentation on prices.

Customers

If a user is already a customer and you would like to display the prices that apply to that customer, you may do so by retrieving the prices directly from the customer instance:

  1. use App\Models\User;
  2. // Retrieve prices for two products...
  3. $prices = User::find(1)->productPrices([123, 456]);

Internally, Cashier will use the user’s paddleCountry method to retrieve the prices in their currency. So, for example, a user living in the United States will see prices in USD while a user in Belgium will see prices in EUR. If no matching currency can be found the default currency of the product will be used. You can customize all prices of a product or subscription plan in the Paddle control panel.

Coupons

You may also choose to display prices after a coupon reduction. When calling the productPrices method, coupons may be passed as a comma delimited string:

  1. use Laravel\Paddle\Cashier;
  2. $prices = Cashier::productPrices([123, 456], ['coupons' => 'SUMMERSALE,20PERCENTOFF']);

Then, display the calculated prices using the price method:

  1. <ul>
  2. @foreach ($prices as $price)
  3. <li>{{ $price->product_title }} - {{ $price->price()->gross() }}</li>
  4. @endforeach
  5. </ul>

You may display the original listed prices (without coupon discounts) using the listPrice method:

  1. <ul>
  2. @foreach ($prices as $price)
  3. <li>{{ $price->product_title }} - {{ $price->listPrice()->gross() }}</li>
  4. @endforeach
  5. </ul>

{note} When using the prices API, Paddle only allows to apply coupons to one-time purchase products and not to subscription plans.

Customers

Customer Defaults

Cashier allows you to set some useful defaults for your customer when creating pay links. Setting these defaults allow you to pre-fill a customer’s email address, country, and postcode so that they can immediately move on to the payment portion of the checkout widget. You can set these defaults by overriding the following methods on your billable user:

  1. /**
  2. * Get the customer's email address to associate with Paddle.
  3. *
  4. * @return string|null
  5. */
  6. public function paddleEmail()
  7. {
  8. return $this->email;
  9. }
  10. /**
  11. * Get the customer's country to associate with Paddle.
  12. *
  13. * This needs to be a 2 letter code. See the link below for supported countries.
  14. *
  15. * @return string|null
  16. * @link https://developer.paddle.com/reference/platform-parameters/supported-countries
  17. */
  18. public function paddleCountry()
  19. {
  20. //
  21. }
  22. /**
  23. * Get the customer's postcode to associate with Paddle.
  24. *
  25. * See the link below for countries which require this.
  26. *
  27. * @return string|null
  28. * @link https://developer.paddle.com/reference/platform-parameters/supported-countries#countries-requiring-postcode
  29. */
  30. public function paddlePostcode()
  31. {
  32. //
  33. }

These defaults will be used for every action in Cashier that generates a pay link.

Subscriptions

Creating Subscriptions

To create a subscription, first retrieve an instance of your billable model, which typically will be an instance of App\Models\User. Once you have retrieved the model instance, you may use the newSubscription method to create the model’s subscription pay link:

  1. $user = User::find(1);
  2. $payLink = $user->newSubscription('default', $premium = 12345)
  3. ->returnTo(route('home'))
  4. ->create();
  5. return view('billing', ['payLink' => $payLink]);

The first argument passed to the newSubscription method should be the name of the subscription. If your application only offers a single subscription, you might call this default or primary. The second argument is the specific plan the user is subscribing to. This value should correspond to the plan’s identifier in Paddle. The returnTo method accepts a URL that your user will be redirected to after they successfully complete the checkout.

The create method will create a pay link which you can use to generate a payment button. The payment button can be generated using the paddle-button Blade component that ships with Cashier Paddle:

  1. <x-paddle-button :url="$payLink" class="px-8 py-4">
  2. Subscribe
  3. </x-paddle-button>

After the user has finished their checkout, a subscription_created webhook will be dispatched from Paddle. Cashier will receive this webhook and setup the subscription for your customer. In order to make sure all webhooks are properly received and handled by your application, ensure you have properly setup webhook handling.

Additional Details

If you would like to specify additional customer or subscription details, you may do so by passing them as a key / value array to the create method:

  1. $payLink = $user->newSubscription('default', $monthly = 12345)
  2. ->returnTo(route('home'))
  3. ->create([
  4. 'vat_number' => $vatNumber,
  5. ]);

To learn more about the additional fields supported by Paddle, check out Paddle’s documentation on generating pay links.

Coupons

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

  1. $payLink = $user->newSubscription('default', $monthly = 12345)
  2. ->returnTo(route('home'))
  3. ->withCoupon('code')
  4. ->create();

Metadata

You can also pass an array of metadata using the withMetadata method:

  1. $payLink = $user->newSubscription('default', $monthly = 12345)
  2. ->returnTo(route('home'))
  3. ->withMetadata(['key' => 'value'])
  4. ->create();

{note} When providing metadata, please avoid using subscription_name as a metadata key. This key is reserved for internal use by Cashier.

Checking Subscription Status

Once a user is subscribed to your application, you may check their subscription status using a variety of convenient methods. First, the subscribed method returns true if the user has an active subscription, even if the subscription is currently within its trial period:

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

The subscribed method also makes a great candidate for a route middleware, allowing you to filter access to routes and controllers based on the user’s subscription status:

  1. public function handle($request, Closure $next)
  2. {
  3. if ($request->user() && ! $request->user()->subscribed('default')) {
  4. // This user is not a paying customer...
  5. return redirect('billing');
  6. }
  7. return $next($request);
  8. }

If you would like to determine if a user is still within their trial period, you may use the onTrial method. This method can be useful for displaying a warning to the user that they are still on their trial period:

  1. if ($user->subscription('default')->onTrial()) {
  2. //
  3. }

The subscribedToPlan method may be used to determine if the user is subscribed to a given plan based on a given Paddle plan ID. In this example, we will determine if the user’s default subscription is actively subscribed to the monthly plan:

  1. if ($user->subscribedToPlan($monthly = 12345, 'default')) {
  2. //
  3. }

By passing an array to the subscribedToPlan method, you may determine if the user’s default subscription is actively subscribed to the monthly or the yearly plan:

  1. if ($user->subscribedToPlan([$monthly = 12345, $yearly = 54321], 'default')) {
  2. //
  3. }

The recurring method may be used to determine if the user is currently subscribed and is no longer within their trial period:

  1. if ($user->subscription('default')->recurring()) {
  2. //
  3. }

Cancelled Subscription Status

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

  1. if ($user->subscription('default')->cancelled()) {
  2. //
  3. }

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 originally scheduled to expire 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->subscription('default')->onGracePeriod()) {
  2. //
  3. }

To determine if the user has cancelled their subscription and is no longer within their “grace period”, you may use the ended method:

  1. if ($user->subscription('default')->ended()) {
  2. //
  3. }

Subscription Scopes

Most subscription states are also available as query scopes so that you may easily query your database for subscriptions that are in a given state:

  1. // Get all active subscriptions...
  2. $subscriptions = Subscription::query()->active()->get();
  3. // Get all of the cancelled subscriptions for a user...
  4. $subscriptions = $user->subscriptions()->cancelled()->get();

A complete list of available scopes is available below:

  1. Subscription::query()->active();
  2. Subscription::query()->onTrial();
  3. Subscription::query()->notOnTrial();
  4. Subscription::query()->pastDue();
  5. Subscription::query()->recurring();
  6. Subscription::query()->ended();
  7. Subscription::query()->paused();
  8. Subscription::query()->notPaused();
  9. Subscription::query()->onPausedGracePeriod();
  10. Subscription::query()->notOnPausedGracePeriod();
  11. Subscription::query()->cancelled();
  12. Subscription::query()->notCancelled();
  13. Subscription::query()->onGracePeriod();
  14. Subscription::query()->notOnGracePeriod();

Past Due Status

If a payment fails for a subscription, it will be marked as past_due. When your subscription is in this state it will not be active until the customer has updated their payment information. You may determine if a subscription is past due using the pastDue method on the subscription instance:

  1. if ($user->subscription('default')->pastDue()) {
  2. //
  3. }

When a subscription is past due, you should instruct the user to update their payment information. You may configure how past due subscriptions are handled in your Paddle subscription settings.

If you would like subscriptions to still be considered active when they are past_due, you may use the keepPastDueSubscriptionsActive method provided by Cashier. Typically, this method should be called in the register method of your AppServiceProvider:

  1. use Laravel\Paddle\Cashier;
  2. /**
  3. * Register any application services.
  4. *
  5. * @return void
  6. */
  7. public function register()
  8. {
  9. Cashier::keepPastDueSubscriptionsActive();
  10. }

{note} When a subscription is in a past_due state it cannot be changed until payment information has been updated. Therefore, the swap and updateQuantity methods will throw an exception when the subscription is in a past_due state.

Subscription Single Charges

Subscription single charges allow you to charge subscribers with a one-time charge on top of their subscriptions:

  1. $response = $user->subscription('default')->charge(12.99, 'Support Add-on');

In contrast to single charges, this method will immediately charge the customer’s stored payment method for the subscription. The charge amount is always in the currency of which the subscription currently is set to.

Updating Payment Information

Paddle always saves a payment method per subscription. If you want to update the default payment method for a subscription, you should first generate a subscription “update URL” using the updateUrl method on the subscription model:

  1. $user = App\Models\User::find(1);
  2. $updateUrl = $user->subscription('default')->updateUrl();

Then, you may use the generated URL in combination with Cashier’s provided paddle-button Blade component to allow the user to initiate the Paddle widget and update their payment information:

  1. <x-paddle-button :url="$updateUrl" class="px-8 py-4">
  2. Update Card
  3. </x-paddle-button>

When a user has finished updating their information, a subscription_updated webhook will be dispatched by Paddle and the subscription details will be updated in your application’s database.

Changing Plans

After a user has subscribed to your application, they may occasionally want to change to a new subscription plan. To swap a user to a new subscription, you should pass the Paddle plan’s identifier to the subscription’s swap method:

  1. $user = App\Models\User::find(1);
  2. $user->subscription('default')->swap($premium = 34567);

If the user is on trial, the trial period will be maintained. Also, if a “quantity” exists for the subscription, that quantity will also be maintained.

If you would like to swap plans and cancel any trial period the user is currently on, you may use the skipTrial method:

  1. $user->subscription('default')
  2. ->skipTrial()
  3. ->swap($premium = 34567);

If you would like to swap plans and immediately invoice the user instead of waiting for their next billing cycle, you may use the swapAndInvoice method:

  1. $user = App\Models\User::find(1);
  2. $user->subscription('default')->swapAndInvoice($premium = 34567);

Prorations

By default, Paddle prorates charges when swapping between plans. The noProrate method may be used to update the subscription’s without prorating the charges:

  1. $user->subscription('default')->noProrate()->swap($premium = 34567);

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 incrementQuantity and decrementQuantity methods:

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

Alternatively, you may set a specific quantity using the updateQuantity method:

  1. $user->subscription('default')->updateQuantity(10);

The noProrate method may be used to update the subscription’s quantity without prorating the charges:

  1. $user->subscription('default')->noProrate()->updateQuantity(10);

Pausing Subscriptions

To pause a subscription, call the pause method on the user’s subscription:

  1. $user->subscription('default')->pause();

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

You may determine if a user has paused their subscription but are still on their “grace period” using the onPausedGracePeriod method:

  1. if ($user->subscription('default')->onPausedGracePeriod()) {
  2. //
  3. }

To resume a paused a subscription, you may call the unpause method on the user’s subscription:

  1. $user->subscription('default')->unpause();

{note} A subscription cannot be modified while it is paused. If you want to swap to a different plan or update quantities you must resume the subscription first.

Cancelling Subscriptions

To cancel a subscription, call the cancel method on the user’s subscription:

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

When a subscription is cancelled, Cashier will automatically set the ends_at column in 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.

You may determine if a user has cancelled their subscription but are still on their “grace period” using the onGracePeriod method:

  1. if ($user->subscription('default')->onGracePeriod()) {
  2. //
  3. }

If you wish to cancel a subscription immediately, you may call the cancelNow method on the user’s subscription:

  1. $user->subscription('default')->cancelNow();

{note} Paddle’s subscriptions cannot be resumed after cancellation. If your customer wishes to resume their subscription, they will have to subscribe to a new subscription.

Subscription Trials

With Payment Method Up Front

{note} While trialing and collecting payment method details up front, Paddle prevents any subscription changes such as swapping plans or updating quantities. If you want to allow a customer to swap plans during a trial the subscription must be cancelled and recreated.

If you would like to offer trial periods to your customers while still collecting payment method information up front, you should use the trialDays method when creating your subscription pay links:

  1. $user = User::find(1);
  2. $payLink = $user->newSubscription('default', $monthly = 12345)
  3. ->returnTo(route('home'))
  4. ->trialDays(10)
  5. ->create();
  6. return view('billing', ['payLink' => $payLink]);

This method will set the trial period ending date on the subscription record within the database, as well as instruct Paddle to not begin billing the customer until after this date.

{note} If the customer’s subscription is not cancelled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date.

You may determine if the user is within their trial period using either the onTrial method of the user instance or the onTrial method of the subscription instance. The two examples below have identical behavior:

  1. if ($user->onTrial('default')) {
  2. //
  3. }
  4. if ($user->subscription('default')->onTrial()) {
  5. //
  6. }

Defining Trial Days In Paddle / Cashier

You may choose to define how many trial days your plan’s receive in the Paddle dashboard or always pass them explicitly using Cashier. If you choose to define your plan’s trial days in Paddle you should be aware that new subscriptions, including new subscriptions for a customer that had a subscription in the past, will always receive a trial period unless you explicitly call the trialDays(0) method.

Without Payment Method Up Front

If you would like to offer trial periods without collecting the user’s payment method information up front, you may set the trial_ends_at column on the customer record attached to your user to your desired trial ending date. This is typically done during user registration:

  1. $user = User::create([
  2. // Other user properties...
  3. ]);
  4. $user->createAsCustomer([
  5. 'trial_ends_at' => now()->addDays(10)
  6. ]);

Cashier refers to this type of trial as a “generic trial”, since it is not attached to any existing subscription. The onTrial method on the User instance will return true if the current date is not past the value of trial_ends_at:

  1. if ($user->onTrial()) {
  2. // User is within their trial period...
  3. }

You may also use the onGenericTrial method if you wish to know specifically that the user is within their “generic” trial period and has not created an actual subscription yet:

  1. if ($user->onGenericTrial()) {
  2. // User is within their "generic" trial period...
  3. }

Once you are ready to create an actual subscription for the user, you may use the newSubscription method as usual:

  1. $user = User::find(1);
  2. $payLink = $user->newSubscription('default', $monthly = 12345)
  3. ->returnTo(route('home'))
  4. ->create();

{note} There is no way to extend or modify a trial period on a Paddle subscription after it has been created.

Handling Paddle Webhooks

{tip} You may use Valet’s share command to help test webhooks during local development.

Paddle can notify your application of a variety of events via webhooks. By default, a route that points to Cashier’s webhook controller is configured through the Cashier service provider. This controller will handle all incoming webhook requests.

By default, this controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Paddle subscription settings), subscription updates, and payment method changes; however, as we’ll soon discover, you can extend this controller to handle any webhook event you like.

To ensure your application can handle Paddle webhooks, be sure to configure the webhook URL in the Paddle control panel. By default, Cashier’s webhook controller listens to the /paddle/webhook URL path. The full list of all webhooks you should configure in the Paddle control panel are:

  • Subscription Created
  • Subscription Updated
  • Subscription Deleted
  • Payment Succeeded
  • Subscription Payment Succeeded

{note} Make sure you protect incoming requests with Cashier’s included webhook signature verification middleware.

Webhooks & CSRF Protection

Since Paddle webhooks need to bypass Laravel’s CSRF protection, be sure to list the URI as an exception in your VerifyCsrfToken middleware or list the route outside of the web middleware group:

  1. protected $except = [
  2. 'paddle/*',
  3. ];

Defining Webhook Event Handlers

Cashier automatically handles subscription cancellation on failed charges, but if you have additional webhook events you would like to handle, you should extend the WebhookController. Your method names should correspond to Cashier’s expected convention, specifically, methods should be prefixed with handle and the “camel case” name of the webhook you wish to handle. For example, if you wish to handle the payment_succeeded webhook, you should add a handlePaymentSucceeded method to the controller:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Laravel\Paddle\Http\Controllers\WebhookController as CashierController;
  4. class WebhookController extends CashierController
  5. {
  6. /**
  7. * Handle payment succeeded.
  8. *
  9. * @param array $payload
  10. * @return void
  11. */
  12. public function handlePaymentSucceeded($payload)
  13. {
  14. // Handle The Event
  15. }
  16. }

Next, define a route to your Cashier controller within your routes/web.php file. This will overwrite the route included with Cashier:

  1. use App\Http\Controllers\WebhookController;
  2. Route::post('paddle/webhook', WebhookController::class);

Cashier emits a Laravel\Paddle\Events\WebhookReceived event when a webhook is received and a Laravel\Paddle\Events\WebhookHandled event when a webhook was handled. Both events contain the full payload of the Paddle webhook.

Cashier also emit events dedicated to the type of the received webhook. In addition to the full payload from Paddle, they also contain the relevant models that were used to process the webhook such as the billable model, the subscription, or the receipt:

  • PaymentSucceeded
  • SubscriptionPaymentSucceeded
  • SubscriptionCreated
  • SubscriptionUpdated
  • SubscriptionCancelled

You can optionally also override the default, built-in webhook route by setting the CASHIER_WEBHOOK env variable in your .env file. This value should be the full URL to your webhook route and needs to match the URL set in your Paddle control panel:

  1. CASHIER_WEBHOOK=https://example.com/my-paddle-webhook-url

Failed Subscriptions

What if a customer’s credit card expires? No worries - Cashier’s Webhook controller will cancel the customer’s subscription for you. Failed payments will automatically be captured and handled by the controller. The controller will cancel the customer’s subscription when Paddle determines the subscription has failed (normally after three failed payment attempts).

Verifying Webhook Signatures

To secure your webhooks, you may use Paddle’s webhook signatures. For convenience, Cashier automatically includes a middleware which validates that the incoming Paddle webhook request is valid.

To enable webhook verification, ensure that the PADDLE_PUBLIC_KEY environment variable is set in your .env file. The public key may be retrieved from your Paddle account dashboard.

Single Charges

Simple Charge

If you would like to make a “one off” charge against a customer, you may use the charge method on a billable model instance to generate a pay link for the charge. The charge method accepts the charge amount (float) as its first argument and a charge description as its second argument:

  1. $payLink = $user->charge(12.99, 'Product Title');
  2. return view('pay', ['payLink' => $payLink]);

After generating the pay link, you may use Cashier’s provided paddle-button Blade component to allow the user to initiate the Paddle widget and complete the charge:

  1. <x-paddle-button :url="$payLink" class="px-8 py-4">
  2. Buy
  3. </x-paddle-button>

The charge method accepts an array as its third argument, allowing you to pass any options you wish to the underlying Paddle pay link creation. Please consult the Paddle documentation to learn more about the options available to you when creating charges:

  1. $payLink = $user->charge(12.99, 'Product Title', [
  2. 'custom_option' => $value,
  3. ]);

Charges happen in the currency specified in the cashier.currency configuration option. By default, this is set to USD. You may override the default currency by setting the CASHIER_CURRENCY in your .env file:

  1. CASHIER_CURRENCY=EUR

You can also override prices per currency using Paddle’s dynamic pricing matching system. To do so, pass an array of prices instead of a fixed amount:

  1. $payLink = $user->charge([
  2. 'USD:19.99',
  3. 'EUR:15.99',
  4. ], 'Product Title');

Charging Products

If you would like to make a “one off” charge against a specific product configured within Paddle, you may use the chargeProduct method on a billable model instance to generate a pay link:

  1. $payLink = $user->chargeProduct($productId);
  2. return view('pay', ['payLink' => $payLink]);

Then, you may provide the pay link to the paddle-button component to allow the user to initialize the Paddle widget:

  1. <x-paddle-button :url="$payLink" class="px-8 py-4">
  2. Buy
  3. </x-paddle-button>

The chargeProduct method accepts an array as its second argument, allowing you to pass any options you wish to the underlying Paddle pay link creation. Please consult the Paddle documentation regarding the options that are available to you when creating charges:

  1. $payLink = $user->chargeProduct($productId, [
  2. 'custom_option' => $value,
  3. ]);

Refunding Orders

If you need to refund a Paddle order, you may use the refund method. This method accepts the Paddle Order ID as its first argument. You may retrieve receipts for a given billable entity using the receipts method:

  1. $receipt = $user->receipts()->first();
  2. $refundRequestId = $user->refund($receipt->order_id);

You may also optionally specify a specific amount to refund as well as a reason for the refund:

  1. $receipt = $user->receipts()->first();
  2. $refundRequestId = $user->refund(
  3. $receipt->order_id, 5.00, 'Unused product time'
  4. );

{tip} You can use the $refundRequestId as a reference for the refund when contacting Paddle support.

Receipts

You may easily retrieve an array of a billable model’s receipts using the receipts method:

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

When listing the receipts for the customer, you may use the receipt’s helper methods to display the relevant receipt information. For example, you may wish to list every receipt in a table, allowing the user to easily download any of the receipts:

  1. <table>
  2. @foreach ($receipts as $receipt)
  3. <tr>
  4. <td>{{ $receipt->paid_at->toFormattedDateString() }}</td>
  5. <td>{{ $receipt->amount() }}</td>
  6. <td><a href="{{ $receipt->receipt_url }}" target="_blank">Download</a></td>
  7. </tr>
  8. @endforeach
  9. </table>

Past & Upcoming Payments

You may use the lastPayment and nextPayment methods to display a customer’s past or upcoming payments for recurring subscriptions:

  1. $subscription = $user->subscription('default');
  2. $lastPayment = $subscription->lastPayment();
  3. $nextPayment = $subscription->nextPayment();

Both of these methods will return an instance of Laravel\Paddle\Payment; however, nextPayment will return null when the billing cycle has ended (such as when a subscription has been cancelled):

  1. Next payment: {{ $nextPayment->amount() }} due on {{ $nextPayment->date()->format('d/m/Y') }}

Handling Failed Payments

Subscription payments fail for various reasons, such as expired cards or a card having insufficient funds. When this happens, we recommend that you let Paddle handle payment failures for you. Specifically, you may setup Paddle’s automatic billing emails in your Paddle dashboard.

Alternatively, you can perform more precise customization by catching the subscription_payment_failed webhook and enabling the “Subscription Payment Failed” option in the Webhook settings of your Paddle dashboard:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Laravel\Paddle\Http\Controllers\WebhookController as CashierController;
  4. class WebhookController extends CashierController
  5. {
  6. /**
  7. * Handle subscription payment failed.
  8. *
  9. * @param array $payload
  10. * @return void
  11. */
  12. public function handleSubscriptionPaymentFailed($payload)
  13. {
  14. // Handle the failed subscription payment...
  15. }
  16. }

Testing

Paddle currently lacks a proper CRUD API so you will need to manually test your billing flow. Paddle also lacks a sandboxed developer environment so any card charges you make are live charges. In order to work around this, we recommend you use coupons with a 100% discount or free products during testing.