Cartalyst LLC.
Stripe-laravel-billing by Cartalyst
0
5
0
2
0

This package requires a valid subscription. Subscribe for access.

Introduction

A comprehensive billing and API package for Stripe.

The package requires PHP 5.4+ and follows the FIG standard PSR-4 to ensure a high level of interoperability between shared PHP code and is fully unit-tested.

Have a read through the Installation Guide and on how to Integrate it with Laravel 4.

Using the API
$customers = Stripe::customers()->all();

foreach ($customers['data'] as $customer)
{
    var_dump($customer['email']);
}
Using a Billable Entity
$user = User::find(1);

$subscriptions = $user->subscriptions;

foreach ($subscriptions as $subscription)
{
    if ($subscription->expired())
    {
        echo 'Subscription has expired!';
    }
}

Installation

Cartalyst packages utilize Composer, for more information on how to install Composer please read the Composer Documentation.

Preparation

Open your composer.json file and add the following to the require array:

"cartalyst/stripe": "0.1.*"

Add the following lines after the require array on your composer.json file:

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.cartalyst.com"
    }
]

Note: Make sure that after the required changes your composer.json file is valid by running composer validate.

Install the dependencies

Run Composer to install or update the new requirement.

php composer install

or

php composer update

Now you are able to require the vendor/autoload.php file to autoload the package.

Integration

Cartalyst packages are framework agnostic and as such can be integrated easily natively or with your favorite framework.

Laravel 4

The Stripe package has optional support for Laravel 4 and it comes bundled with a Service Provider and a Facade for easy integration.

After installing the package, open your Laravel config file located at app/config/app.php and add the following lines.

In the $providers array add the following service provider for this package.

'Cartalyst\Stripe\Laravel\StripeServiceProvider',

In the $aliases array add the following facade for this package.

'Stripe' => 'Cartalyst\Stripe\Laravel\Facades\Stripe',

Set the Stripe API Key

Now you need to setup the Stripe API key, to do this open or create the app/config/services.php file, and add or update the 'stripe' array:

<?php

return [

    'stripe' => [
        'secret' => 'your-stripe-key-here',
    ],

];

Billing

The Stripe package comes with billing functionality that you can attach to a single entity or multiple entities.

To use this feature please follow the next steps:

Model setup

Add the Cartalyst\Stripe\Billing\BillableTrait to your Eloquent model and make sure that the model implements the Cartalyst\Stripe\Billing\BillableInterface:

use Cartalyst\Stripe\Billing\BillableTrait;
use Cartalyst\Stripe\Billing\BillableInterface;

class User extends Eloquent implements BillableInterface {

    use BillableTrait;

}

Open the app/config/services.php file and add a new 'model' entry on the 'stripe' array that will hold your entity model class name:

return [

    'stripe' => [
        'secret' => 'your-stripe-key-here',
        'model'  => 'User',
    ],

];

If you want to attach multiple models, just define an array instead of a string:

return [

    'stripe' => [
        'secret' => 'your-stripe-key-here',
        'model'  => [
            'User',
            'OtherModel',
        ]
    ],

];

As a reminder, all models should implement the Cartalyst\Stripe\Billing\BillableInterface otherwise you'll receive an InvalidArgumentException exception.

The same applies to when you define a model that doesn't exist, in that situation you'll receive an Exception warning that the model wasn't found or doesn't exist.

Note: If a model is under a namespace, please provide the full namespace, ex: 'Acme\Models\User'.

Migrations

Now you need to migrate your database, but before doing that, you'll need to generate a migration that suits your billable table and to do this you just need to run the following command:

php artisan stripe:table users

Note: Replace users with the billable entity table name.

Now that the migration file is created you just need to run php artisan migrate to create the tables on your database.

Note: If you have multiple models setup on the app/config/services.php file, please repeat this step for each model.

API

The Stripe package comes bundled with an API connector to the Stripe REST API.

Charges

To charge a credit or a debit card, you create a new charge object. You can retrieve and refund individual charges as well as list all charges. Charges are identified by a unique ID.

Create a new charge

To charge a credit card, you need to create a new charge object. If your API key is in test mode, the supplied card won't actually be charged, though everything else will occur as if in live mode. (Stripe will assume that the charge would have completed successfully).

Arguments
Key Required Type Default Description
amount true number null A positive amount representing how much to charge the card.
currency true string null 3-letter ISO code for currency.
customer false string null The customer unique identifier.
card false string or array null The card unique identifier.
description false string null An arbitrary string which you can attach to a charge object.
metadata false array [] A set of key/value pairs that you can attach to a charge object.
capture false bool null Whether or not to immediately capture the charge.
statement_description false string null An arbitrary string to be displayed alongside your company name on your customer's credit card statement.
receipt_email false string null The email address to send this charge’s receipt to.
application_fee false int null An application fee to add on to this charge.
Example
$charge = Stripe::charges()->create([
    'customer' => 'cus_4EBumIjyaKooft',
    'currency' => 'USD',
    'amount'   => 50.49,
]);

echo $charge['id'];

Update a charge

Updates the specified charge by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

Arguments
Key Required Type Default Description
id true string null The charge unique identifier.
description false string null An arbitrary string which you can attach to a charge object.
metadata false array [] A set of key/value pairs that you can attach to a charge object.
Example
$charge = Stripe::charges()->update([
    'id'          => 'ch_4ECWMVQp5SJKEx',
    'description' => 'Payment to foo bar',
]);

Capture a charge

Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step payment flow, where first you created a charge with the capture option set to false.

Uncaptured payments expire exactly seven days after they are created. If they are not captured by that point in time, they will be marked as refunded and will no longer be capturable.

Arguments
Key Required Type Default Description
id true string null The charge unique identifier.
amount false number null A positive amount for the transaction.
application_fee false bool null An application fee to add on to this charge. Can only be used with Stripe Connect
metadata false array [] A set of key/value pairs that you can attach to a charge object.
Example
$charge = Stripe::charges()->capture([
    'id' => 'ch_4ECWMVQp5SJKEx',
]);

Retrieve all charges

Returns a list of charges you've previously created. The charges are returned in sorted order, with the most recent charges appearing first.

Arguments
Key Required Type Default Description
created false string null A filter on the list based on the object created field.
customer false string null The customer unique identifier.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
Example
$charges = Stripe::charges()->all();

foreach ($charges['data'] as $charge)
{
    var_dump($charge['id']);
}

Retrieve an existing charge

Retrieves the details of a charge that has been previously created. Supply the unique charge ID that was returned from a previous request, and Stripe will return the corresponding charge information. The same information is returned when creating or refunding the charge.

Arguments
Key Required Type Default Description
id true string null The charge unique identifier.
Example
$charge = Stripe::charges()->find([
    'id' => 'ch_4ECWMVQp5SJKEx',
]);
Using the alias
$charge = Stripe::charge('ch_4ECWMVQp5SJKEx');

Refunds

Refund objects allow you to refund a charge that has previously been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged. The fees you were originally charged are also refunded.

Refund a charge

Creating a new refund will refund a charge that has previously been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged. The fees you were originally charged are also refunded.

Arguments
Key Required Type Default Description
charge true string null The charge unique identifier.
amount false number null A positive amount for the transaction.
refund_application_fee false int null Boolean indicating whether the application fee should be refunded when refunding this charge.
metadata false array [] A set of key/value pairs that you can attach to a refund object.
$charge = Stripe::refunds()->create([
    'charge' => 'ch_4ECWMVQp5SJKEx',
]);

Retrieve all refunds of a charge

You can see a list of the refunds belonging to a specific charge.

Arguments
Key Required Type Default Description
charge true string null The charge unique identifier.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
$refunds = Stripe::refunds()->all([
    'charge' => 'ch_4ECWMVQp5SJKEx',
]);

foreach ($refunds['data'] as $refund)
{
    var_dump($refund['id']);
}

Retrieve an existing refund

By default, you can see the 10 most recent refunds stored on a charge directly on the charge object, but you can also retrieve details about a specific refund stored on the charge.

Arguments
Key Required Type Default Description
charge true string null The charge unique identifier.
id true string null The refund unique identifier.
$refund = Stripe::refunds()->find([
    'charge' => 'ch_4ECWMVQp5SJKEx',
    'id'     => 'txn_4IgdBGArAOeiQw',
]);
Using the alias
$charge = Stripe::refund('ch_4ECWMVQp5SJKEx', 'txn_4IgdBGArAOeiQw');

Update an existing refund

Updates the specified refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

Arguments
Key Required Type Default Description
charge true string null The charge unique identifier.
id true string null The refund unique identifier.
metadata false array [] A set of key/value pairs that you can attach to a refund object.
$refund = Stripe::refunds()->update([
    'charge'   => 'ch_4ECWMVQp5SJKEx',
    'id'       => 'txn_4IgdBGArAOeiQw',
    'metadata' => [
        'reason'      => 'Customer requested for the refund.',
        'refunded_by' => 'John Doe',
    ],
]);

Customers

Customer objects allow you to perform recurring charges and track multiple charges that are associated with the same customer. The API allows you to create, delete, and update your customers. You can retrieve individual customers as well as a list of all your customers.

Create a new customer

Creates a new customer object.

Arguments
Key Required Type Default Description
account_balance false number null A positive amount that is the starting account balance for your customer.
card false string or array null Unique card identifier (can either be an ID or a hash).
coupon false string null Coupon identifier that applies a discount on all recurring charges.
description false string null An arbitrary string that you can attach to a customer object.
email false string null Customer’s email address.
metadata false array null A set of key/value pairs that you can attach to a customer object.
quantity false integer null Quantity you'd like to apply to the subscription you're creating.
plan false string null Plan for the customer.
trial_end false integer null UTC integer timestamp representing the end of the trial period the customer will get before being charged for the first time.
$customer = Stripe::customers()->create([
    'email' => 'john.doe@example.com',
]);

echo $customer['id'];

Delete a customer

Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer.

Arguments
Key Required Type Default Description
id true string null The customer unique identifier.
$customer = Stripe::customers()->destroy([
    'id' => 'cus_4EBumIjyaKooft',
]);

Update a customer

Updates the specified customer by setting the values of the parameters passed.

Arguments
Key Required Type Default Description
id true string null The customer unique identifier.
account_balance false number null A positive amount that is the starting account balance for your customer.
card false string or array null Unique card identifier (can either be an ID or a hash).
coupon false string null Coupon identifier that applies a discount on all recurring charges.
default_card false string null The card unique identifier.
description false string null An arbitrary string that you can attach to a customer object.
email false string null Customer’s email address.
metadata false array null A set of key/value pairs that you can attach to a customer object.
$customer = Stripe::customers()->update([
    'id'    => 'cus_4EBumIjyaKooft',
    'email' => 'jonathan@doe.com',
]);

echo $customer['email'];

Retrieve all customers

Returns a list of your customers. The customers are returned sorted by creation date, with the most recently created customers appearing first.

Arguments
Key Required Type Default Description
created false string or array null A filter based on the "created" field. Can be an exact UTC timestamp, or an hash.
ending_before false string null A cursor to be used in pagination.
limit false integer 10 A limit on the number of objects to be returned. Limit can range between 1 and 100 items.
starting_after false string null A cursor to be used in pagination.
$customers = Stripe::customers()->all();

foreach ($customers['data'] as $customer)
{
    var_dump($customer['id']);
}

Retrieve a customer

Retrieves the details of an existing customer.

Arguments
Key Required Type Default Description
id true string null The customer unique identifier.
$customer = Stripe::customers()->find([
    'id' => 'cus_4EBumIjyaKooft',
]);

echo $customer['email'];
Using the alias
$charge = Stripe::customer('cus_4EBumIjyaKooft');

Delete a customer discount

Removes the currently applied discount on a customer.

Arguments
Key Required Type Default Description
id true string null The customer unique identifier.
$customer = Stripe::customers()->deleteDiscount([
    'id' => 'cus_4EBumIjyaKooft',
])->toArray();

Cards

You can store multiple cards on a customer in order to charge the customer later. You can also store multiple debit cards on a recipient in order to transfer to those cards later.

Create a new card

When you create a new credit card, you must specify a customer to create it on.

Creating a new credit card will not change the card owner's existing default credit card. If the card's owner has no default credit card, the added credit card will become the default.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
card true string or array null The card unique identifier.
Through the Stripe.js Token (recommended)
$cardToken = Input::get('stripeToken');

$card = Stripe::cards()->create([
    'customer' => 'cus_4EBumIjyaKooft',
    'card'     => $cardToken,
]);
Manually
$card = Stripe::cards()->create([
    'customer' => 'cus_4EBumIjyaKooft',
    'card'     => [
        'number'    => '4242424242424242',
        'exp_month' => 6,
        'exp_year'  => 2015,
        'cvc'       => '314',
    ],
]);

Update a card

If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the full card details.

When you update a card, Stripe will automatically validate the card.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
id true string null The card unique identifier.
address_city false string null The card holder city.
address_line1 false string null The card holder address line 1.
address_line2 false string null The card holder address line 2.
address_state false string null The card holder state.
address_zip false string null The card holder address zip code.
exp_month false string null The card expiration month.
exp_year false string null The card expiration year.
name false string null The card holder name.
Example
$card = Stripe::cards()->update([
    'customer'      => 'cus_4EBumIjyaKooft',
    'id'            => 'card_4EBj4AslJlNXPs',
    'name'          => 'John Doe',
    'address_line1' => 'Example Street 1',
]);

Delete a card

You can delete cards from a customer.

If you delete a card that is currently the default card on a customer, the most recently added card will be used as the new default.

If you delete the last remaining card on a customer, the default_card attribute on the card's owner will become null.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
id true string null The card unique identifier.
Example
$card = Stripe::cards()->destroy([
    'customer' => 'cus_4EBumIjyaKooft',
    'id'       => 'card_4EBi3uAIBFnKy4',
]);

Retrieve all cards

You can see a list of the cards belonging to a customer.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
id true string null The customer unique identifier.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
Example
$cards = Stripe::cards()->all([
    'customer' => 'cus_4EBumIjyaKooft',
]);

foreach ($cards['data'] as $card)
{
    var_dump($card['id']);
}

Retrieve a Card

Retrieves the details of an existing credit card.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
id true string null The card unique identifier.
Example
$card = Stripe::cards()->find([
    'customer' => 'cus_4EBumIjyaKooft',
    'id'       => 'card_4DmaB3muM8SNdZ',
]);

echo $card['last4'];
Using the alias
$charge = Stripe::card('cus_4EBumIjyaKooft', 'card_4DmaB3muM8SNdZ');

Plans

A subscription plan contains the pricing information for different products and feature levels on your site. For example, you might have a €10/month plan for basic features and a different €20/month plan for premium features.

Create a new plan

You can create plans easily via the plan management page of the Stripe dashboard. Plan creation is also accessible via the API if you need to create plans on the fly.

Arguments
Key Required Type Default Description
id true string null The plan unique identifier.
amount true number null A positive amount for the transaction.
currency true string null 3-letter ISO code for currency.
interval true string null Specifies billing frequency. Either week, month or year.
interval_count false int 1 The number of intervals between each subscription billing.
name true string null The name of the plan.
trial_period_days false int null Specifies a trial period in (an integer number of) days.
metadata false array [] A set of key/value pairs that you can attach to a transfer object
statement_description false string null An arbitrary string which will be displayed on the customer's bank statement.
$plan = Stripe::plans()->create([
    'id'                    => 'monthly',
    'name'                  => 'Monthly (30$)',
    'amount'                => 30.00,
    'currency'              => 'USD',
    'interval'              => 'month',
    'statement_description' => 'Monthly Subscription to Foo Bar Inc.',
]);

echo $plan['id'];

Delete a plan

You can delete plans via the plan management page of the Stripe dashboard. However, deleting a plan does not affect any current subscribers to the plan; it merely means that new subscribers can't be added to that plan. You can also delete plans via the API.

Arguments
Key Required Type Default Description
id true string null The plan unique identifier.
$plan = Stripe::plans()->destroy([
    'id' => 'monthly',
]);

Update a plan

Updates the name of a plan. Other plan details (price, interval, etc.) are, by design, not editable.

Arguments
Key Required Type Default Description
id true string null The plan unique identifier.
name false string null The name of the plan.
metadata false array [] A set of key/value pairs that you can attach to a transfer object
statement_description false string null An arbitrary string which will be displayed on the customer's bank statement.
$plan = Stripe::plans()->update([
    'id'   => 'monthly',
    'name' => 'Monthly Subscription',
]);

echo $plan['name'];

Retrieve all the existing plans

Returns a list of your plans.

Arguments
Key Required Type Default Description
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
$plans = Stripe::plans()->all();

foreach ($plans['data'] as $plan)
{
    var_dump($plan['id']);
}

Retrieve an existing plan

Retrieves the plan with the given ID.

Arguments
Key Required Type Default Description
id true string null The plan unique identifier.
$plan = Stripe::plans()->find([
    'id' => 'monthly',
]);

echo $plan['name'];
Using the alias
$charge = Stripe::plan('monthly');

Coupons

A coupon contains information about a percent-off discount you might want to apply to a customer. Coupons only apply to invoices created for recurring subscriptions and invoice items; they do not apply to one-off charges.

Create a new coupon

You can create coupons easily via the coupon management page of the Stripe dashboard. Coupon creation is also accessible via the API if you need to create coupons on the fly.

A coupon has either a percent_off or an amount_off and currency. If you set an amount_off, that amount will be subtracted from any invoice's subtotal. For example, an invoice with a subtotal of $10 will have a final total of $0 if a coupon with an amount_off of 2000 is applied to it and an invoice with a subtotal of $30 will have a final total of $10 if a coupon with an amount_off of 2000 is applied to it.

Arguments
Key Required Type Default Description
id false string null The coupon unique identifier, if not provided a random string will be generated.
duration true string null Specifies how long the discount will be in effect. Can be forever, once, or repeating.
amount_off false number null A positive amount representing the amount to subtract from an invoice total (required if percent_off is not passed).
currency true string null 3-letter ISO code for currency.
duration_in_months false int null If duration is repeating, a positive integer that specifies the number of months the discount will be in effect.
max_redemptions false int null A positive integer specifying the number of times the coupon can be redeemed before it’s no longer valid.
metadata false array [] A set of key/value pairs that you can attach to a coupon object.
percent_off false int null A positive integer between 1 and 100 that represents the discount the coupon will apply (required if amount_off is not passed).
redeem_by false int null Unix timestamp specifying the last time at which the coupon can be redeemed.
$coupon = Stripe::coupons()->create([
    'id'          => '50-PERCENT-OFF',
    'duration'    => 'forever',
    'percent_off' => 50,
]);

echo $coupon['id'];

Delete a coupon

You can delete coupons via the coupon management page of the Stripe dashboard. However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons via the API.

Arguments
Key Required Type Default Description
id true string null The coupon unique identifier.
$coupon = Stripe::coupons()->destroy([
    'id' => '50-PERCENT-OFF',
]);

Retrieve all the existing coupons

Returns a list of your coupons.

Arguments
Key Required Type Default Description
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
$coupons = Stripe::coupons()->all();

foreach ($coupons['data'] as $coupon)
{
    var_dump($coupon['id']);
}

Retrieve an existing coupon

Retrieves the coupon with the given ID.

Arguments
Key Required Type Default Description
id true string null The coupon unique identifier.
$coupon = Stripe::coupons()->find([
    'id' => '50-PERCENT-OFF',
]);

echo $coupon['percent_off'];
Using the alias
$charge = Stripe::coupon('50-PERCENT-OFF');

Subscriptions

Subscriptions allow you to charge a customer's card on a recurring basis. A subscription ties a customer to a particular plan.

Create a subscription

Creates a new subscription on an existing customer.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier that this subscription belongs to.
plan true string null The plan unique identifier.
coupon false string null The coupon unique identifier.
trial_end false int null UTC integer timestamp representing the end of the trial period the customer will get before being charged for the first time.
card false string or array null The card token or an array.
quantity false int 1 The quantity you'd like to apply to the subscription you're creating.
application_fee_percent false int null A positive decimal (with at most two decimal places) between 1 and 100.
metadata false array [] A set of key/value pairs that you can attach to a subscription object.
$subscription = Stripe::subscriptions()->create([
    'customer' => 'cus_4EBumIjyaKooft',
    'plan'     => 'monthly',
]);

echo $subscription['id'];

Cancel a subscription

Cancels a customer's subscription. If you set the at_period_end parameter to true, the subscription will remain active until the end of the period, at which point it will be canceled and not renewed. By default, the subscription is terminated immediately. In either case, the customer will not be charged again for the subscription. Note, however, that any pending invoice items that you've created will still be charged for at the end of the period unless manually deleted. If you've set the subscription to cancel at period end, any pending prorations will also be left in place and collected at the end of the period, but if the subscription is set to cancel immediately, pending prorations will be removed.

By default, all unpaid invoices for the customer will be closed upon subscription cancellation. We do this in order to prevent unexpected payment retries once the customer has canceled a subscription. However, you can reopen the invoices manually after subscription cancellation to have us proceed with automatic retries, or you could even re-attempt payment yourself on all unpaid invoices before allowing the customer to cancel the subscription at all.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier that this subscription belongs to.
id true string null The subscription unique identifier.
at_period_end false bool false A flag that if set to true will delay the cancellation of the subscription until the end of the current period.
$subscription = Stripe::subscriptions()->cancel([
    'customer' => 'cus_4EBumIjyaKooft',
    'id'       => 'sub_4ETjGeEPC5ai9J',
]);
Cancel at the end of the period
$subscription = Stripe::subscriptions()->cancel([
    'customer'      => 'cus_4EBumIjyaKooft',
    'id'            => 'sub_4ETjGeEPC5ai9J',
    'at_period_end' => true,
]);

Update a subscription

Updates an existing subscription on a customer to match the specified parameters. When changing plans or quantities, we will optionally prorate the price we charge next month to make up for any price changes.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier that this subscription belongs to.
id true string null The subscription unique identifier.
plan false string null The plan unique identifier.
coupon false string null The coupon unique identifier.
prorate false bool true Flag telling us whether to prorate switching plans during a billing cycle.
trial_end false int null UTC integer timestamp representing the end of the trial period the customer will get before being charged for the first time.
card false string or array null The card token or an array.
quantity false int 1 The quantity you'd like to apply to the subscription you're creating.
application_fee_percent false int null A positive decimal (with at most two decimal places) between 1 and 100.
metadata false array [] A set of key/value pairs that you can attach to a subscription object.
$subscription = Stripe::subscriptions()->update([
    'customer'      => 'cus_4EBumIjyaKooft',
    'id'            => 'sub_4EUEBlsoU7kRHX',
    'plan'          => 'monthly',
    'at_period_end' => false,
]);

Retrieve all the subscriptions of a customer

You can see a list of the customer's active subscriptions. Note that the 10 most recent active subscriptions are always available by default on the customer object. If you need more than those 10, you can use the limit and starting_after parameters to page through additional subscriptions.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier that this subscription belongs to.
ending_before false string null A cursor to be used in pagination.
limit false integer 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
$subscriptions = Stripe::subscriptions()->all([
    'customer' => 'cus_4EBumIjyaKooft',
]);

foreach ($subscriptions['data'] as $subscription)
{
    var_dump($subscription['id']);
}

Retrieve a subscription of a customer

Retrieves the details of an existing customer subscription.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier that this subscription belongs to.
id true string null The subscription unique identifier.
$subscription = Stripe::subscriptions()->find([
    'customer' => 'cus_4EBumIjyaKooft',
    'id'       => 'sub_4ETjGeEPC5ai9J',
]);

echo $subscription['id'];
Using the alias
$charge = Stripe::subscription('cus_4EBumIjyaKooft', 'sub_4ETjGeEPC5ai9J');

Delete a subscription discount

Removes the currently applied discount on a subscription.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier that this subscription belongs to.
id true string null The subscription unique identifier.
$customer = Stripe::subscriptions()->deleteDiscount([
    'customer' => 'cus_4EBumIjyaKooft',
    'id'       => 'sub_4ETjGeEPC5ai9J',
])->toArray();

Invoices

Invoices are statements of what a customer owes for a particular billing period, including subscriptions, invoice items, and any automatic proration adjustments if necessary.

Create a new invoice

If you need to invoice your customer outside the regular billing cycle, you can create an invoice that pulls in all pending invoice items, including prorations. The customer's billing cycle and regular subscription won't be affected.

Once you create the invoice, it'll be picked up and paid automatically, though you can choose to pay it right away.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
application_fee false int null An application fee to add on to this invoice.
description false string null An arbitrary string which you can attach to a invoice object.
metadata false array [] A set of key/value pairs that you can attach to a invoice object.
statement_description false string null An arbitrary string to be displayed alongside your company name on your customer's credit card statement.
subscription false string null The subscription unique identifier to invoice.
$invoice = Stripe::invoices()->create([
    'customer' => 'cus_4EBumIjyaKooft',
]);

Update an invoice

Until an invoice is paid, it is marked as open (closed=false). If you'd like to stop Stripe from automatically attempting payment on an invoice or would simply like to close the invoice out as no longer owed by the customer, you can update the closed parameter.

Arguments
Key Required Type Default Description
id true string null The invoice unique identifier.
application_fee false int null An application fee to add on to this invoice.
closed false bool false Boolean representing whether an invoice is closed or not.
description false string null An arbitrary string which you can attach to a invoice object.
forgiven false bool false Boolean representing whether an invoice is forgiven or not.
metadata false array [] A set of key/value pairs that you can attach to a invoice object.
statement_description false string null An arbitrary string to be displayed alongside your company name on your customer's credit card statement.
subscription false string null The subscription unique identifier to invoice.
$invoice = Stripe::invoices()->update([
    'id'     => 'in_4EgP02zb8qxsLq',
    'closed' => true,
]);

Pay an existing invoice

Stripe automatically creates and then attempts to pay invoices for customers on subscriptions. We'll also retry unpaid invoices according to your retry settings. However, if you'd like to attempt to collect payment on an invoice out of the normal retry schedule or for some other reason, you can do so.

Arguments
Key Required Type Default Description
id true string null The invoice unique identifier.
$invoice = Stripe::invoices()->pay([
    'id' => 'in_4EgP02zb8qxsLq',
]);

Retrieve all the existing invoices

You can list all invoices, or list the invoices for a specific customer. The invoices are returned sorted by creation date, with the most recently created invoices appearing first.

Arguments
Key Required Type Default Description
customer false string null The customer unique identifier.
date false string null A filter on the list based on the object date field.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
$invoices = Stripe::invoices()->all();

foreach ($invoices['data'] as $invoice)
{
    var_dump($invoice['id']);
}

Retrieve an existing invoice

Retrieves the invoice with the given ID.

Arguments
Key Required Type Default Description
id true string null The invoice unique identifier.
$invoice = Stripe::invoices()->find([
    'id' => 'in_4EgP02zb8qxsLq',
]);

echo $invoice['paid'];
Using the alias
$charge = Stripe::invoice('in_4EgP02zb8qxsLq');

Retrieve an existing invoice line items

When retrieving an invoice, you'll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items.

Arguments
Key Required Type Default Description
id true string null The invoice unique identifier.
customer false string null The customer unique identifier.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
subscription false string null The subscription unique identifier.
$lines = Stripe::invoices()->invoiceLineItems([
    'id' => 'in_4EgP02zb8qxsLq',
]);

foreach ($lines['data'] as $line)
{
    var_dump($line['id']);
}

Retrieve the upcoming invoice

At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discount that is applicable to the customer.

Note that when you are viewing an upcoming invoice, you are simply viewing a preview -- the invoice has not yet been created. As such, the upcoming invoice will not show up in invoice listing calls, and you cannot use the API to pay or edit the invoice. If you want to change the amount that your customer will be billed, you can add, remove, or update pending invoice items, or update the customer's discount.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
subscription false string null The subscription unique identifier.
$invoice = Stripe::invoices()->upcomingInvoice([
    'customer' => 'cus_4EBumIjyaKooft',
]);

foreach ($invoice['lines']['data'] as $item)
{
    var_dump($item['id']);
}

Invoice Items

Sometimes you want to add a charge or credit to a customer but only actually charge the customer's card at the end of a regular billing cycle. This is useful for combining several charges to minimize per-transaction fees or having Stripe tabulate your usage-based billing totals.

Create a new invoice item

Adds an arbitrary charge or credit to the customer's upcoming invoice.

Arguments
Key Required Type Default Description
customer true string null The customer unique identifier.
amount true number null A positive amount for the transaction.
currency true string null 3-letter ISO code for currency.
invoice false string null The invoice unique identifier.
subscription false string null The subscription unique identifier to invoice.
description false string null An arbitrary string which you can attach to a invoice item object.
metadata false array [] A set of key/value pairs that you can attach to a invoice item object.
$item = Stripe::invoiceItems()->create([
    'customer' => 'cus_4EBumIjyaKooft',
    'amount'   => 50.00,
    'currency' => 'USD',
]);

echo $item['id'];

Update an invoice item

Updates the amount or description of an invoice item on an upcoming invoice. Updating an invoice item is only possible before the invoice it's attached to is closed.

Arguments
Key Required Type Default Description
id true string null The invoice item unique identifier.
amount false number null A positive amount for the transaction.
description false string null An arbitrary string which you can attach to a invoice item object.
metadata false array [] A set of key/value pairs that you can attach to a invoice item object.
$item = Stripe::invoiceItems()->update([
    'id'          => 'ii_4Egr3tUtHjVEnm',
    'description' => 'Candy',
    'metadata'    => [
        'foo' => 'Bar',
    ],
]);

Delete an invoice item

Removes an invoice item from the upcoming invoice. Removing an invoice item is only possible before the invoice it's attached to is closed.

Arguments
Key Required Type Default Description
id true string null The invoice item unique identifier.
Stripe::invoiceItems()->destroy([
    'id' => 'ii_4Egr3tUtHjVEnm',
]);

Retrieve all invoice items

Returns a list of your invoice items. Invoice Items are returned sorted by creation date, with the most recently created invoice items appearing first.

Arguments
Key Required Type Default Description
created false string null A filter on the list based on the object created field.
customer false string null The customer unique identifier.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
$items = Stripe::invoiceItems()->find();

foreach ($items['data'] as $item)
{
    var_dump($item['id']);
}

Retrieve an invoice item

Retrieves the invoice item with the given ID.

Arguments
Key Required Type Default Description
id true string null The invoice item unique identifier.
$item = Stripe::invoiceItems()->find([
    'id' => 'ii_4Egr3tUtHjVEnm',
]);

echo $item['amount'];
Using the alias
$charge = Stripe::invoiceItem('ii_4Egr3tUtHjVEnm');

Transfers

When Stripe sends you money or you initiate a transfer to a third party recipient's bank account or debit card, a transfer object will be created. You can retrieve individual transfers as well as list all transfers.

Create a new transfer

Arguments
Key Required Type Default Description
amount true number null A positive amount for the transaction.
currency true string null 3-letter ISO code for currency.
recipient true string null The ID of an existing, verified recipient.
description false string null An arbitrary string which you can attach to a transfer object.
bank_account false string null If a recipient has both a bank account and a card attached, this parameter or the card parameter must be provided, but never both.
card false string null The card unique identifier.
statement_description false string null An arbitrary string which will be displayed on the recipient's bank statement.
metadata false array [] A set of key/value pairs that you can attach to a transfer object.
$transfer = Stripe::transfers()->create([
    'amount'    => 10.00,
    'currency'  => 'USD',
    'recipient' => 'rp_4EYxxX0LQWYDMs',
]);

echo $transfer['id'];

Update a transfer

Arguments
Key Required Type Default Description
id true string null The transfer unique identifier.
description false string null An arbitrary string which you can attach to a transfer object.
metadata false array [] A set of key/value pairs that you can attach to a transfer object.
$transfer = Stripe::transfers()->update([
    'id'          => 'tr_4EZer9REaUzJ76',
    'description' => 'Transfer to John Doe',
]);

echo $transfer['description'];

Cancel a transfer

Arguments
Key Required Type Default Description
id true string null The transfer unique identifier.
$transfer = Stripe::transfers()->cancel([
    'id' => 'tr_4EZer9REaUzJ76',
]);

Retrieve all the existing transfers

Arguments
Key Required Type Default Description
created false string null A filter on the list based on the object created field.
date false string null A filter on the list based on the object date field.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
recipient false string null Only return transfers for the recipient specified by this recipient ID.
starting_after false string null A cursor to be used in pagination.
status false string null Only return transfers that have the given status: "pending", "paid", or "failed".
$transfers = Stripe::transfers()->all();

foreach ($transfers['data'] as $transfer)
{
    var_dump($transfer['id']);
}

Retrieve an existing transfer

Arguments
Key Required Type Default Description
id true string null The transfer unique identifier.
$transfers = Stripe::transfers()->find([
    'id' => 'tr_4EZer9REaUzJ76',
]);

echo $transfer['id'];

Recipients

With recipient objects, you can transfer money from your Stripe account to a third party bank account or debit card. The API allows you to create, delete, and update your recipients. You can retrieve individual recipients as well as a list of all your recipients.

Create a new recipient

Arguments
Key Required Type Default Description
name true string null The recipient's full, legal name.
type true string null Type of the recipient: either individual or corporation.
tax_id false string null The recipient's tax ID, as a string. For type individual, the full SSN; for type corporation, the full EIN.
bank_account false array null A bank account to attach to the recipient.
card false string or array null The card token or an array.
email false string null The recipient's email address.
description false string null An arbitrary string which you can attach to a recipient object.
metadata false array null A set of key/value pairs that you can attach to a recipient object.
$recipient = Stripe::recipients()->create([
    'name' => 'John Doe',
    'type' => 'individual',
]);

Update a recipient

Arguments
Key Required Type Default Description
id true string null The recipient unique identifier.
name false string null The recipient's full, legal name.
tax_id false string null The recipient's tax ID, as a string. For type individual, the full SSN; for type corporation, the full EIN.
bank_account false array null A bank account to attach to the recipient.
card false string or array null The card token or an array.
default_card false string null ID of card to make the recipient’s new default for transfers.
email false string null The recipient's email address.
description false string null An arbitrary string which you can attach to a recipient object.
metadata false array null A set of key/value pairs that you can attach to a recipient object.
$recipient = Stripe::recipients()->update([
    'id'   => 'rp_4EYRyEYthf2Doc',
    'name' => 'John Doe Inc.',
]);

Delete a recipient

Arguments
Key Required Type Default Description
id true string null The recipient unique identifier.
$recipient = Stripe::recipients()->destroy([
    'id' => 'rp_4EYRyEYthf2Doc',
]);

Retrieve all the recipients

Arguments
Key Required Type Default Description
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
verified false bool null Only return recipients that are verified or unverified.
$recipients = Stripe::recipients()->all();

foreach ($recipients['data'] as $recipient)
{
    var_dump($recipient['id']);
}

Retrieve a recipient

Arguments
Key Required Type Default Description
id true string null The recipient unique identifier.
$recipient = Stripe::recipients()->find([
    'id' => '50-PERCENT-OFF',
]);

echo $recipient['id'];

Tokens

Often you want to be able to charge credit cards or send payments to bank accounts without having to hold sensitive card information on your own servers. Stripe.js makes this easy in the browser, but you can use the same technique in other environments with our token API.

Create a card token

Creates a single use token that wraps the details of a credit card. This token can be used in place of a credit card dictionary with any API method. These tokens can only be used once: by creating a new charge object, or attaching them to a customer.

Arguments
Key Required Type Default Description
card true string or array null The card unique identifier.
customer false string null A customer to create a token for.
$token = Stripe::tokens()->create([
    'card' => [
        'number'    => '4242424242424242',
        'exp_month' => 6,
        'exp_year'  => 2015,
        'cvc'       => 314,
    ],
]);

echo $token['id'];

Create a bank account token

Creates a single use token that wraps the details of a bank account. This token can be used in place of a bank account dictionary with any API method. These tokens can only be used once: by attaching them to a recipient.

Arguments
Key Required Type Default Description
bank_account true array null A bank account to attach to the recipient.
$token = Stripe::tokens()->create([
    'bank_account' => [
        'country'        => 'US',
        'routing_number' => '110000000',
        'account_number' => '000123456789',
    ],
]);

echo $token['id'];

Account

This is an object representing your Stripe account. You can retrieve it to see properties on the account like its current e-mail address or if the account is enabled yet to make live charges.

Retrieve information about your Stripe account.

Example
$account = Stripe::account()->details();

echo $account['email'];

Balance

This is an object representing your Stripe balance. You can retrieve it to see the balance currently on your Stripe account.

You can also retrieve a list of the balance history, which contains a full list of transactions that have ever contributed to the balance (charges, refunds, transfers, and so on).

Retrieve account balance

$balance = Stripe::balance()->current();

echo $balance['pending']['amount'];

Retrieve all the balance history

$history = Stripe::balance()->all();

foreach ($history['data'] as $balance)
{
    var_dump($balance['id']);
}

Retrieve a balance history

$balance = Stripe::balance()->history([
    'id' => 'txn_4EI2Pu1gPR27yT',
]);

echo $balance['amount'];

Events

Events are our way of letting you know about something interesting that has just happened in your account. When an interesting event occurs, we create a new event object. For example, when a charge succeeds we create a charge.succeeded event; or, when an invoice can't be paid we create an invoice.payment_failed event. Note that many API requests may cause multiple events to be created. For example, if you create a new subscription for a customer, you will receive both a customer.subscription.created event and a charge.succeeded event.

Retrieve all the events

Arguments
Key Required Type Default Description
created false string null A filter on the list based on the object created field.
ending_before false string null A cursor to be used in pagination.
limit false int 10 A limit on the number of objects to be returned.
starting_after false string null A cursor to be used in pagination.
type false string null A string containing a specific event name, or group of events using * as a wildcard.
$events = Stripe::events()->all();

foreach ($events['data'] as $event)
{
    var_dump($event);
}

Retrieve an event

Arguments
Key Required Type Default Description
id true string null The event unique identifier.
$event = Stripe::events()->find([
    'id' => 'evt_4ECnKrmXyNn8IM',
]);

echo $event['type'];

Pagination

Handling pagination on APIs is very hard and instead of manually handling the pagination, the Stripe package comes with a resource iterator which handles all of this for you, automatically!

Here is an example of grabbing all the customers:

$customers = Stripe::customersIterator();

foreach ($customers as $customer)
{
    var_dump($customer['id']);
}

You can still pass any API argument as you would with any normal API method:

$customers = Stripe::customersIterator([
    'created' => 123456789,
]);

foreach ($customers as $customer)
{
    var_dump($customer['id']);
}

Set results limit

If you have the need to lock the number of results, you can achieve this by using the ->setLimit(:amount); method:

$customers = Stripe::customersIterator();
$customers->setLimit(30);

foreach ($customers as $customer)
{
    var_dump($customer['id']);
}

In this example, it will only return 30 results.

Set results per page

Setting a number of results per page is very easy and very similar to the results limit "locking", you just need to use the ->setPageSize(:amount); method:

$customers = Stripe::customersIterator();
$customers->setPageSize(50);

foreach ($customers as $customer)
{
    var_dump($customer['id']);
}

Note: The max results per page that Stripe allows is 100.

Handling Exceptions

The Stripe API throws two kinds of exceptions:

Guzzle Exceptions

These exceptions will be thrown since Guzzle will automatically validate all the arguments you provide according to the manifest file rules.

If an argument is invalid, Guzzle will throw a Guzzle\Service\Exception\ValidationException exception,

try
{
    $customer = Stripe::customers()->find([
        // We should pass in the id argument here..
    ]);
}
catch (Guzzle\Service\Exception\ValidationException $e)
{
    $errors = $e->getErrors();
}
API Exceptions

These exceptions will be thrown when something is wrong, like when a credit card with a bad number is submited, an expired credit card or even when Stripe.com itself has done something wrong.

Here is the list of all the exceptions that the Stripe API throws with a brief description:

Exception Description
Cartalyst\Stripe\Api\Exception\BadRequestException This exception will be thrown when the data sent through the request is mal formed.
Cartalyst\Stripe\Api\Exception\UnauthorizedException This exception will be thrown if your Stripe API Key is incorrect.
Cartalyst\Stripe\Api\Exception\RequestFailedException This exception will be thrown whenever the request fails for some reason.
Cartalyst\Stripe\Api\Exception\CardErrorException This exception will be thrown whenever the credit card is invalid.
Cartalyst\Stripe\Api\Exception\NotFoundException This exception will be thrown whenever a request results on a 404.
Cartalyst\Stripe\Api\Exception\ServerErrorException This exception will be thrown whenever Stripe does something wrong.

Usage

Below is an example of using the API to find a customer, but this customer doesn't exist, so it'll thrown a NotFoundException.

try
{
    $customer = Stripe::customers()->find([
        'id' => 'foobar',
    ]);

    echo $customer['email'];
}
catch (Cartalyst\Stripe\Api\Exception\NotFoundException $e)
{
    // Get the error message returned by Stripe
    $message = $e->getMessage();

    // Get the error type returned by Stripe
    $type = $e->getErrorType();

    // Get the status code
    $code = $e->getCode();

    // Get the request response, if required to get more information
    $response = $e->getResponse();
}

Billable Entities

In this section we'll show how you can use the billable entities feature.

Note: A User model will be used for the following examples.

$entity->isBillable()

This method is very useful when you need to determine if the entity is ready to be billed, or in other words, if the entity has a Stripe customer already attached.

Example
$user = User::find(1);

if ( ! $user->isBillable())
{
    echo "User is not ready to be billed!";
}

$entity->applyCoupon()

Applies a coupon on the entity, this will execute a Stripe API call to apply the coupon on the Stripe customer that is attached to this entity.

Arguments
Key Required Type Default Description
$coupon true string null The coupon unique identifier.
Example
$coupon = Input::get('coupon');

$user = User::find(1);

$user->applyCoupon($coupon);

$entity->isSubscribed()

This method will help you to determine if the entity has any active subscription.

Example
$user = User::find(1);

if ($user->isSubscribed())
{
    //
}

$entity->hasActiveCard()

This method will help you to determine if the entity has any active credit card.

Example
$user = User::find(1);

if ($user->hasActiveCard())
{
    //
}

Attaching

In a scenario where you already have your Stripe customers but you don't have them attached to entities on local storage you would obviously be wanting for an easy and fast way to attach them.

With this scenario in mind, we've two methods implemented that will help you to attach all the Stripe customers at once or a single Stripe customer at a time with the ability to syncronize all their related data like cards, charges, invoices and subscriptions.

Please refer to the following sections for a better understanding and example of usage.

Attach a single Stripe Customer

You have a Stripe customer and you want to attach that Stipe customer to an entity you have stored locally, to make it easy, we've the attachStripeCustomer() method that will do this job for you and it'll syncronize all the related data automatically using the syncWithStripe().

Arguments
Key Required Type Default Description
$data true Cartalyst\Stripe\Api\Response null The Stripe customer data.
$sync false bool true If it should syncronize the related data.
Example
// Get the Stripe customer
$customer = Stripe::customer('cus_4EBumIjyaKooft');

// Get the entity and attach the Stripe customer
$entity = User::where('email', $customer['email'])->first();
$entity->attachStripeCustomer($customer);

Attach all Stripe Customers

Attaching all Stripe customers is even easier and internally it works exactly like the attachStripeCustomer() method with the main difference that you need to pass a Closure and return the entity from within the Closure.

The entity that is returned from the Closure needs to be the entity that will be used to attach the Stripe customer that is passed through the $customer argument on the Closure to the entity you return, so you can use any information you see fit on your application to search for the proper entity using the $customer object.

Arguments
Key Required Type Default Description
$callback true Closure null A Closure that should return a Cartalyst\Stripe\Billing\BillableInterface object.
$sync false bool true If it should syncronize the related data.
Example
use Cartalyst\Stripe\Api\Response;

User::attachStripeCustomers(function(Response $customer)
{
    return User::where('email', $customer['email'])->first();
});

Synchronization

Synchronize all the entities

User::syncStripeCustomers(function($customer)
{
    return User::where('stripe_id', $customer['id'])->first();
});

Synchronize a single entity

If you have the need to completely have your local data in sync with the Stripe data, you can use the syncWithStripe() method.

This will syncronize up the cards, charges, invoices and their invoice items, the pending invoice items and subscriptions that belongs to your entity.

Example
$user = User::find(1);

$user->syncWithStripe();

Credit Cards

Retrieve all the attached cards

Listing the attached cards from an entity is very easy.

$user = User::find(1);

$cards = $user->cards;

Attaching credit cards

Attach a new credit card to the entity.

$token = Input::get('stripeToken');

$user = User::find(1);

$user->card()->create($token);
Attaching and setting it as default

If you want to attach a credit card to the entity and make it the default credit card, you need to use the makeDefault() method.

$token = Input::get('stripeToken');

$user = User::find(1);

$user->card()->makeDefault()->create($token);

Updating credit cards

Update a credit card.

$user = User::find(1);

$attributes = [
    'name' => 'John Doe',
];

$user->card(10)->update($attributes);
Setting an existing credit card the default credit card.
$user = User::find(1);

$user->card(10)->setDefault();

Deleting credit cards

$user = User::find(1);

$user->card(10)->delete();

Get the entity default Credit Card

$user = User::find(1);

$card = $user->getDefaultCard();

echo $card->last_four;

Update the entity default Credit Card

$token = Input::get('stripeToken');

$user = User::find(1);

$user->updateDefaultCard($token);

Check if the entity has any active card

$user = User::find(1);

if ( ! $user->hasActiveCard())
{
    echo "User doesn't have any active credit card!";
}
Sync data from Stripe

Often you might have the need to sync the data from Stripe with your database, we have an easy way to achieve this.

$user = User::find(1);

$user->card()->syncWithStripe();

Note: You can pass a card id integer or a Cartalyst\Stripe\Billing\Models\IlluminateCard object through the card() method.

Charges

Retrieve all the charges

$user = User::find(1);

$charges = $user->charges;
Retrieve an existing charge
$user = User::find(1);

$charge = $user->charges->find(10);

echo $charge['amount'];
Creating charges
$user = User::find(1);

$amount = 150.95;

$user
    ->charge()
    ->create($amount, [
        'description' => 'Purchased Book!',
    ]);

Creating a charge with a new credit card.

$token = Input::get('stripeToken');

$user = User::find(1);

$amount = 150.95;

$user
    ->charge()
    ->setToken($token)
    ->create($amount, [
        'description' => 'Purchased Book!',
    ]);

Creating a charge to be captured later.

$user = User::find(1);

$amount = 150.95;

$user
    ->charge()
    ->captureLater()
    ->create($amount, [
        'description' => 'Purchased Book!',
    ]);

Capturing a charge.

$user = User::find(1);

$user
    ->charge(10)
    ->capture();
Refund charges

Do a full refund

$user = User::find(1);

$user
    ->charge(10)
    ->refund();

Do a partial refund

$user = User::find(1);

$amount = 50.00;

$user
    ->charge(10)
    ->refund($amount);
Sync data from Stripe

Often you might have the need to sync the data from Stripe with your database, we have an easy way to achieve this.

$user = User::find(1);

$user
    ->charge()
    ->syncWithStripe();

Note: You can pass a charge id integer or a Cartalyst\Stripe\Billing\Models\IlluminateCharge object through the charge() method.

Invoices

Creating Invoices

Creating invoices on your billable entities is a breeze.

Create the invoices item and Create the Invoice

First we need to create an invoice item:

$item = $user->invoice()->items()->create([
    'amount'      => 34.50,
    'currency'    => 'USD',
    'description' => 'Line 1 description',
]);

Now that we have our item created we can create our invoice:

$invoice = $user->invoice()->create();
Create a new Invoice and pass in invoice line items
$invoice = $user->invoice()->create([
    'items' => [
        [
            'amount'      => 34.50,
            'currency'    => 'USD',
            'description' => 'Line 1 description',
        ],
        [
            'amount'      => 10.95,
            'currency'    => 'USD',
            'description' => 'Line 2 description',
        ],
    ],
]);

Pay an Invoice

$user->invoice(10)->pay();

or

$user->invoice()->pay('in_4TGCNPyz32qIUr');

Retrieve all the invoices

$user = User::find(1);

$invoices = $user->invoices;

Retrieve an existing invoice

$user = User::find(1);

$invoice = $user->invoices->find(10);

$items = $invoice->items;

echo $invoice['total'];

Sync data from Stripe

Often you might have the need to sync the data from Stripe with your database, we have an easy way to achieve this.

$user = User::find(1);

$user
    ->invoice()
    ->syncWithStripe();

Note: You can pass a invoice id integer or a Cartalyst\Stripe\Billing\Models\IlluminateInvoice object through the invoice() method.

Subscriptions

List all the user subscriptions

$user = User::find(1);

$subscriptions = $user->subscriptions;

Creating subscriptions

Subscribing an entity to a plan

$token = Input::get('stripeToken');

$user = User::find(1);

$user
    ->subscription()
    ->onPlan('monthly')
    ->setToken($token)
    ->create();

Subscribing an entity to a plan and apply a coupon to this new subscription

$token = Input::get('stripeToken');

$coupon = Input::get('coupon');

$user = User::find(1);

$user
    ->subscription()
    ->onPlan('monthly')
    ->withCoupon($coupon)
    ->setToken($token)
    ->create();

Create a trial subscription

$token = Input::get('stripeToken');

$user = User::find(1);

$user
    ->subscription()
    ->onPlan('monthly')
    ->trialFor(Carbon::now()->addDays(14))
    ->setToken($token)
    ->create();

Cancelling subscriptions

Cancel a Subscription using its id

$user = User::find(1);

$user
    ->subscription(10)
    ->cancel();

Cancelling a subscription by passing a Cartalyst\Stripe\Subscription\IlluminateSubscription object.

$user = User::find(1);

$subscription = $user->subscriptions()->where('stripe_id', 'sub_48w0VyQzcNWCe3')->first();

$user
    ->subscription($subscription)
    ->cancel();

Cancel a subscription at the End of the Period

$user = User::find(1);

$user
    ->subscription(10)
    ->cancelAtEndOfPeriod();

Updating subscriptions

Apply a trial period on a subscription

$user = User::find(1);

$user
    ->subscription(10)
    ->setTrialPeriod(Carbon::now()->addDays(14))

Removing the trial period from a subscription

$user = User::find(1);

$user
    ->subscription(10)
    ->removeTrialPeriod()

Apply a coupon to an existing subscription

$coupon = Input::get('coupon');

$user = User::find(1);

$user
    ->subscription(10)
    ->applyCoupon($coupon);

Remove a coupon from an existing subscription

$user = User::find(1);

$user
    ->subscription(10)
    ->removeCoupon();

Resuming subscriptions

Resume a canceled subscription

$user = User::find(1);

$user
    ->subscription(10)
    ->resume();

Resume a canceled subscription and remove its trial period

$user = User::find(1);

$user
    ->subscription(10)
    ->skipTrial()
    ->resume();

Resume a canceled subscription and change its trial period end date

$user = User::find(1);

$user
    ->subscription(10)
    ->trialFor(Carbon::now()->addDays(14))
    ->resume()

Checking a Subscription Status

First, we need to grab the subscription:

$user = User::find(1);

$subscription = $user->subscriptions->find(10);

To determine if the subscription is on the trial period, you may use the onTrialPeriod() method:

if ($subscription->onTrialPeriod())
{
    //
}

To determine if the subscription is marked as canceled, you may use the canceled method:

if ($subscription->isCanceled())
{
    //
}

To determine if the subscription has expired, you may use the expired method:

if ($subscription->isExpired())
{
    //
}

You may also determine if a subscription, is still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was scheduled to end on March 10th, the user is on their "grace period" until March 10th.

if ($subscription->onGracePeriod())
{
    //
}

Sync data from Stripe

Often you might have the need to sync the data from Stripe with your database, we have an easy way to achieve this.

$user = User::find(1);

$user
    ->subscription()
    ->syncWithStripe();

Note: You can pass a subscription id integer or a Cartalyst\Stripe\Billing\Models\IlluminateSubscription object through the subscription() method.

Extending Models

Extending the default models is very easy, we provide handy methods you can utilise with your Entity model.

Firstly you create your model(s) and this model needs to extend the model you want to "override", here's an example on how to do it:

<?php

use Cartalyst\Stripe\Billing\Models\IlluminateCard;

class Card extends IlluminateCard {

    // You can create any new methods here or if
    // required, you can override any existing
    // method to apply your custom features.

}

Note: Please use the list below for a complete list of models namespace paths.

Models list

Model Name Model full namespace path
Card Cartalyst\Stripe\Billing\Models\IlluminateCard
Charge Cartalyst\Stripe\Billing\Models\IlluminateCharge
ChargeRefund Cartalyst\Stripe\Billing\Models\IlluminateChargeRefund
Invoice Cartalyst\Stripe\Billing\Models\IlluminateInvoice
InvoiceItem Cartalyst\Stripe\Billing\Models\IlluminateInvoiceItem
Subscription Cartalyst\Stripe\Billing\Models\IlluminateSubscription

Set the models

Now that you've the model(s) created, it's time to set them.

This can be done where you see it's more appropriate on your application, as an example, you can do this on the app/filters.php file, this is to ensure you only apply this change once per request!

Note: We recommended that this should be done the earlier as you can on your application.

$entity->setCardModel()

This method will change the card model on the entity.

User::setCardModel('Acme\Models\Card');
$entity->setChargeModel()

This method will change the charge model on the entity.

User::setChargeModel('Acme\Models\Charge');
$entity->setChargeRefundModel()

This method will change the charge refunds model on the entity.

User::setChargeRefundModel('Acme\Models\ChargeRefund');
$entity->setInvoiceModel()

This method will change the invoice model on the entity.

User::setInvoiceModel('Acme\Models\Invoice');
$entity->setInvoiceItemModel()

This method will change the invoice items model on the entity.

User::setInvoiceItemModel('Acme\Models\InvoiceItem');
$entity->setSubscriptionModel()

This method will change the subscription model on the entity.

User::setSubscriptionModel('Acme\Models\Subscription');

Note: The User model we're using for these examples, is the model you've applied the Billable Trait!

Events

On this section we have a list of all the events fired by the Stripe package that you can listen for on your application.

Event Parameters Description
cartalyst.stripe.card.created $entity, $response, $card Event fired when a new credit card is attached to the entity.
cartalyst.stripe.card.updated $entity, $response, $card Event fired when an existing credit card is updated.
cartalyst.stripe.card.deleted $entity, $response Event fired when an existing credit card is deleted.
cartalyst.stripe.charge.created $entity, $response, $charge Event fired when a new charge is created.
cartalyst.stripe.charge.updated $entity, $response, $charge Event fired when an existing charge is updated.
cartalyst.stripe.charge.captured $entity, $response, $charge Event fired when an existing charge is refunded.
cartalyst.stripe.charge.refunded $entity, $response, $charge Event fired when an existing charge is captured.
cartalyst.stripe.invoice.created $entity, $response, $invoice Event fired when a new invoice is attached to the entity.
cartalyst.stripe.invoice.updated $entity, $response, $invoice Event fired when an existing invocie is updated.
cartalyst.stripe.invoice.paid $entity, $response, $invoice Event fired when an existing invocie is paid.
cartalyst.stripe.invoice.item.created $entity, $response, $item Event fired when a new invoice item is created.
cartalyst.stripe.invoice.item.updated $entity, $response, $item Event fired when an existing invoice item is updated.
cartalyst.stripe.invoice.item.deleted $entity, $response Event fired when an existing invoice item is deleted.
cartalyst.stripe.subscription.created $entity, $response, $subscription Event fired when a new subscription is attached to the entity.
cartalyst.stripe.subscription.updated $entity, $response, $subscription Event fired when an existing subscription is updated.
cartalyst.stripe.subscription.updated $entity, $response, $subscription Event fired when an existing subscription is canceled.
cartalyst.stripe.subscription.resumed $entity, $response, $subscription Event fired when an existing subscription is resumed.

Note: Please refer to the list below for the full event parameter object namespace.

Parameter Response
$entity Cartalyst\Stripe\Billing\BillingInterface
$response Cartalyst\Stripe\Api\Response
$card Cartalyst\Stripe\Billing\Models\IlluminateCard
$charge Cartalyst\Stripe\Billing\Models\IlluminateCharge
$invoice Cartalyst\Stripe\Billing\Models\IlluminateInvoice
$item Cartalyst\Stripe\Billing\Models\IlluminateInvoiceItem
$subscription Cartalyst\Stripe\Billing\Models\IlluminateSubscription

Examples

Whenever a new subscription is attached to an entity.

use Cartalyst\Stripe\Api\Response;
use Cartalyst\Stripe\Billing\BillingInterface;
use Cartalyst\Stripe\Billing\Models\IlluminateSubscription;

Event::listen('cartalyst.stripe.subscription.created', function(BillingInterface $entity, Response $response, IlluminateSubscription $subscription)
{
    // Apply your own logic here
});

Whenever an existing subscription is canceled.

use Cartalyst\Stripe\Api\Response;
use Cartalyst\Stripe\Billing\BillingInterface;
use Cartalyst\Stripe\Billing\Models\IlluminateSubscription;

Event::listen('cartalyst.stripe.subscription.canceled', function(BillingInterface $entity, Response $response, IlluminateSubscription $subscription)
{
    // Apply your own logic here
});

Whenever an existing subscription is resumed.

use Cartalyst\Stripe\Api\Response;
use Cartalyst\Stripe\Billing\BillingInterface;
use Cartalyst\Stripe\Billing\Models\IlluminateSubscription;

Event::listen('cartalyst.stripe.subscription.resumed', function(BillingInterface $entity, Response $response, IlluminateSubscription $subscription)
{
    // Apply your own logic here
});

Webhooks

Listening to Stripe notification events (Webhooks) is incredible easy and you can listen to any notification that Stripe sends.

Setup

First create a new controller somewhere inside your application that extends our Cartalyst\Stripe\WebhookController controller.

<?php namespace Acme\Controllers;

use Cartalyst\Stripe\WebhookController as BaseWebhookController;

class WebhookController extends BaseWebhookController {

}

Note: The controller name and namespace is just for the example, you can name and place the controller where it fits best inside your application.

Now you need to register a post route that points to your controller:

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

Note: The route URI webhook/stripe is just for the example, you can choose to use a different one.

Once you have your route registered, you'll need to go into your Stripe.com Dashboard and setup the webhook.

Handling events

Now you just need to create the notification event handlers inside your controller, we have a few examples prepared below:

<?php

class WebhookController extends Cartalyst\Stripe\WebhookController {

    /**
     * Handles a successful payment.
     *
     * @param  array  $payload
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleChargeSucceeded($payload)
    {
        $charge = $this->handlePayment($payload);

        // apply your own logic here if required

        return $this->sendResponse('Webhook successfully handled.');
    }

    /**
     * Handles a failed payment.
     *
     * @param  array  $payload
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleChargeFailed($payload)
    {
        $charge = $this->handlePayment($payload);

        // apply your own logic here if required

        return $this->sendResponse('Webhook successfully handled.');
    }

    /**
     * Handles a payment refund.
     *
     * @param  array  $payload
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleChargeRefunded($payload)
    {
        $charge = $this->handlePayment($payload);

        // apply your own logic here if required

        return $this->sendResponse('Webhook successfully handled.');
    }

    /**
     * Handles the payment event.
     *
     * @param  array  $charge
     * @return \Cartalyst\Stripe\Billing\Models\IlluminateCharge
     */
    protected function handlePayment($charge)
    {
        $entity = $this->getBillable($charge['customer']);

        $entity->charge()->syncWithStripe();

        return $entity->charges()->whereStripeId($charge['id'])->first();
    }

}

Note 1: The examples above are merely for demonstration, you can apply your own logic for each event notification, we're just showing the power of the synchronization methods the Stripe package has to offer :)

Note 2: Please refer to the list below for all the events that Stripe sends and to know which controller method name you need to use.

Types of Events

Below is a complete list of all the webhook type events that Stripe.com sends.

We're covering in this list the proper method name you should use on your webhook controller.

Stripe Event Name Controller Method Name Description
account.updated handleAccountUpdated Occurs whenever an account status or property has changed.
account.application.deauthorized handleAccountApplicationDeauthorized Occurs whenever a user deauthorizes an application. Sent to the related application only.
application_fee.created handleApplicationFeeCreated Occurs whenever an application fee is created on a charge.
application_fee.refunded handleBalanceAvailable Occurs whenever your Stripe balance has been updated (e.g. when a charge collected is available to be paid out). By default, Stripe will automatically transfer any funds in your balance to your bank account on a daily basis.
charge.succeeded handleChargeSucceeded Occurs whenever a new charge is created and is successful.
charge.failed handleChargeFailed Occurs whenever a failed charge attempt occurs.
charge.refunded handleChargeRefunded Occurs whenever a charge is refunded, including partial refunds.
charge.captured handleChargeCaptured Occurs whenever a previously uncaptured charge is captured.
charge.updated handleChargeUpdated Occurs whenever a charge description or metadata is updated.
charge.dispute.created handleChargeDisputeCreated Occurs whenever a customer disputes a charge with their bank (chargeback).
charge.dispute.updated handleChargeDisputeUpdated Occurs when the dispute is updated (usually with evidence).
charge.dispute.closed handleChargeDisputeClosed Occurs when the dispute is resolved and the dispute status changes to won or lost.
customer.created handleCustomerCreated Occurs whenever a new customer is created.
customer.updated handleCustomerUpdated Occurs whenever any property of a customer changes.
customer.deleted handleCustomerDeleted Occurs whenever a customer is deleted.
customer.card.created handleCustomerCardCreated Occurs whenever a new card is created for the customer.
customer.card.updated handleCustomerCardUpdated Occurs whenever a card's details are changed.
customer.card.deleted handleCustomerCardDeleted Occurs whenever a card is removed from a customer.
customer.subscription.created handleCustomerSubscriptionCreated Occurs whenever a customer with no subscription is signed up for a plan.
customer.subscription.updated handleCustomerSubscriptionUpdated Occurs whenever a subscription changes. Examples would include switching from one plan to another, or switching status from trial to active.
customer.subscription.deleted handleCustomerSubscriptionDeleted Occurs whenever a customer ends their subscription.
customer.subscription.trialwillend handleCustomerSubscriptionTrialWillEnd Occurs three days before the trial period of a subscription is scheduled to end.
customer.discount.created handleCustomerDiscountCreated Occurs whenever a coupon is attached to a customer.
customer.discount.updated handleCustomerDiscountUpdated Occurs whenever a customer is switched from one coupon to another.
customer.discount.deleted handleCustomerDiscountDeleted Occurs whenever a customer's discount is removed.
invoice.created handleInvoiceCreated Occurs whenever a new invoice is created. If you are using webhooks, Stripe will wait one hour after they have all succeeded to attempt to pay the invoice; the only exception here is on the first invoice, which gets created and paid immediately when you subscribe a customer to a plan. If your webhooks do not all respond successfully, Stripe will continue retrying the webhooks every hour and will not attempt to pay the invoice. After 3 days, Stripe will attempt to pay the invoice regardless of whether or not your webhooks have succeeded. See how to respond to a webhook.
invoice.updated handleInvoiceUpdated Occurs whenever an invoice changes (for example, the amount could change).
invoice.payment_succeeded handleInvoicePaymentSucceeded Occurs whenever an invoice attempts to be paid, and the payment succeeds.
invoice.payment_failed handleInvoicePaymentFailed Occurs whenever an invoice attempts to be paid, and the payment fails. This can occur either due to a declined payment, or because the customer has no active card. A particular case of note is that if a customer with no active card reaches the end of its free trial, an invoice.payment_failed notification will occur.
invoiceitem.created handleInvoiceitemCreated Occurs whenever an invoice item is created.
invoiceitem.updated handleInvoiceitemUpdated Occurs whenever an invoice item is updated.
invoiceitem.deleted handleInvoiceitemDeleted Occurs whenever an invoice item is deleted.
plan.created handlePlanCreated Occurs whenever a plan is created.
plan.updated handlePlanUpdated Occurs whenever a plan is updated.
plan.deleted handlePlanDeleted Occurs whenever a plan is deleted.
coupon.created handleCouponCreated Occurs whenever a coupon is created.
coupon.deleted handleCouponDeleted Occurs whenever a coupon is deleted.
transfer.created handleTransferCreated Occurs whenever a new transfer is created.
transfer.updated handleTransferUpdated Occurs whenever the description or metadata of a transfer is updated.
transfer.paid handleTransferPaid Occurs whenever a sent transfer is expected to be available in the destination bank account. If the transfer failed, a transfer.failed webhook will additionally be sent at a later time.
transfer.failed handleTransferFailed Occurs whenever Stripe attempts to send a transfer and that transfer fails.

Testing Webhooks

There are situations when you might need to test your webhook controller while you're developing it.

While pushing the changes to a staging server is a good pratice it's not always the fastest way to really test our webhook controller and get the feedback if it worked properly or not since we'll need to wait for Stripe.com to send the webhook event that will hit your server and then you'll need to either check the server logs, Stripe.com Dashboard to see if the webhook was handled successfully.

Below we'll give you two examples on how to test all events or a single event.

Testing a Single Event

Testing single events is a no brainer, you just need to know the Stripe Event Id.

Example
// Fetch the Event payload for the given event id
$payload = Stripe::event('evt_4Y2WyIMZdxy9Pg');

// Instantiate your Webhook Controller
$controller = app('Acme\Controllers\WebhookController');

// Pass in the payload to be handled
$controller->handleWebhook($payload);

Testing Multiple Events

Testing multiple events is similar the single events, you just need to fetch all the events and loop through them, the rest of the logic is very similar.

Example
// Instantiate your Webhook Controller
$controller = app('Acme\Controllers\WebhookController');

// Fetch all the events
$events = Stripe::events()->all();

// Loop through the events
foreach ($events['data'] as $payload)
{
    // Pass in the payload to be handled
    $controller->handleWebhook($payload);
}

You wont find fancy lifestyle graphics and marketing bravado here. Just cold... hard... code...

Code Well, Rock On!
Processing Payment...