Laravel Cashier

Introducción

Laravel Cashier proporciona una expresiva y fluida interfaz para los servicios de facturación de suscripción de Stripe. Gestiona casi todo el código repetitivo de facturación de suscripción que tanto temes escribir. Además de la administración de suscripción básica, Cashier puede gestionar cupones, cambios de suscripción, "cantidades" de suscripción, cancelaciones con periodos de gracia e incluso generar facturas PDF.

Configuración

Composer

First, add the Cashier package to your composer.json file and run the composer update command:

"laravel/cashier": "~5.0" (For Stripe SDK ~2.0, and Stripe APIs on 2015-02-18 version and later)
"laravel/cashier": "~4.0" (For Stripe APIs on 2015-02-18 version and later)
"laravel/cashier": "~3.0" (For Stripe APIs up to and including 2015-02-16 version)

Proveedor de servicios

Next, register the Laravel\Cashier\CashierServiceProvider service provider in your app configuration file.

Migración

Antes de usar Cashier, tienes que agregar algunas columnas a tu base de datos. No te preocupes, puedes usar el comando de Artisan cashier:table para crear la migración con las columnas necesarias. For example, to add the column to the users table run the command: php artisan cashier:table users.

Una vez creada la migración, simplemente ejecuta el comando migrate.

Configuración del modelo

A continuación, agregue el trait Billable y los mutators de fecha adecuados para la definición del modelo:

use Laravel\Cashier\Billable;
use Laravel\Cashier\Contracts\Billable as BillableContract;

class User extends Model implements BillableContract {

    use Billable;

    protected $dates = ['trial_ends_at', 'subscription_ends_at'];

}

Adding the columns to your model's $dates property will instruct Eloquent to return the columns as Carbon / DateTime instances instead of raw strings.

Llave Stripe

Finally, set your Stripe key in your services.php configuration file:

'stripe' => [
    'model'  => 'User',
    'secret' => env('STRIPE_API_SECRET'),
],

Subscriptions

Creating Subscriptions

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

$usuario = Usuario::find(1);

$usuario->subscription('monthly')->create($creditCardToken);

The create method will automatically create the Stripe subscription, as well as update your database with Stripe customer ID and other relevant billing information. Si tu plan tiene una configuración de prueba en Stripe, la fecha de caducidad de la prueba se establecerá automáticamente en el registro del usuario.

In you want to implement trial periods, but are managing the trials entirely within your application instead of defining them within Stripe, you must manually set the trial end date:

$usuario->trial_ends_at = Carbon::now()->addDays(14);

$usuario->save();

Additional User Details

Si deseas especificar datos adicionales del cliente, puedes hacerlo pasándolos como segundo argumento al método create:

$user->subscription('monthly')->create($creditCardToken, [
    'email' => $email, 'description' => 'Our First Customer'
]);

Para más información sobre los campos adicionales soportados por Stripe, revisa la documentación sobre la creación del cliente.

Coupons

Si quieres aplicar un cupón al crear la suscripción, puedes usar el método withCoupon:

$user->subscription('monthly')
     ->withCoupon('code')
     ->create($creditCardToken);

Comprobar el estado de suscripción

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

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

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

public function handle($request, Closure $next)
{
    if ($request->user() && ! $request->user()->subscribed()) {
        // This user is not a paying customer...
        return redirect('billing');
    }

    return $next($request);
}

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

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

The onPlan method may be used to determine if the user is subscribed to a given plan based on its Stripe ID:

if ($user->onPlan('monthly')) {
    //
}

Cancelled Subscription Status

Para determinar si el usuario era un suscriptor activo, pero ha cancelado su suscripción, puedes usar el método cancelled:

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

También puedes determinar su el usuario ha cancelado su suscripción, pero sigue en su "periodo de gracia" hasta que expire la suscripción. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Ten en cuenta que el método subscribed aún devuelve true durante este tiempo.

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

El método everSubscribed puede utilizarse para determinar si el usuario nunca se ha suscrito a un plan en tu aplicación:

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

Changing Plans

After a user is subscribed to your application, they may occasionally want to change to a new subscription plan. To swap a user to a new subscription, use the swap method. For example, we may easily switch a user to the premium subscription:

$user = App\User::find(1);

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

If the user is on trial, the trial period will be maintained. Also, if a "quantity" exists for the subscription, that quantity will also be maintained. When swapping plans, you may also use the prorate method to indicate that the charges should be pro-rated. In addition, you may use the swapAndInvoice method to immediately invoice the user for the plan change:

$user->subscription('premium')
            ->prorate()
            ->swapAndInvoice();

Cantidad de suscripciones

A veces las suscripciones son afectadas por la "cantidad". For example, your application might charge $10 per month per user on an account. Para aumentar o disminuir fácilmente la cantidad de suscripción, usa los métodos increment y decrement:

$usuario = User::find(1);

$usuario->subscription()->increment();

// Suma 5 a la cantidad actual de la suscripción...
$user->subscription()->increment(5);

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

// Resta 5 a la cantidad actual de la suscripción...
$usuario->subscription()->decrement(5);

For more information on subscription quantities, consult the Stripe documentation.

Subscription Taxes

With Cashier, it's easy to provide the tax_percent value sent to Stripe. To specify the tax percentage a user pays on a subscription, implement the getTaxPercent method on your billable model, and return a numeric value between 0 and 100, with no more than 2 decimal places.

public function getTaxPercent() {
    return 20;
}

This enables you to apply a tax rate on a model-by-model basis, which may be helpful for a user base that spans multiple countries.

Cancelling Subscriptions

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

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

When a subscription is cancelled, Cashier will automatically set the subscription_ends_at column in your database. Esta columna se utiliza para saber cuando el método subscribed debe devolver false. Por ejemplo, si un cliente cancela una suscripción el 1 de marzo, pero la suscripción no estaba programada para terminar hasta el 5 de marzo, el método subscribed continuará siendo true hasta el 5 de marzo.

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

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

Resuming Subscriptions

Si un usuario ha cancelado su suscripción y desea reanudarla, usa el método resume:

$usuario->subscription('mensual')->resume($tokenTarjetaCredito);

Si el usuario cancela una suscripción y luego la reanuda antes de que la suscripción haya caducado totalmente, no será cobrado inmediatamente. Instead, their subscription will simply be re-activated, and they will be billed on the original billing cycle.

Handling Stripe Webhooks

Failed Subscriptions

¿Qué pasa si vence la tarjeta de crédito de un cliente? No te preocupes - Cashier incluye el controlador Webhook que puede cancelar fácilmente la suscripción del cliente por ti. Sólo hay que señalar la ruta del controlador:

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

¡Eso es todo! Los pagos fallidos serán capturados y gestionados por el controlador. El controlador cancelará la suscripción cuando Stripe determine que ha fallado (normalmente, después de tres intentos de cobro fallidos). Don't forget: you will need to configure the webhook URI in your Stripe control panel settings.

Since Stripe webhooks need to bypass Laravel's CSRF verification, be sure to list the URI an exception in your VerifyCsrfToken middleware:

protected $except = [
    'stripe/*',
];

Other Webhooks

Si tienes eventos "webhook" de Stripe adicionales que desees gestionar, simplemente hereda el controlador Webhook. Your method names should correspond to Cashier's expected convention, specifically, methods should be prefixed with handle and the "camel case" name of the Stripe webhook you wish to handle. Por ejemplo, si deseas gestionar el webook invoice.payment_succeeded, deberías añadir el método handleInvoicePaymentSucceeded al controlador.

<?php

namespace App\Http\Controller;

use Laravel\Cashier\WebhookController as BaseController;

class WebhookController extends BaseController
{
    /**
     * Handle a stripe webhook.
     *
     * @param  array  $payload
     * @return Response
     */
    public function handleInvoicePaymentSucceeded($payload)
    {
        // Handle The Event
    }
}

Cargos individiales

If you would like to make a "one off" charge against a subscribed customer's credit card, you may use the charge method on a billable model instance. The charge method accepts the amount you would like to charge in the lowest denominator of the currency used by your application. So, for example, the example above will charge 100 cents, or $1.00, against the user's credit card:

$user->charge(100);

El método charge acepta un array como segundo argumento, permitiendo pasar otras opciones a la creación del cargo Stripe:

$user->charge(100, [
    'source' => $token,
    'receipt_email' => $user->email,
]);

El método charge devolverá false si el cargo falla. Esto normalmente indica que el cargo fue denegado:

if ( ! $user->charge(100)) {
    // The charge was denied...
}

Si el cargo se realiza con éxito, la respuesta completa de Stripe será devuelta por el método.

Facturas

You may easily retrieve an array of a billable model's invoices using the invoices method:

$facturas = $usuario->invoices();

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

<table>
    @foreach ($invoices as $invoice)
        <tr>
            <td>{{ $invoice->dateString() }}</td>
            <td>{{ $invoice->dollars() }}</td>
            <td><a href="/user/invoice/{{ $invoice->id }}">Download</a></td>
        </tr>
    @endforeach
</table>

Generating Invoice PDFs

From within a route or controller, use the downloadInvoice method to generate a PDF download of the invoice. This method will automatically generate the proper HTTP response to send the download to the browser:

Route::get('user/invoice/{invoice}', function ($invoiceId) {
    return Auth::user()->downloadInvoice($invoiceId, [
        'vendor'  => 'Your Company',
        'product' => 'Your Product',
    ]);
});