Cashier (Stripe)
Laravel Cashier (Stripe)
- Introduction
- Upgrading Cashier
- Installation
- Database Migrations
- Configuration
- Billable Model
- API Keys
- Currency Configuration
- Tax Configuration
- Logging
- Using Custom Models
- Customers
- Retrieving Customers
- Creating Customers
- Updating Customers
- Balances
- Tax IDs
- Syncing Customer Data With Stripe
- Billing Portal
- Payment Methods
- Storing Payment Methods
- Retrieving Payment Methods
- Determining If A User Has A Payment Method
- Updating The Default Payment Method
- Adding Payment Methods
- Deleting Payment Methods
- Subscriptions
- Creating Subscriptions
- Checking Subscription Status
- Changing Prices
- Subscription Quantity
- Subscriptions With Multiple Products
- Multiple Subscriptions
- Metered Billing
- Subscription Taxes
- Subscription Anchor Date
- Canceling Subscriptions
- Resuming Subscriptions
- Subscription Trials
- With Payment Method Up Front
- Without Payment Method Up Front
- Extending Trials
- Handling Stripe Webhooks
- Defining Webhook Event Handlers
- Verifying Webhook Signatures
- Single Charges
- Simple Charge
- Charge With Invoice
- Creating Payment Intents
- Refunding Charges
- Checkout
- Product Checkouts
- Single Charge Checkouts
- Subscription Checkouts
- Collecting Tax IDs
- Guest Checkouts
- Invoices
- Retrieving Invoices
- Upcoming Invoices
- Previewing Subscription Invoices
- Generating Invoice PDFs
- Handling Failed Payments
- Strong Customer Authentication (SCA)
- Payments Requiring Additional Confirmation
- Off-session Payment Notifications
- Stripe SDK
- Testing
Introduction
Laravel Cashier Stripe 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.
Upgrading Cashier
When upgrading to a new version of Cashier, it’s important that you carefully review the upgrade guide.
Warning
To prevent breaking changes, Cashier uses a fixed Stripe API version. Cashier 14 utilizes Stripe API version2022-11-15. The Stripe API version will be updated on minor releases in order to make use of new Stripe features and improvements.
Installation
First, install the Cashier package for Stripe using the Composer package manager:
composer require laravel/cashier
Warning
To ensure Cashier properly handles all Stripe events, remember to set up Cashier’s webhook handling.
Database Migrations
Cashier’s service provider registers its own database migration directory, so remember to migrate your database after installing the package. The Cashier migrations will add several columns to your users table as well as create a new subscriptions table to hold all of your customer’s subscriptions:
php artisan migrate
If you need to overwrite the migrations that ship with Cashier, you can publish them using the vendor:publish Artisan command:
php artisan vendor:publish --tag="cashier-migrations"
If you would like to prevent Cashier’s migrations from running entirely, you may use the ignoreMigrations method provided by Cashier. Typically, this method should be called in the register method of your AppServiceProvider:
use Laravel\Cashier\Cashier; /** * Register any application services. */public function register(): void{ Cashier::ignoreMigrations();}
Warning
Stripe recommends that any column used for storing Stripe identifiers should be case-sensitive. Therefore, you should ensure the column collation for thestripe_idcolumn is set toutf8_binwhen using MySQL. More information regarding this can be found in the Stripe documentation.
Configuration
Billable Model
Before using Cashier, add the Billable trait to your billable model definition. Typically, this will be the App\Models\User model. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons, and updating payment method information:
use Laravel\Cashier\Billable; class User extends Authenticatable{ use Billable;}
Cashier assumes your billable model will be the App\Models\User class that ships with Laravel. If you wish to change this you may specify a different model via the useCustomerModel method. This method should typically be called in the boot method of your AppServiceProvider class:
use App\Models\Cashier\User;use Laravel\Cashier\Cashier; /** * Bootstrap any application services. */public function boot(): void{ Cashier::useCustomerModel(User::class);}
Warning
If you’re using a model other than Laravel’s suppliedApp\Models\Usermodel, you’ll need to publish and alter the Cashier migrations provided to match your alternative model’s table name.
API Keys
Next, you should configure your Stripe API keys in your application’s .env file. You can retrieve your Stripe API keys from the Stripe control panel:
STRIPE_KEY=your-stripe-keySTRIPE_SECRET=your-stripe-secretSTRIPE_WEBHOOK_SECRET=your-stripe-webhook-secret
Warning
You should ensure that theSTRIPE_WEBHOOK_SECRETenvironment variable is defined in your application’s.envfile, as this variable is used to ensure that incoming webhooks are actually from Stripe.
Currency Configuration
The default Cashier currency is United States Dollars (USD). You can change the default currency by setting the CASHIER_CURRENCY environment variable within your application’s .env file:
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:
CASHIER_CURRENCY_LOCALE=nl_BE
Warning
In order to use locales other thanen, ensure theext-intlPHP extension is installed and configured on your server.
Tax Configuration
Thanks to Stripe Tax, it’s possible to automatically calculate taxes for all invoices generated by Stripe. You can enable automatic tax calculation by invoking the calculateTaxes method in the boot method of your application’s App\Providers\AppServiceProvider class:
use Laravel\Cashier\Cashier; /** * Bootstrap any application services. */public function boot(): void{ Cashier::calculateTaxes();}
Once tax calculation has been enabled, any new subscriptions and any one-off invoices that are generated will receive automatic tax calculation.
For this feature to work properly, your customer’s billing details, such as the customer’s name, address, and tax ID, need to be synced to Stripe. You may use the customer data synchronization and Tax ID methods offered by Cashier to accomplish this.
Warning
No tax is calculated for single charges or single charge checkouts.
Logging
Cashier allows you to specify the log channel to be used when logging fatal Stripe errors. You may specify the log channel by defining the CASHIER_LOGGER environment variable within your application’s .env file:
CASHIER_LOGGER=stack
Exceptions that are generated by API calls to Stripe will be logged through your application’s default log channel.
Using Custom Models
You are free to extend the models used internally by Cashier by defining your own model and extending the corresponding Cashier model:
use Laravel\Cashier\Subscription as CashierSubscription; class Subscription extends CashierSubscription{ // ...}
After defining your model, you may instruct Cashier to use your custom model via the Laravel\Cashier\Cashier class. Typically, you should inform Cashier about your custom models in the boot method of your application’s App\Providers\AppServiceProvider class:
use App\Models\Cashier\Subscription;use App\Models\Cashier\SubscriptionItem; /** * Bootstrap any application services. */public function boot(): void{ Cashier::useSubscriptionModel(Subscription::class); Cashier::useSubscriptionItemModel(SubscriptionItem::class);}
Customers
Retrieving Customers
You can retrieve a customer by their Stripe ID using the Cashier::findBillable method. This method will return an instance of the billable model:
use Laravel\Cashier\Cashier; $user = Cashier::findBillable($stripeId);
Creating Customers
Occasionally, you may wish to create a Stripe customer without beginning a subscription. You may accomplish this using the createAsStripeCustomer method:
$stripeCustomer = $user->createAsStripeCustomer();
Once the customer has been created in Stripe, you may begin a subscription at a later date. You may provide an optional $options array to pass in any additional customer creation parameters that are supported by the Stripe API:
$stripeCustomer = $user->createAsStripeCustomer($options);
You may use the asStripeCustomer method if you want to return the Stripe customer object for a billable model:
$stripeCustomer = $user->asStripeCustomer();
The createOrGetStripeCustomer method may be used if you would like to retrieve the Stripe customer object for a given billable model but are not sure whether the billable model is already a customer within Stripe. This method will create a new customer in Stripe if one does not already exist:
$stripeCustomer = $user->createOrGetStripeCustomer();
Updating Customers
Occasionally, you may wish to update the Stripe customer directly with additional information. You may accomplish this using the updateStripeCustomer method. This method accepts an array of customer update options supported by the Stripe API:
$stripeCustomer = $user->updateStripeCustomer($options);
Balances
Stripe allows you to credit or debit a customer’s “balance”. Later, this balance will be credited or debited on new invoices. To check the customer’s total balance you may use the balance method that is available on your billable model. The balance method will return a formatted string representation of the balance in the customer’s currency:
$balance = $user->balance();
To credit a customer’s balance, you may provide a value to the creditBalance method. If you wish, you may also provide a description:
$user->creditBalance(500, 'Premium customer top-up.');
Providing a value to the debitBalance method will debit the customer’s balance:
$user->debitBalance(300, 'Bad usage penalty.');
The applyBalance method will create new customer balance transactions for the customer. You may retrieve these transaction records using the balanceTransactions method, which may be useful in order to provide a log of credits and debits for the customer to review:
// Retrieve all transactions...$transactions = $user->balanceTransactions(); foreach ($transactions as $transaction) { // Transaction amount... $amount = $transaction->amount(); // $2.31 // Retrieve the related invoice when available... $invoice = $transaction->invoice();}
Tax IDs
Cashier offers an easy way to manage a customer’s tax IDs. For example, the taxIds method may be used to retrieve all of the tax IDs that are assigned to a customer as a collection:
$taxIds = $user->taxIds();
You can also retrieve a specific tax ID for a customer by its identifier:
$taxId = $user->findTaxId('txi_belgium');
You may create a new Tax ID by providing a valid type and value to the createTaxId method:
$taxId = $user->createTaxId('eu_vat', 'BE0123456789');
The createTaxId method will immediately add the VAT ID to the customer’s account. Verification of VAT IDs is also done by Stripe; however, this is an asynchronous process. You can be notified of verification updates by subscribing to the customer.tax_id.updated webhook event and inspecting the VAT IDs verification parameter. For more information on handling webhooks, please consult the documentation on defining webhook handlers.
You may delete a tax ID using the deleteTaxId method:
$user->deleteTaxId('txi_belgium');
Syncing Customer Data With Stripe
Typically, when your application’s users update their name, email address, or other information that is also stored by Stripe, you should inform Stripe of the updates. By doing so, Stripe’s copy of the information will be in sync with your application’s.
To automate this, you may define an event listener on your billable model that reacts to the model’s updated event. Then, within your event listener, you may invoke the syncStripeCustomerDetails method on the model:
use App\Models\User;use function Illuminate\Events\queueable; /** * The "booted" method of the model. */protected static function booted(): void{ static::updated(queueable(function (User $customer) { if ($customer->hasStripeId()) { $customer->syncStripeCustomerDetails(); } }));}
Now, every time your customer model is updated, its information will be synced with Stripe. For convenience, Cashier will automatically sync your customer’s information with Stripe on the initial creation of the customer.
You may customize the columns used for syncing customer information to Stripe by overriding a variety of methods provided by Cashier. For example, you may override the stripeName method to customize the attribute that should be considered the customer’s “name” when Cashier syncs customer information to Stripe:
/** * Get the customer name that should be synced to Stripe. */public function stripeName(): string|null{ return $this->company_name;}
Similarly, you may override the stripeEmail, stripePhone, stripeAddress, and stripePreferredLocales methods. These methods will sync information to their corresponding customer parameters when updating the Stripe customer object. If you wish to take total control over the customer information sync process, you may override the syncStripeCustomerDetails method.
Billing Portal
Stripe offers an easy way to set up a billing portal so that your customer can manage their subscription, payment methods, and view their billing history. You can redirect your users to the billing portal by invoking the redirectToBillingPortal method on the billable model from a controller or route:
use Illuminate\Http\Request; Route::get('/billing-portal', function (Request $request) { return $request->user()->redirectToBillingPortal();});
By default, when the user is finished managing their subscription, they will be able to return to the home route of your application via a link within the Stripe billing portal. You may provide a custom URL that the user should return to by passing the URL as an argument to the redirectToBillingPortal method:
use Illuminate\Http\Request; Route::get('/billing-portal', function (Request $request) { return $request->user()->redirectToBillingPortal(route('billing'));});
If you would like to generate the URL to the billing portal without generating an HTTP redirect response, you may invoke the billingPortalUrl method:
$url = $request->user()->billingPortalUrl(route('billing'));
Payment Methods
Storing Payment Methods
In order to create subscriptions or perform “one-off” charges with Stripe, you will need to store a payment method and retrieve its identifier from Stripe. The approach used to accomplish this differs based on whether you plan to use the payment method for subscriptions or single charges, so we will examine both below.
Payment Methods For Subscriptions
When storing a customer’s credit card information for future use by a subscription, the Stripe “Setup Intents” API must be used to securely gather the customer’s payment method details. A “Setup Intent” indicates to Stripe the intention to charge a customer’s payment method. Cashier’s Billable trait includes the createSetupIntent method to easily create a new Setup Intent. You should invoke this method from the route or controller that will render the form which gathers your customer’s payment method details:
return view('update-payment-method', [ 'intent' => $user->createSetupIntent()]);
After you have created the Setup Intent and passed it to the view, you should attach its secret to the element that will gather the payment method. For example, consider this “update payment method” form:
<input id="card-holder-name" type="text"> <!-- Stripe Elements Placeholder --><div id="card-element"></div> <button id="card-button" data-secret="{{ $intent->client_secret }}"> Update Payment Method</button>
Next, the Stripe.js library may be used to attach a Stripe Element to the form and securely gather the customer’s payment details:
<script src="https://js.stripe.com/v3/"></script> <script> const stripe = Stripe('stripe-public-key'); const elements = stripe.elements(); const cardElement = elements.create('card'); cardElement.mount('#card-element');</script>
Next, the card can be verified and a secure “payment method identifier” can be retrieved from Stripe using Stripe’s confirmCardSetup method:
const cardHolderName = document.getElementById('card-holder-name');const cardButton = document.getElementById('card-button');const clientSecret = cardButton.dataset.secret; cardButton.addEventListener('click', async (e) => { const { setupIntent, error } = await stripe.confirmCardSetup( clientSecret, { payment_method: { card: cardElement, billing_details: { name: cardHolderName.value } } } ); if (error) { // Display "error.message" to the user... } else { // The card has been verified successfully... }});
After the card has been verified by Stripe, you may pass the resulting setupIntent.payment_method identifier to your Laravel application, where it can be attached to the customer. The payment method can either be added as a new payment method or used to update the default payment method. You can also immediately use the payment method identifier to create a new subscription.
Note
If you would like more information about Setup Intents and gathering customer payment details please review this overview provided by Stripe.
Payment Methods For Single Charges
Of course, when making a single charge against a customer’s payment method, we will only need to use a payment method identifier once. Due to Stripe limitations, you may not use the stored default payment method of a customer for single charges. You must allow the customer to enter their payment method details using the Stripe.js library. For example, consider the following form:
<input id="card-holder-name" type="text"> <!-- Stripe Elements Placeholder --><div id="card-element"></div> <button id="card-button"> Process Payment</button>
After defining such a form, the Stripe.js library may be used to attach a Stripe Element to the form and securely gather the customer’s payment details:
<script src="https://js.stripe.com/v3/"></script> <script> const stripe = Stripe('stripe-public-key'); const elements = stripe.elements(); const cardElement = elements.create('card'); cardElement.mount('#card-element');</script>
Next, the card can be verified and a secure “payment method identifier” can be retrieved from Stripe using Stripe’s createPaymentMethod method:
const cardHolderName = document.getElementById('card-holder-name');const cardButton = document.getElementById('card-button'); cardButton.addEventListener('click', async (e) => { const { paymentMethod, error } = await stripe.createPaymentMethod( 'card', cardElement, { billing_details: { name: cardHolderName.value } } ); if (error) { // Display "error.message" to the user... } else { // The card has been verified successfully... }});
If the card is verified successfully, you may pass the paymentMethod.id to your Laravel application and process a single charge.
Retrieving Payment Methods
The paymentMethods method on the billable model instance returns a collection of Laravel\Cashier\PaymentMethod instances:
$paymentMethods = $user->paymentMethods();
By default, this method will return payment methods of the card type. To retrieve payment methods of a different type, you may pass the type as an argument to the method:
$paymentMethods = $user->paymentMethods('sepa_debit');
To retrieve the customer’s default payment method, the defaultPaymentMethod method may be used:
$paymentMethod = $user->defaultPaymentMethod();
You can retrieve a specific payment method that is attached to the billable model using the findPaymentMethod method:
$paymentMethod = $user->findPaymentMethod($paymentMethodId);
Determining If A User Has A Payment Method
To determine if a billable model has a default payment method attached to their account, invoke the hasDefaultPaymentMethod method:
if ($user->hasDefaultPaymentMethod()) { // ...}
You may use the hasPaymentMethod method to determine if a billable model has at least one payment method attached to their account:
if ($user->hasPaymentMethod()) { // ...}
This method will determine if the billable model has payment methods of the card type. To determine if a payment method of another type exists for the model, you may pass the type as an argument to the method:
if ($user->hasPaymentMethod('sepa_debit')) { // ...}
Updating The Default Payment Method
The updateDefaultPaymentMethod method may be used to update a customer’s default payment method information. This method accepts a Stripe payment method identifier and will assign the new payment method as the default billing payment method:
$user->updateDefaultPaymentMethod($paymentMethod);
To sync your default payment method information with the customer’s default payment method information in Stripe, you may use the updateDefaultPaymentMethodFromStripe method:
$user->updateDefaultPaymentMethodFromStripe();
Warning
The default payment method on a customer can only be used for invoicing and creating new subscriptions. Due to limitations imposed by Stripe, it may not be used for single charges.
Adding Payment Methods
To add a new payment method, you may call the addPaymentMethod method on the billable model, passing the payment method identifier:
$user->addPaymentMethod($paymentMethod);
Note
To learn how to retrieve payment method identifiers please review the payment method storage documentation.
Deleting Payment Methods
To delete a payment method, you may call the delete method on the Laravel\Cashier\PaymentMethod instance you wish to delete:
$paymentMethod->delete();
The deletePaymentMethod method will delete a specific payment method from the billable model:
$user->deletePaymentMethod('pm_visa');
The deletePaymentMethods method will delete all of the payment method information for the billable model:
$user->deletePaymentMethods();
By default, this method will delete payment methods of the card type. To delete payment methods of a different type you can pass the type as an argument to the method:
$user->deletePaymentMethods('sepa_debit');
Warning
If a user has an active subscription, your application should not allow them to delete their default payment method.
Subscriptions
Subscriptions provide a way to set up recurring payments for your customers. Stripe subscriptions managed by Cashier provide support for multiple subscription prices, subscription quantities, trials, and more.
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:
use Illuminate\Http\Request; Route::post('/user/subscribe', function (Request $request) { $request->user()->newSubscription( 'default', 'price_monthly' )->create($request->paymentMethodId); // ...});
The first argument passed to the newSubscription method should be the internal name of the subscription. If your application only offers a single subscription, you might call this default or primary. This subscription name is only for internal application usage and is not meant to be shown to users. In addition, it should not contain spaces and it should never be changed after creating the subscription. The second argument is the specific price the user is subscribing to. This value should correspond to the price’s identifier in Stripe.
The create method, which accepts a Stripe payment method identifier or Stripe PaymentMethod object, will begin the subscription as well as update your database with the billable model’s Stripe customer ID and other relevant billing information.
Warning
Passing a payment method identifier directly to thecreatesubscription method will also automatically add it to the user’s stored payment methods.
Collecting Recurring Payments Via Invoice Emails
Instead of collecting a customer’s recurring payments automatically, you may instruct Stripe to email an invoice to the customer each time their recurring payment is due. Then, the customer may manually pay the invoice once they receive it. The customer does not need to provide a payment method up front when collecting recurring payments via invoices:
$user->newSubscription('default', 'price_monthly')->createAndSendInvoice();
The amount of time a customer has to pay their invoice before their subscription is cancelled is determined by the days_until_due option. By default, this is 30 days; however, you may provide a specific value for this option if you wish:
$user->newSubscription('default', 'price_monthly')->createAndSendInvoice([], [ 'days_until_due' => 30]);
Quantities
If you would like to set a specific quantity for the price when creating the subscription, you should invoke the quantity method on the subscription builder before creating the subscription:
$user->newSubscription('default', 'price_monthly') ->quantity(5) ->create($paymentMethod);
Additional Details
If you would like to specify additional customer or subscription options supported by Stripe, you may do so by passing them as the second and third arguments to the create method:
$user->newSubscription('default', 'price_monthly')->create($paymentMethod, [ 'email' => $email,], [ 'metadata' => ['note' => 'Some extra information.'],]);
Coupons
If you would like to apply a coupon when creating the subscription, you may use the withCoupon method:
$user->newSubscription('default', 'price_monthly') ->withCoupon('code') ->create($paymentMethod);
Or, if you would like to apply a Stripe promotion code, you may use the withPromotionCode method:
$user->newSubscription('default', 'price_monthly') ->withPromotionCode('promo_code_id') ->create($paymentMethod);
The given promotion code ID should be the Stripe API ID assigned to the promotion code and not the customer facing promotion code. If you need to find a promotion code ID based on a given customer facing promotion code, you may use the findPromotionCode method:
// Find a promotion code ID by its customer facing code...$promotionCode = $user->findPromotionCode('SUMMERSALE'); // Find an active promotion code ID by its customer facing code...$promotionCode = $user->findActivePromotionCode('SUMMERSALE');
In the example above, the returned $promotionCode object is an instance of Laravel\Cashier\PromotionCode. This class decorates an underlying Stripe\PromotionCode object. You can retrieve the coupon related to the promotion code by invoking the coupon method:
$coupon = $user->findPromotionCode('SUMMERSALE')->coupon();
The coupon instance allows you to determine the discount amount and whether the coupon represents a fixed discount or percentage based discount:
if ($coupon->isPercentage()) { return $coupon->percentOff().'%'; // 21.5%} else { return $coupon->amountOff(); // $5.99}
You can also retrieve the discounts that are currently applied to a customer or subscription:
$discount = $billable->discount(); $discount = $subscription->discount();
The returned Laravel\Cashier\Discount instances decorate an underlying Stripe\Discount object instance. You may retrieve the coupon related to this discount by invoking the coupon method:
$coupon = $subscription->discount()->coupon();
If you would like to apply a new coupon or promotion code to a customer or subscription, you may do so via the applyCoupon or applyPromotionCode methods:
$billable->applyCoupon('coupon_id');$billable->applyPromotionCode('promotion_code_id'); $subscription->applyCoupon('coupon_id');$subscription->applyPromotionCode('promotion_code_id');
Remember, you should use the Stripe API ID assigned to the promotion code and not the customer facing promotion code. Only one coupon or promotion code can be applied to a customer or subscription at a given time.
For more info on this subject, please consult the Stripe documentation regarding coupons and promotion codes.
Adding Subscriptions
If you would like to add a subscription to a customer who already has a default payment method you may invoke the add method on the subscription builder:
use App\Models\User; $user = User::find(1); $user->newSubscription('default', 'price_monthly')->add();
Creating Subscriptions From The Stripe Dashboard
You may also create subscriptions from the Stripe dashboard itself. When doing so, Cashier will sync newly added subscriptions and assign them a name of default. To customize the subscription name that is assigned to dashboard created subscriptions, extend the WebhookController and overwrite the newSubscriptionName method.
In addition, you may only create one type of subscription via the Stripe dashboard. If your application offers multiple subscriptions that use different names, only one type of subscription may be added through the Stripe dashboard.
Finally, you should always make sure to only add one active subscription per type of subscription offered by your application. If a customer has two default subscriptions, only the most recently added subscription will be used by Cashier even though both would be synced with your application’s database.
Checking Subscription Status
Once a customer is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the subscribed method returns true if the customer has an active subscription, even if the subscription is currently within its trial period. The subscribed method accepts the name of the subscription as its first argument:
if ($user->subscribed('default')) { // ...}
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:
<?php namespace App\Http\Middleware; use Closure;use Illuminate\Http\Request;use Symfony\Component\HttpFoundation\Response; class EnsureUserIsSubscribed{ /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { if ($request->user() && ! $request->user()->subscribed('default')) { // This user is not a paying customer... return redirect('billing'); } return $next($request); }}
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 determining if you should display a warning to the user that they are still on their trial period:
if ($user->subscription('default')->onTrial()) { // ...}
The subscribedToProduct method may be used to determine if the user is subscribed to a given product based on a given Stripe product’s identifier. In Stripe, products are collections of prices. In this example, we will determine if the user’s default subscription is actively subscribed to the application’s “premium” product. The given Stripe product identifier should correspond to one of your product’s identifiers in the Stripe dashboard:
if ($user->subscribedToProduct('prod_premium', 'default')) { // ...}
By passing an array to the subscribedToProduct method, you may determine if the user’s default subscription is actively subscribed to the application’s “basic” or “premium” product:
if ($user->subscribedToProduct(['prod_basic', 'prod_premium'], 'default')) { // ...}
The subscribedToPrice method may be used to determine if a customer’s subscription corresponds to a given price ID:
if ($user->subscribedToPrice('price_basic_monthly', 'default')) { // ...}
The recurring method may be used to determine if the user is currently subscribed and is no longer within their trial period:
if ($user->subscription('default')->recurring()) { // ...}
Warning
If a user has two subscriptions with the same name, the most recent subscription will always be returned by thesubscriptionmethod. For example, a user might have two subscription records nameddefault; however, one of the subscriptions may be an old, expired subscription, while the other is the current, active subscription. The most recent subscription will always be returned while older subscriptions are kept in the database for historical review.
Canceled Subscription Status
To determine if the user was once an active subscriber but has canceled their subscription, you may use the canceled method:
if ($user->subscription('default')->canceled()) { // ...}
You may also determine if a user has canceled 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:
if ($user->subscription('default')->onGracePeriod()) { // ...}
To determine if the user has canceled their subscription and is no longer within their “grace period”, you may use the ended method:
if ($user->subscription('default')->ended()) { // ...}
Incomplete and Past Due Status
If a subscription requires a secondary payment action after creation the subscription will be marked as incomplete. Subscription statuses are stored in the stripe_status column of Cashier’s subscriptions database table.
Similarly, if a secondary payment action is required when swapping prices the subscription will be marked as past_due. When your subscription is in either of these states it will not be active until the customer has confirmed their payment. Determining if a subscription has an incomplete payment may be accomplished using the hasIncompletePayment method on the billable model or a subscription instance:
if ($user->hasIncompletePayment('default')) { // ...} if ($user->subscription('default')->hasIncompletePayment()) { // ...}
When a subscription has an incomplete payment, you should direct the user to Cashier’s payment confirmation page, passing the latestPayment identifier. You may use the latestPayment method available on subscription instance to retrieve this identifier:
<a href="{{ route('cashier.payment', $subscription->latestPayment()->id) }}"> Please confirm your payment.</a>
If you would like the subscription to still be considered active when it’s in a past_due or incomplete state, you may use the keepPastDueSubscriptionsActive and keepIncompleteSubscriptionsActive methods provided by Cashier. Typically, these methods should be called in the register method of your App\Providers\AppServiceProvider:
use Laravel\Cashier\Cashier; /** * Register any application services. */public function register(): void{ Cashier::keepPastDueSubscriptionsActive(); Cashier::keepIncompleteSubscriptionsActive();}
Warning
When a subscription is in anincompletestate it cannot be changed until the payment is confirmed. Therefore, theswapandupdateQuantitymethods will throw an exception when the subscription is in anincompletestate.
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:
// Get all active subscriptions...$subscriptions = Subscription::query()->active()->get(); // Get all of the canceled subscriptions for a user...$subscriptions = $user->subscriptions()->canceled()->get();
A complete list of available scopes is available below:
Subscription::query()->active();Subscription::query()->canceled();Subscription::query()->ended();Subscription::query()->incomplete();Subscription::query()->notCanceled();Subscription::query()->notOnGracePeriod();Subscription::query()->notOnTrial();Subscription::query()->onGracePeriod();Subscription::query()->onTrial();Subscription::query()->pastDue();Subscription::query()->recurring();
Changing Prices
After a customer is subscribed to your application, they may occasionally want to change to a new subscription price. To swap a customer to a new price, pass the Stripe price’s identifier to the swap method. When swapping prices, it is assumed that the user would like to re-activate their subscription if it was previously canceled. The given price identifier should correspond to a Stripe price identifier available in the Stripe dashboard:
use App\Models\User; $user = App\Models\User::find(1); $user->subscription('default')->swap('price_yearly');
If the customer is on trial, the trial period will be maintained. Additionally, if a “quantity” exists for the subscription, that quantity will also be maintained.
If you would like to swap prices and cancel any trial period the customer is currently on, you may invoke the skipTrial method:
$user->subscription('default') ->skipTrial() ->swap('price_yearly');
If you would like to swap prices and immediately invoice the customer instead of waiting for their next billing cycle, you may use the swapAndInvoice method:
$user = User::find(1); $user->subscription('default')->swapAndInvoice('price_yearly');
Prorations
By default, Stripe prorates charges when swapping between prices. The noProrate method may be used to update the subscription’s price without prorating the charges:
$user->subscription('default')->noProrate()->swap('price_yearly');
For more information on subscription proration, consult the Stripe documentation.
Warning
Executing thenoProratemethod before theswapAndInvoicemethod will have no effect on proration. An invoice will always be issued.
Subscription Quantity
Sometimes subscriptions are affected by “quantity”. For example, a project management application might charge $10 per month per project. You may use the incrementQuantity and decrementQuantity methods to easily increment or decrement your subscription quantity:
use App\Models\User; $user = User::find(1); $user->subscription('default')->incrementQuantity(); // Add five to the subscription's current quantity...$user->subscription('default')->incrementQuantity(5); $user->subscription('default')->decrementQuantity(); // Subtract five from the subscription's current quantity...$user->subscription('default')->decrementQuantity(5);
Alternatively, you may set a specific quantity using the updateQuantity method:
$user->subscription('default')->updateQuantity(10);
The noProrate method may be used to update the subscription’s quantity without prorating the charges:
$user->subscription('default')->noProrate()->updateQuantity(10);
For more information on subscription quantities, consult the Stripe documentation.
Quantities For Subscriptions With Multiple Products
If your subscription is a subscription with multiple products, you should pass the ID of the price whose quantity you wish to increment or decrement as the second argument to the increment / decrement methods:
$user->subscription('default')->incrementQuantity(1, 'price_chat');
(本文超出站点单文档体积上限,已按小节截断)
