[Laravel5.2 documentation] service-subscription payment implementation: LaravelCashier

Source: Internet
Author: User
Tags webhook
[Laravel5.2 documentation] service-subscription payment implementation: LaravelCashier 1. Introduction

LaravelCashier provides an elegant and smooth interface for implementing the subscription payment service through Stripe. It encapsulates almost all the sample subscription and payment code you are afraid to write. In addition to basic subscription management, Cashier also supports coupon processing, subscription upgrade/replacement, subscription "quantity", Grace period cancellation, and even PDF invoice generation.

1.1 Installation & Configuration

Composer

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

"laravel/cashier": "~6.0"

Service provider

Next, register the service provider Laravel \ Cashier \ CashierServiceProvider in the config/app. php configuration file.

Migration

Before using Cashier, we need to prepare the database. We need to add a field to the users table, and create a new subscriptions table to process all user subscriptions:

Schema::table('users', function ($table) {    $table->string('stripe_id')->nullable();    $table->string('card_brand')->nullable();    $table->string('card_last_four')->nullable();});Schema::create('subscriptions', function ($table) {    $table->increments('id');    $table->integer('user_id');    $table->string('name');    $table->string('stripe_id');    $table->string('stripe_plan');    $table->integer('quantity');    $table->timestamp('trial_ends_at')->nullable();    $table->timestamp('ends_at')->nullable();    $table->timestamps();});

After the migration is created, simply run the migrate command and the modification will be updated to the database.

Set model

Next, add Billabletrait to the User model class:

use Laravel\Cashier\Billable;class User extends Authenticatable{    use Billable;}

Stripe key

Finally, set the Stripe key in the config/services. php configuration file:

'stripe' => [    'model'  => 'User',    'secret' => env('STRIPE_API_SECRET'),],
2. subscribe to 2.1 create a subscription

To create a subscription, you must first obtain an instance of the billing model, typically an App \ User instance. After obtaining the model instance, you can use the newsubscribe method to create the model subscription:

$user = User::find(1);$user->newSubscription('main', 'monthly')->create($creditCardToken);

The first parameter passed to the newsubscribe method is the subscription name. if the application only has one subscription, it can be called main or primary. The second parameter is used to specify the Stripe plan subscribed by the user, this value corresponds to the plan id in Stripe.

The create method automatically creates this Stripe subscription and updates the client ID (stripe_id in the users table) and other related billing information of Stripe in the database. If your subscription plan has a trial period, the end time of the trial period will be automatically set to the database field.

Additional user information

If you want to specify additional customer information, you can pass it as the second parameter to the create method:

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

For more information about the fields supported by Stripe, see the Stripe documentation on creating consumers.

Coupon

If you want to use coupons when creating a subscription, you can use the withCoupon method:

$user->newSubscription('main', 'monthly')     ->withCoupon('code')     ->create($creditCardToken);
2.2 check subscription status

After a user subscribes to your application, you can use a variety of convenient methods to check the subscription status. First, if the user has a valid subscription, the subscribed method returns true, even if the subscription is due to the trial period:

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

The subscribed method can also be used for routing middleware. based on the user subscription status, you can filter the access to routes and controllers:

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

If you want to determine whether a user is still in the trial period, you can use the onTrial method. this method is useful for displaying warning information for users still in the trial period:

if ($user->->subscription('main')->onTrial()) {    //}

The onPlan method can be used to determine whether a user subscribes to a given plan based on the Stripe ID:

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

Canceled subscription status

You can use the canceled method to determine whether a user has been a valid subscriber but has canceled the subscription:

if ($user->subscription('main')->cancelled()) {    //}

You can also determine whether the user has canceled the subscription, but is still in the "grace period" until it is completely invalid. For example, if a user cancels a subscription that is valid until January 1, the user is in the "grace period" until January 1. Note that the subscribed method returns true during this period.

if ($user->subscription('main')->onGracePeriod()) {    //}
2.3 modify subscription

After a user subscribes to an application and occasionally wants to change to a new subscription plan, he must switch the user to a new subscription and use the swap method. For example, we can easily switch users to premium subscription:

$user = App\User::find(1);$user->subscription('main')->swap('stripe-plan-id');

If the user is in trial use, the trial period will be maintained. In addition, if the subscription quantity exists, the quantity can also be maintained. After switching the subscription plan,

You can use the invoice method to invoice users immediately:

$user->subscription('main')->swap('stripe-plan-id');$user->invoice();
2.4 subscription quantity

Sometimes the number of subscriptions is also affected. for example, you need to pay $10 per month for each account in the application. to simply increase or decrease the number of subscriptions, use the incrementQuantity and decrementQuantity methods:

$user = User::find(1);$user->subscription('main')->incrementQuantity();// Add five to the subscription's current quantity...$user->subscription('main')->incrementQuantity(5);$user->subscription('main')->decrementQuantity();// Subtract five to the subscription's current quantity...$user->subscription('main')->decrementQuantity(5);

You can also use the updateQuantity method to specify the quantity:

$user->subscription('main')->updateQuantity(10);

For more information about the number of subscriptions, see the relevant Stripe documentation.

2.5 subscription tax

In Cashier, it is easy to provide the tax_percent value and send it to Stripe. To specify the tax rate of the user's subscription, implement the getTaxPercent method of the billing model, and return a value between 0 and 100, no more than two decimal places:

public function getTaxPercent() {    return 20;}

This allows you to use tax rates based on the model and is useful for users across different countries.

2.6 cancel subscription

To cancel the subscription, you can call the cancel method on the user subscription:

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

When the subscription is canceled, Cashier automatically sets the subscription_ends_at field in the database. This field is used to understand when the subscribed method returns false. For example, if the customer cancels the subscription in July but the subscription does not end until July 15, The subscribed method returns true until July 15.

You can use the onGracePeriod method to determine whether the user has canceled the subscription but is still in the "grace period ":

if ($user->subscription('main')->onGracePeriod()) {    //}
2.7 resume subscription

If you have canceled the subscription but want to resume the subscription, you can use the resume method, provided that the user must be within the grace period:

$user->subscription('main')->resume();

If a user cancels a subscription and resumes the subscription before the subscription expires, the user will not pay the bill immediately. Instead, their subscription will only be reactivated, and return to the normal payment cycle.

3. process StripeWebhook3.1 Subscription failure handling

What if the customer's credit card is invalid? Don't worry -- Cashier comes with a Webhook controller, which can easily cancel the customer subscription for you. You only need to define the following controller route:

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

That's it! The failed payment will be captured and processed by the controller. When Stripe determines that the subscription has failed (three failed attempts under normal circumstances), the controller will cancel the customer's subscription. Don't forget: you need to configure the corresponding webhook URI in the Stripe control panel settings, otherwise it will not work properly.

Because Stripe webhooks needs to pass Laravel's CSRF verification, we place this URI in the VerifyCsrfToken middleware exclusion list:

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

If you want to handle Stripe webhook events, simply inherit the Webhook controller. your method name should be consistent with the convention expected by Cashier, in particular, the method should start with "handle" and be named by the camper name. For example, if you want to process invoice. payment_succeededwebhook, you should add the handleInvoicePaymentSucceeded method to the controller:

      4. one-time payment     

If you want to use the subscriber's credit card to settle the bill at one time, you can use the charge method on the billing model instance to receive the payment amount (the value corresponding to the minimum unit of the currency used) as a parameter, for example, the following example uses a credit card to pay 100 cents or $1:

$user->charge(100);

The charge method receives an array as the second parameter, allowing you to pass any underlying Stripe Bill creation parameters you want to pass:

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

If the payment fails, the charge method returns false, which usually indicates that the payment is denied:

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

If the payment is successful, this method returns a complete Stripe response.

5. invoice

You can use the invoices method to easily obtain the invoice array of the billing model:

$invoices = $user->invoices();

When listing customer invoices, you can use the invoice auxiliary function to display related invoice information. For example, you may want to list each invoice in the table so that users can download them easily:

  
  
   
       @foreach ($invoices as $invoice)        
   
    @endforeach 
   
{{ $invoice->dateString() }} {{ $invoice->dollars() }} id }}">Download
Generate PDF invoice

Install the PHP library dompdf before generating a PDF ticket:

composer require dompdf/dompdf

In the routing or controller, use the downloadInvoice method to generate a PDF download of the invoice. this method will automatically generate the corresponding HTTP response and send it to the browser:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.