### Integration Guide Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt A step-by-step guide to setting up and integrating Laravel Cashier Stripe into your application, including real-world implementation patterns and testing procedures. ```APIDOC ## Integration Guide This guide provides a practical walkthrough for integrating Laravel Cashier Stripe. ### Setup and Implementation: - **5-Step Setup Guide**: Comprehensive installation and initial configuration. - **10 Implementation Patterns**: Real-world examples covering simple subscriptions, multi-plan systems, metered billing, one-off charges, custom invoicing, and more. - **Webhook Handling**: Examples for setting up and processing webhook events. ### Testing and Best Practices: - **Testing Guide**: Includes card numbers and CLI commands for testing. - **Unit Test Examples**: Demonstrations of how to write unit tests. - **8 Critical Best Practices**: Recommendations for optimal usage and performance. Refer to `integration-guide.md` for detailed instructions and examples. ``` -------------------------------- ### Install Laravel Cashier Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md Install the Cashier package using Composer. ```bash composer require laravel/cashier ``` -------------------------------- ### Testing Guide Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt Provides guidance and examples for testing your Laravel Cashier Stripe implementation. ```APIDOC ## Testing Guide This guide provides examples and best practices for testing your Laravel Cashier Stripe implementation. ### Content: - Testing examples. - Strategies for ensuring your billing logic is correct. ``` -------------------------------- ### Create and Retrieve Setup Intents Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Use this to create a SetupIntent for collecting payment methods without immediate charging. You can then pass the client secret to your frontend or retrieve it later by its ID. ```php // Create SetupIntent $intent = $user->createSetupIntent([ 'payment_method_types' => ['card'], ]); // Pass to frontend return ['clientSecret' => $intent->client_secret]; // Retrieve later $intent = $user->findSetupIntent('seti_123456'); ``` -------------------------------- ### Webhook Handling Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt A guide to handling webhooks from Stripe using Laravel Cashier. ```APIDOC ## Webhook Handling This guide details how to handle webhooks from Stripe using Laravel Cashier. ### Content: - Specific guide for webhook handling. - Includes patterns and best practices for processing incoming webhook events. ``` -------------------------------- ### Migration Guide Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt Assists users in migrating to newer versions of Laravel Cashier Stripe. ```APIDOC ## Migration Guide This guide provides information and steps for migrating to newer versions of Laravel Cashier Stripe. ### Content: - Migration guide included. ``` -------------------------------- ### Configuration Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt Details all configuration options available for Laravel Cashier Stripe, including setup steps and environment variable usage. ```APIDOC ## Configuration Documentation This section covers all configuration options for Laravel Cashier Stripe. ### Key Areas: - All configuration options are documented. - Setup steps are provided in the integration guide. - Environment variables are referenced in the README. ### Purpose: - Enables users to customize Cashier's behavior according to their application's needs. ``` -------------------------------- ### Handling InvalidCustomer Exception Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Example of catching an InvalidCustomer exception and creating the customer on Stripe if they do not exist. ```php try { $invoice = $user->invoice(); } catch (InvalidCustomer $e) { // Customer not yet created on Stripe $user->createAsStripeCustomer(); } ``` -------------------------------- ### Get Applied Discounts Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves an array of discounts applied to the invoice, or null if no discounts are applied. ```php public function discounts(): Discount[]|null ``` -------------------------------- ### Skip Trial Period Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Use the `skipTrial` method to bypass the trial period and start immediate billing for the subscription. ```php public function skipTrial(): $this ``` -------------------------------- ### Coupon Percent Off Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the percentage discount (0-100). Returns null if the coupon is not a percentage-off type. ```php public function percentOff(): ?int ``` -------------------------------- ### Create Guest Checkout Session Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md This example shows how to create a Stripe Checkout session for a guest user, meaning no authenticated customer is associated. You can specify the prices and URLs for success and cancellation. ```php // Checkout without a customer $checkout = Checkout::guest() ->create(['price_123'], [ 'success_url' => route('success'), 'cancel_url' => route('cancel'), ]); return $checkout->redirect(); ``` -------------------------------- ### Cashier Core API Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the Cashier Facade static methods, Billable Trait, and core classes like Subscription, Payment, and Invoice. This section details over 50 method signatures with parameters, return types, and code examples. ```APIDOC ## Cashier Core API Overview This section covers the primary API surface exposed by the Laravel Cashier Stripe package. ### Key Components: - **Cashier Facade**: Provides static methods for interacting with Cashier. - **Billable Trait**: Methods available on Eloquent models that can be billed. - **Subscription Class**: Manages subscription lifecycles and details. - **Payment Class**: Handles payment status checks. - **Invoice Class**: Provides invoice formatting utilities. - **Checkout Class**: Manages Stripe Checkout session integration. ### Method Signatures: Over 50 method signatures are documented, including parameters, return types, and usage examples. Specific details can be found in the `cashier-core-api.md` file. ``` -------------------------------- ### Cashier::stripe() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Get or create a Stripe SDK client instance with configured API key and version. This is essential for making direct calls to the Stripe API. ```APIDOC ## Cashier::stripe() ### Description Get or create a Stripe SDK client instance with configured API key and version. ### Method `public static function stripe(array $options = []): Stripe\StripeClient` ### Parameters #### Path Parameters - **$options** (`array`) - Optional - Options to merge with Stripe client config ### Response #### Success Response - **Stripe\StripeClient** - Configured Stripe API client instance. ### Request Example ```php $stripe = Cashier::stripe(); $customers = $stripe->customers->all(); // With custom API key $stripe = Cashier::stripe(['api_key' => 'sk_live_...']); ``` ``` -------------------------------- ### Coupon Amount Off Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the fixed amount discount in the smallest currency unit. Returns null if the coupon is not a fixed-amount-off type. ```php public function amountOff(): ?int ``` -------------------------------- ### Get Formatted Invoice Total Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the formatted total amount of the invoice, excluding any starting balance. ```php public function total(): string ``` -------------------------------- ### createSetupIntent Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Create a SetupIntent for saving payment methods. This is useful for securely collecting and saving payment details from customers. ```APIDOC ## createSetupIntent ### Description Create a SetupIntent for saving payment methods. ### Method POST ### Endpoint /paymentMethods/setupIntents ### Parameters #### Request Body - **options** (array) - Required - Stripe SetupIntent options ### Request Example ```json { "options": {} } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the SetupIntent. - **client_secret** (string) - The client secret for the SetupIntent, used by Stripe.js. #### Response Example ```json { "id": "seti_12345", "client_secret": "seti_12345_client_secret_abc" } ``` ``` -------------------------------- ### Retrieve SetupIntent Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieve a specific SetupIntent by its ID. ```php public function findSetupIntent(string $id, array $params = [], array $options = []): Stripe\SetupIntent ``` -------------------------------- ### Install Optional Dompdf Dependency Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Installs the Dompdf library via Composer, which is required for generating and downloading invoice receipts in Laravel Cashier. ```php composer require dompdf/dompdf ``` -------------------------------- ### Create SetupIntent Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Create a SetupIntent for saving payment methods. Pass the intent's client_secret to the frontend for Stripe.js integration. ```php public function createSetupIntent(array $options = []): Stripe\SetupIntent ``` ```php $intent = $user->createSetupIntent(); // Pass intent->client_secret to frontend for Stripe.js ``` -------------------------------- ### Create SetupIntent for Payment Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md Generates a SetupIntent client secret for the frontend to securely collect and save a customer's payment method. This is the first step in saving payment methods. ```php // Create SetupIntent for frontend public function getSetupIntent(Request $request) { $intent = Auth::user()->createSetupIntent(); return response()->json([ 'clientSecret' => $intent->client_secret, ]); } ``` -------------------------------- ### findSetupIntent Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieve a specific SetupIntent by its ID. This allows you to check the status or details of a previously created SetupIntent. ```APIDOC ## findSetupIntent ### Description Retrieve a specific SetupIntent. ### Method GET ### Endpoint /paymentMethods/setupIntents/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the SetupIntent to retrieve. #### Query Parameters - **params** (array) - Optional - Additional parameters for the Stripe API. - **options** (array) - Optional - Options for the request. ### Response #### Success Response (200) - **id** (string) - The ID of the SetupIntent. - **status** (string) - The status of the SetupIntent (e.g., 'succeeded', 'requires_payment_method'). #### Response Example ```json { "id": "seti_12345", "status": "succeeded" } ``` ``` -------------------------------- ### Get All Payment Methods Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Get all saved payment methods for a customer, optionally filtering by type. Iterate through the collection to access details like the last 4 digits of a card. ```php public function paymentMethods(?string $type = null, array $parameters = []): Collection ``` ```php $cards = $user->paymentMethods('card'); foreach ($cards as $card) { echo $card->card->last4; // Last 4 digits } ``` -------------------------------- ### Get Stripe SDK Client Instance Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Obtain a configured Stripe SDK client. Supports passing custom options like API keys. ```php public static function stripe(array $options = []): Stripe\StripeClient ``` ```php $stripe = Cashier::stripe(); $customers = $stripe->customers->all(); // With custom API key $stripe = Cashier::stripe(['api_key' => 'sk_live_...']); ``` -------------------------------- ### Create a Simple Subscription Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md Create a new subscription for a user with an optional trial period. ```php // Route Route::post('/subscribe', function (Request $request) { $user = Auth::user(); $subscription = $user->newSubscription('default', 'price_monthly') ->trialDays(7) ->create($request->payment_method); return redirect('/dashboard')->with('success', 'Welcome to Premium!'); })->middleware('auth'); ``` -------------------------------- ### Get or Set Subscription Item Quantity Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieve or update the quantity for a subscription item. Pass an integer to set the quantity, or call without arguments to get the current quantity. ```php public function quantity(?int $quantity = null): int|null ``` -------------------------------- ### Run Database Migrations for Cashier Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Executes vendor:publish to expose Cashier's migration files and then applies all pending database migrations, including those for updated subscription item tracking. ```shell php artisan vendor:publish --tag="cashier-migrations" php artisan migrate ``` -------------------------------- ### SubscriptionItem->quantity() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Get or set the quantity for the subscription item. ```APIDOC ## SubscriptionItem->quantity(?int $quantity = null) ### Description Get or set the quantity. ### Method `instance` ### Parameters #### Path Parameters - **quantity** (`int`|`null`) - Optional - The new quantity to set ### Returns `int`|`null` (the current or new quantity) ### Example ```php $currentQuantity = $subscriptionItem->quantity(); $subscriptionItem->quantity(5); ``` ``` -------------------------------- ### Get All Invoices Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Fetch a collection of all invoices for the customer using the `invoices` method. You can pass an array of parameters to filter or paginate the results, such as `limit` or `starting_after`. ```PHP $invoices = $user->invoices(['limit' => 10]); ``` -------------------------------- ### Billable Methods Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt Detailed documentation for methods available on billable Eloquent models, organized by trait concerns such as subscription management, customer management, invoicing, and payment methods. Over 80 methods are documented with parameter tables and usage examples. ```APIDOC ## Billable Methods Documentation This section details the methods available on Eloquent models utilizing the Billable trait, categorized by their functional concern. ### Trait Concerns Covered: - **ManagesSubscriptions**: Methods for creating, updating, and canceling subscriptions. - **ManagesCustomer**: Methods for managing customer details in Stripe. - **ManagesInvoices**: Methods for retrieving and formatting invoices. - **ManagesPaymentMethods**: Methods for attaching, detaching, and selecting payment methods. - **PerformsCharges**: Methods for one-off charges and checkout processes. - **ManagesUsageBilling**: Methods for implementing metered billing. - **HandlesTaxes**: Configuration for tax calculations. - **AllowsCoupons**: Methods for applying discounts and coupons. ### Method Details: Each of the 80+ methods includes parameter tables with types and descriptions, along with usage examples. Refer to `billable-methods.md` for complete documentation. ``` -------------------------------- ### Subscription Configuration Options Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Use these options when creating a new subscription. They control aspects like trial periods, billing anchors, and tax rates. ```php [ 'prices' => ['price_123', 'price_456'], // Price IDs 'trial_days' => 14, // Days of trial 'trial_until' => Carbon::now()->addDays(30), // Trial end date 'skip_trial' => false, // Skip trial 'billing_cycle_anchor' => time(), // Anchor date timestamp 'billing_thresholds' => [ // Threshold settings 'amount_gte' => 10000, // Minimum amount before billing 'reset_billing_cycle_anchor' => true ], 'metadata' => ['key' => 'value'], // Custom metadata 'coupon' => 'SAVE20', // Coupon code 'tax_rates' => ['txr_123'], // Tax rate IDs ] ``` -------------------------------- ### Get Associated Customer Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the billable customer object associated with this payment. ```php public function customer(): Billable|null ``` -------------------------------- ### Manually Register Cashier Routes Source: https://github.com/laravel/cashier-stripe/blob/16.x/resources/boost/skills/cashier-stripe-development/references/webhooks.md Provides an example of how to manually register Cashier's webhook and payment routes within `routes/web.php` when `Cashier::ignoreRoutes()` is called. This ensures custom handlers and flows continue to work. ```php use App\Http\Controllers\StripeWebhookController; use Illuminate\Support\Facades\Route; use Laravel\Cashier\Http\Controllers\PaymentController; Route::prefix(config('cashier.path')) ->name('cashier.') ->group(function () { Route::get('payment/{id}', [PaymentController::class, 'show'])->name('payment'); Route::post('webhook', [StripeWebhookController::class, 'handleWebhook'])->name('webhook'); }); ``` -------------------------------- ### Apply and Manage Coupons Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Demonstrates how to apply coupons to new subscriptions or one-off payments, and how to remove or apply coupons to a customer for future subscriptions. ```php // Apply coupon to subscription $subscription = $user->newSubscription('premium', 'price_monthly') ->withCoupon('SUMMER20') ->create(); // Apply coupon to payment $payment = $user->pay(5000) ->applyCoupon('SUMMER20'); // Remove coupon from customer $user->removeCoupon(); // Apply to customer (applies to all new subscriptions) $user->applyCoupon('LOYALTY10'); ``` -------------------------------- ### Get Default Payment Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieve the customer's default payment method. ```php public function defaultPaymentMethod(): PaymentMethod|Stripe\Card|Stripe\BankAccount|null ``` -------------------------------- ### Local Development with Stripe CLI Source: https://github.com/laravel/cashier-stripe/blob/16.x/resources/boost/skills/cashier-stripe-development/references/webhooks.md Demonstrates how to use the Stripe CLI to forward webhook events to a local development server. It includes commands for logging in, listening to events, and triggering test events. ```bash stripe login stripe listen --forward-to your-app.test/stripe/webhook stripe trigger invoice.payment_succeeded ``` -------------------------------- ### CheckoutBuilder->redirect() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Get a redirect response to the Stripe Checkout URL from a CheckoutBuilder instance. ```APIDOC ## CheckoutBuilder->redirect() ### Description Get a redirect response to the Stripe Checkout URL. ### Method `instance` ### Returns `RedirectResponse` ### Example ```php return $user->checkout(['price_123']) ->create() ->redirect(); ``` ``` -------------------------------- ### Get Invoice View Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the invoice view for rendering, optionally with additional data. ```php public function view(array $data = []): View ``` -------------------------------- ### Create Subscription and Send Invoice Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Use the `createAndSendInvoice` method to create a subscription and immediately send an invoice to the customer, suitable for terms like NET-30. ```php public function createAndSendInvoice( array $customerOptions = [], array $subscriptionOptions = [] ): Subscription ``` -------------------------------- ### Retrieve and Manage Subscription Items Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Demonstrates how to retrieve all subscription items for a given subscription, find a specific item by price ID, and update its quantity or swap its price. ```php $subscription = $user->subscription('premium'); // Get all items foreach ($subscription->items as $item) { echo $item->stripe_price; echo $item->quantity; } // Find specific item $item = $subscription->findItemOrFail('price_123'); // Update item $item->update(['quantity' => 3]); // Swap price for this item $item->swap('price_new'); // Update quantity $item->quantity(5); ``` -------------------------------- ### Get Invoice Line Items Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves an array of the invoice's line items. ```php public function items(): InvoiceLineItem[] ``` -------------------------------- ### Customize Stripe Customer Attribute Mapping Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md This example shows how to override methods in your User model to customize the data sent to Stripe for customer attributes like name, email, phone, address, and metadata. It also demonstrates setting a preferred currency. ```php class User extends Model { use Billable; public function stripeName(): ?string { return $this->first_name . ' ' . $this->last_name; } public function stripeEmail(): ?string { return $this->email; } public function stripePhone(): ?string { return $this->phone; } public function stripeAddress(): ?array { if (!$this->address) return null; return [ 'line1' => $this->address, 'city' => $this->city, 'postal_code' => $this->postal_code, 'country' => $this->country, ]; } public function stripeMetadata(): ?array { return [ 'internal_id' => $this->id, 'department' => $this->department, ]; } public function preferredCurrency(): string { return strtolower($this->country) === 'de' ? 'eur' : 'usd'; } } ``` -------------------------------- ### Get Invoice Date Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the invoice date, optionally formatted for a specific timezone. ```php public function date(DateTimeZone|string|int|null $timezone = null): CarbonInterface ``` -------------------------------- ### CustomerBalanceTransaction Description Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the transaction description. Returns null if a description is not available. ```php public function description(): ?string ``` -------------------------------- ### Apply Promotion Codes to Subscriptions Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Shows how to apply a promotion code to a new subscription. Promotion codes offer more flexibility than coupons, including limited redemptions and time-based restrictions. ```php // Apply promotion code to subscription $subscription = $user->newSubscription('premium', 'price_monthly') ->withPromotionCode('SAVE25') ->create(); // Promotion codes are preferred over coupons as they: // - Support limited redemptions // - Support time-based restrictions // - Can be disabled/enabled ``` -------------------------------- ### ->stripeMetadata() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the metadata to be attached to the Stripe customer. This method can be overridden to add custom metadata. ```APIDOC ## ->stripeMetadata() ### Description Get metadata to attach to the Stripe customer. ### Method Signature ```php public function stripeMetadata(): ?array ``` ### Example Usage (Override) ```php public function stripeMetadata(): ?array { return ['internal_id' => $this->id]; } ``` ``` -------------------------------- ### Manage Subscription Trials in PHP Source: https://github.com/laravel/cashier-stripe/blob/16.x/resources/boost/skills/cashier-stripe-development/references/subscriptions.md Allows creating new subscriptions with a trial period and extending existing trials. This is used for offering introductory periods to new users. ```php $user->newSubscription('default', 'price_xxxx') ->trialDays(14) ->create($paymentMethodId); $subscription->extendTrial(now()->addDays(7)); ``` -------------------------------- ### Access Subscription Items Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Demonstrates how to iterate through the new items relationship on a subscription model to retrieve individual plan details and quantities. ```php foreach ($subscription->items as $item) { $item->stripe_plan; $item->quantity; } ``` -------------------------------- ### Get Applied Taxes Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves an array of taxes applied to the invoice, or null if no taxes are applied. ```php public function taxes(): Tax[]|null ``` -------------------------------- ### Create New Subscription Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Initiates the creation of a new subscription for a user. You can specify the subscription type and price ID, or add prices later using fluent methods. The `trialDays` method can be used to set up a trial period. ```php public function newSubscription(string $type, string|array $prices = []): SubscriptionBuilder ``` ```php $user->newSubscription('premium', 'price_monthly') ->trialDays(14) ->create(); ``` ```php $user->newSubscription('professional') ->price('price_addon_1') ->price('price_addon_2', 2) ->create(); ``` -------------------------------- ### Configuration Options Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/DOCUMENTATION_SUMMARY.txt Reference for all configuration options available in the `cashier.php` configuration file, including environment variables, Stripe API settings, and webhook configuration. ```APIDOC ## Configuration Reference This section details the configuration options for Laravel Cashier Stripe. ### Configuration File (`cashier.php`): - **9+ Configuration Keys**: All options are documented. - **Environment Variables**: Reference table for relevant environment variables. - **Stripe API Configuration**: Settings for connecting to Stripe. - **Webhook Configuration**: Guide for setting up webhook endpoints. - **Testing Configuration**: Information on using test cards. Refer to `configuration.md` for a complete breakdown of all settings and their usage. ``` -------------------------------- ### Get Formatted Invoice Subtotal Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the formatted subtotal of the invoice before taxes and discounts are applied. ```php public function subtotal(): string ``` -------------------------------- ### Tax Percentage Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the tax percentage. This method returns the tax rate as a number. ```php public function percentage(): int|float ``` -------------------------------- ### Create and Report Metered Usage Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md Set up a metered subscription and report usage for billing. ```php // Create metered subscription $subscription = $user->newSubscription('api', 'price_metered_requests') ->meteredPrice('price_metered_requests') ->create(); // Track usage (in your API) public function handleRequest() { $user = Auth::user(); // Do work performWork(); // Report 1 unit of usage $user->reportUsage(1); // Or report in batch $user->reportUsage(100, null, null, 'set'); } // Billing happens automatically at period end // Usage resets monthly ``` -------------------------------- ### Coupon ID Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the coupon ID. This method returns the unique identifier for the coupon. ```php public function id(): string ``` -------------------------------- ### Create Subscription with Trial Period Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Create subscriptions with a trial period, either for a specified number of days from creation or until a specific date. You can also skip the trial entirely and check the trial status. ```php // Create with trial $subscription = $user->newSubscription('premium', 'price_monthly') ->trialDays(14) // 14 days from now ->create(); // Or specific date $subscription = $user->newSubscription('premium', 'price_monthly') ->trialUntil(now()->addMonths(1)) ->create(); // Skip trial $subscription = $user->newSubscription('premium', 'price_monthly') ->skipTrial() ->create(); // Check trial status if ($user->onTrial('premium')) { echo "Trial ends: " . $user->trialEndsAt('premium'); } if ($user->hasExpiredTrial('premium')) { echo "Trial has ended"; } ``` -------------------------------- ### ->createAsStripeCustomer() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Creates a new customer in Stripe for the model. Accepts options for customer details and API request options. Throws an exception if the customer already exists. ```APIDOC ## ->createAsStripeCustomer() ### Description Create a new Stripe customer for this model. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (array) - Optional - Stripe customer options (name, email, etc.). - **requestOptions** (array) - Optional - Stripe API request options. ### Method Signature ```php public function createAsStripeCustomer(array $options = [], array $requestOptions = []): Stripe\Customer ``` ### Returns Created Stripe Customer object. ### Throws - `CustomerAlreadyCreated` if customer already exists. ### Request Example ```php $customer = $user->createAsStripeCustomer([ 'email' => 'user@example.com', 'metadata' => ['internal_id' => $user->id], ]); ``` ``` -------------------------------- ### ->stripePreferredLocales() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the preferred locales for customer communications. This method can be overridden to specify custom locale preferences. ```APIDOC ## ->stripePreferredLocales() ### Description Get preferred locales for customer communications. ### Method Signature ```php public function stripePreferredLocales(): ?array ``` ``` -------------------------------- ### Migrate Database for Multiplan Subscriptions Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Updates the subscriptions table to allow null values for plan and quantity, and creates a new subscription_items table to track multiple plans per subscription. ```php Schema::table('subscriptions', function (Blueprint $table) { $table->string('stripe_plan')->nullable()->change(); $table->integer('quantity')->nullable()->change(); }); Schema::create('subscription_items', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('subscription_id'); $table->string('stripe_id')->index(); $table->string('stripe_plan'); $table->integer('quantity'); $table->timestamps(); $table->unique(['subscription_id', 'stripe_plan']); }); ``` -------------------------------- ### ->stripeAddress() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the address array for the Stripe customer. This method can be overridden to provide a custom address structure. ```APIDOC ## ->stripeAddress() ### Description Get the address array for Stripe customer. ### Method Signature ```php public function stripeAddress(): ?array ``` ### Example Usage (Override) ```php public function stripeAddress(): ?array { return [ 'line1' => '123 Main St', 'city' => 'Springfield', 'postal_code' => '12345', 'country' => 'US', ]; } ``` ``` -------------------------------- ### ->stripeEmail() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the email address for the Stripe customer. This method can be overridden to customize the email used for Stripe. ```APIDOC ## ->stripeEmail() ### Description Get the email for Stripe customer. ### Method Signature ```php public function stripeEmail(): ?string ``` ### Usage Override to customize. ``` -------------------------------- ### Checkout::customer() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Create a checkout session for an authenticated customer. Requires the billable model and an optional parent instance. ```APIDOC ## Checkout::customer($owner, ?object $parentInstance = null) ### Description Create a checkout session for an authenticated customer. ### Method `static` ### Parameters #### Path Parameters - **owner** (`Model`) - Required - Billable model (customer) - **parentInstance** (`object`|`null`) - Optional - Parent builder (subscription, etc.) ### Returns `CheckoutBuilder` instance. ### Example ```php $user = User::find(1); $checkoutBuilder = Checkout::customer($user); ``` ``` -------------------------------- ### Create a Subscription with Trial Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/00_START_HERE.md Use this snippet to create a new subscription for a user, including a trial period. Ensure the user model is Billable and the Stripe price ID is valid. ```php $subscription = $user->newSubscription('premium', 'price_monthly') ->trialDays(14) ->create('pm_card_visa'); ``` -------------------------------- ### Get Formatted Real Invoice Total Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the formatted total amount that has been paid or is due to be paid. ```php public function realTotal(): string ``` -------------------------------- ### Swap Subscription Plans in PHP Source: https://github.com/laravel/cashier-stripe/blob/16.x/resources/boost/skills/cashier-stripe-development/references/subscriptions.md Enables users to swap to a new subscription plan. Options include prorating, skipping the trial, and immediately invoicing the change. ```php $user->subscription('default')->swap('price_new'); $user->subscription('default')->noProrate()->swap('price_new'); $user->subscription('default')->swapAndInvoice('price_new'); $user->subscription('default')->skipTrial()->swap('price_new'); ``` -------------------------------- ### Get PaymentIntent Client Secret Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the PaymentIntent client secret, which is necessary for frontend confirmation of the payment. ```php public function clientSecret(): string ``` -------------------------------- ### Manage Multiple Products on a Subscription in PHP Source: https://github.com/laravel/cashier-stripe/blob/16.x/resources/boost/skills/cashier-stripe-development/references/subscriptions.md Facilitates managing subscriptions that include multiple products or prices. Users can add, remove, or swap products within a single subscription. ```php $user->newSubscription('default', ['price_monthly', 'price_chat']) ->quantity(5, 'price_chat') ->create($paymentMethod); $user->subscription('default')->addPrice('price_chat'); $user->subscription('default')->removePrice('price_chat'); $user->subscription('default')->swap(['price_pro', 'price_chat']); ``` -------------------------------- ### PromotionCode Code Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the human-readable promotion code string (e.g., "SAVE20"). ```php public function code(): string ``` -------------------------------- ### Discount Coupon Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the underlying coupon object associated with this discount. Returns a Coupon instance. ```php public function coupon(): Coupon ``` -------------------------------- ### Checkout::guest() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Create a checkout session for a guest (non-authenticated) customer. Returns a CheckoutBuilder instance. ```APIDOC ## Checkout::guest() ### Description Create a checkout session for a guest (non-authenticated) customer. ### Method `static` ### Returns `CheckoutBuilder` instance. ### Example ```php $checkoutBuilder = Checkout::guest(); ``` ``` -------------------------------- ### checkout() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Create a Checkout Session for existing prices. This is used to initiate the Stripe Checkout flow for predefined products or services. ```APIDOC ## checkout() ### Description Create a Checkout Session for existing prices. ### Method `checkout(string|array $items, array $sessionOptions = [], array $customerOptions = [])` ### Parameters #### Path Parameters - **$items** (string|array) - Required - Price ID(s) or line item objects - **$sessionOptions** (array) - Optional - Stripe Checkout Session options - **$customerOptions** (array) - Optional - Customer creation options ### Response #### Success Response - **Checkout** object with session URL. ### Request Example ```php $checkout = $user->checkout(['price_123', 'price_456']) ->redirect(); ``` ``` -------------------------------- ### Unit Test Subscription Creation Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md Write unit tests to verify the creation of subscriptions for users, ensuring that the Stripe ID is generated and the user's subscription status is correctly updated. ```php use Laravel\Cashier\Subscription; use Illuminate\Foundation\Testing\RefreshDatabase; class SubscriptionTest extends TestCase { use RefreshDatabase; public function test_user_can_create_subscription() { $user = User::factory()->create(); // Create subscription $subscription = $user->newSubscription('default', 'price_test_monthly') ->skipTrial() ->create(); $this->assertNotNull($subscription->stripe_id); $this->assertTrue($user->subscribed('default')); } public function test_subscription_status_queries() { $user = User::factory()->create(); $subscription = Subscription::factory() ->for($user, 'billable') ->create(['stripe_status' => 'active']); $this->assertTrue($user->subscribed('default')); $this->assertTrue($subscription->active()); $this->assertFalse($subscription->onTrial()); } } ``` -------------------------------- ### ->stripePhone() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the phone number for the Stripe customer. This method can be overridden to customize the phone number used for Stripe. ```APIDOC ## ->stripePhone() ### Description Get the phone number for Stripe customer. ### Method Signature ```php public function stripePhone(): ?string ``` ### Usage Override to customize. ``` -------------------------------- ### Create Subscription Without Payment Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Use the `add` method to create a subscription without explicitly providing a payment method, which will use the customer's default payment method. ```php public function add(array $customerOptions = [], array $subscriptionOptions = []): Subscription ``` -------------------------------- ### ->stripeName() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the name to be used for Stripe customer creation. This method can be overridden to provide custom name logic. ```APIDOC ## ->stripeName() ### Description Get the name to use for Stripe customer creation. ### Method Signature ```php public function stripeName(): ?string ``` ### Example Usage (Override) ```php public function stripeName(): ?string { return $this->first_name . ' ' . $this->last_name; } ``` ``` -------------------------------- ### Get Preferred Locales for Stripe Customer Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves the preferred locales for customer communications. This method can be overridden for customization. ```php public function stripePreferredLocales(): ?array ``` -------------------------------- ### Get All Subscriptions Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Returns all subscriptions associated with the customer as an Eloquent relationship. This allows iterating through all of a user's subscriptions. ```php public function subscriptions(): HasMany ``` ```php foreach ($user->subscriptions as $subscription) { echo $subscription->type; } ``` -------------------------------- ### Get Stripe PaymentMethod Object Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieve the underlying Stripe PaymentMethod object associated with this Cashier PaymentMethod instance. ```php public function asStripePaymentMethod(): Stripe\PaymentMethod ``` -------------------------------- ### Configure Subscription Payment Behavior Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Demonstrates how to use allowPaymentFailures() to maintain legacy 'allow_incomplete' behavior when creating or updating subscriptions in Cashier 14. ```php $request->user()->newSubscription('default', 'price_monthly')->allowPaymentFailures()->create($request->paymentMethodId); $user->subscription('default')->allowPaymentFailures()->swap('price_yearly'); ``` -------------------------------- ### Implement Custom Invoice Renderer Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/configuration.md Create a custom invoice renderer by implementing the InvoiceRenderer interface. This allows for custom PDF generation logic. ```php // In your billing controller public function downloadInvoice($invoiceId) { $invoice = $user->findInvoice($invoiceId); return $invoice->download(new CustomInvoiceRenderer()); } ``` ```php use Laravel\Cashier\Contracts\InvoiceRenderer; class CustomInvoiceRenderer implements InvoiceRenderer { public function render(Invoice $invoice, array $data = [], ?string $disk = null): string { // Return PDF content } } ``` -------------------------------- ### Get Raw Real Invoice Total Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the raw real total amount in the smallest currency unit. ```php public function rawRealTotal(): int ``` -------------------------------- ### Create Complex Subscription with Multiple Prices Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Create a subscription that includes multiple prices, such as a base price and add-ons. Properties like stripe_price and quantity will be null, with individual item details accessible via the 'items' property. ```php // Complex subscription with multiple prices $subscription = $user->newSubscription('bundle') ->price('price_base') ->price('price_addon_1', 2) ->price('price_addon_2') ->create(); // Properties echo $subscription->stripe_price; // null (multiple prices) echo $subscription->quantity; // null (per-item quantities) echo $subscription->hasMultiplePrices(); // true // Access items foreach ($subscription->items as $item) { echo $item->stripe_price; // Individual price ID echo $item->quantity; // Individual quantity } ``` -------------------------------- ### Get Raw Invoice Total Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Retrieves the raw invoice total in the smallest currency unit (e.g., cents). ```php public function rawTotal(): int ``` -------------------------------- ### Publish Cashier Configuration Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/configuration.md Publish Cashier's configuration file to customize settings. This creates the `config/cashier.php` file. ```bash php artisan vendor:publish --provider="Laravel\Cashier\CashierServiceProvider" ``` -------------------------------- ### Tax Display Name Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the display name for the tax. Returns null if a display name is not available. ```php public function displayName(): ?string ``` -------------------------------- ### Create Simple Subscription Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Create a new subscription for a user with a single price. Access the assigned price ID and quantity. ```php // Simple subscription with one price $subscription = $user->newSubscription('premium', 'price_monthly') ->create(); // Access price echo $subscription->stripe_price; // 'price_monthly' echo $subscription->quantity; // e.g., 2 ``` -------------------------------- ### Get Stripe Customer Metadata Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves metadata to attach to the Stripe customer. This method can be overridden to add custom metadata. ```php public function stripeMetadata(): ?array ``` ```php public function stripeMetadata(): ?array { return ['internal_id' => $this->id]; } ``` -------------------------------- ### Create Metered Subscription and Report Usage Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md Set up subscriptions for metered billing and report usage. Usage can be reported as increments or absolute values, and can be associated with a specific subscription item or timestamp. ```php // Create subscription with metered price $subscription = $user->newSubscription('api', 'price_metered') ->meteredPrice('price_metered') // No quantity required ->create(); // Report usage $user->reportUsage(100); // 100 units used // Report for specific item in multi-price subscription $item = $subscription->findItemOrFail('price_metered'); $user->reportUsage(50, $item->stripe_id); // 50 units for that item // With timestamp $user->reportUsage(25, null, now()->subDay()); // Increment vs set $user->reportUsage(10, null, null, 'increment'); // Add to count $user->reportUsage(100, null, null, 'set'); // Set absolute value ``` -------------------------------- ### Add Price and Invoice Immediately Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Use `invoicePrice` to add a Stripe price and immediately invoice the customer. This method takes the price, quantity, and optional tab and invoice options. ```PHP $invoice = $user->invoicePrice('price_123', 2); ``` -------------------------------- ### Get Stripe Customer Email Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves the email address for the Stripe customer. This method can be overridden to customize the email used. ```php public function stripeEmail(): ?string ``` -------------------------------- ### InvoiceLineItem Amount Method Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/types-and-exceptions.md Get the formatted amount for the line item. This method returns the amount as a string, suitable for display. ```php public function amount(): string ``` -------------------------------- ### Set Trial Period in Days Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/cashier-core-api.md Use the `trialDays` method to define a trial period for the subscription in a specified number of days. ```php public function trialDays(int $trialDays): $this ``` -------------------------------- ### Configure Custom Billable Model in AppServiceProvider Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Demonstrates how to register a custom billable model using the Cashier::useCustomerModel method within the boot method of the AppServiceProvider. ```php use App\Models\Cashier\User; use Laravel\Cashier\Cashier; /** * Bootstrap any application services. * * @return void */ public function boot() { Cashier::useCustomerModel(User::class); } ``` -------------------------------- ### ->preferredCurrency() Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Gets the preferred currency for charges and subscriptions. This method can be overridden to customize the default currency. Defaults to the value from `config('cashier.currency')`. ```APIDOC ## ->preferredCurrency() ### Description Get the currency for charges/subscriptions. ### Method Signature ```php public function preferredCurrency(): string ``` ### Usage Override to customize. Default: `config('cashier.currency')`. ``` -------------------------------- ### Create Stripe Customer on First Use Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/advanced-features.md This snippet shows how to create a Stripe customer associated with a user model when they first interact with a billing feature. It includes options for adding email and metadata. ```php // Create on first use $customer = $user->createAsStripeCustomer([ 'email' => 'user@example.com', 'metadata' => ['internal_id' => $user->id], ]); ``` -------------------------------- ### Get Preferred Currency Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves the currency to be used for charges and subscriptions. This method can be overridden for customization. Defaults to the value from `config('cashier.currency')`. ```php public function preferredCurrency(): string ``` -------------------------------- ### Get Stripe Customer Address Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves the address array for the Stripe customer. This method can be overridden to return a custom address structure. ```php public function stripeAddress(): ?array ``` ```php public function stripeAddress(): ?array { return [ 'line1' => '123 Main St', 'city' => 'Springfield', 'postal_code' => '12345', 'country' => 'US', ]; } ``` -------------------------------- ### Apply Trial Middleware to Routes Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md Applies the 'trial' middleware to a group of routes, ensuring that only users on a trial or subscribed can access them. This is used to protect premium features. ```php // Use in routes Route::middleware('trial')->group(function () { // Premium features only available on trial or paid }); ``` -------------------------------- ### Trial Middleware for Access Control Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/integration-guide.md A middleware that checks if a user is on a trial or subscribed, redirecting them to an upgrade page if they are not. Use this to protect premium features. ```php // Check in middleware class TrialMiddleware { public function handle($request, $next) { if ($request->user() && !$request->user()->onGenericTrial()) { if (!$request->user()->subscribed()) { return redirect('/upgrade'); } } return $next($request); } } ``` -------------------------------- ### Get Stripe Customer Phone Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves the phone number for the Stripe customer. This method can be overridden to customize the phone number used. ```php public function stripePhone(): ?string ``` -------------------------------- ### Get Stripe Customer ID Source: https://github.com/laravel/cashier-stripe/blob/16.x/_autodocs/billable-methods.md Retrieves the customer's Stripe ID. Returns null if the customer has not yet been created in Stripe. ```php public function stripeId(): ?string ``` -------------------------------- ### Configure Checkout Payment Methods Source: https://github.com/laravel/cashier-stripe/blob/16.x/UPGRADE.md Demonstrates how to explicitly set payment method types during a checkout session to restore previous default behavior. ```php $request->user()->checkout('price_tshirt', [ 'payment_method_types' => ['card'], ]); ```