Laravel Stripe example by using Laravel Cashier from Scratch

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you a example of Stripe subscription example by using Laravel Cashier in Laravel application.So now in this example i will use Laravel Cashier(Billing) on Laravel application. Whenever we are working on big any project as like ecommerce or ERP on that project we mostly need to use subscription plane for our application on that way client can earn something. So now in the laravel include Billing subscription by using Stripe. So now we will make the bellow example for pay subscription payment method.

So now in bellow preview we can see i added input field of form. For one for select plane, second for add the credit card number or dabit card number, third for CVC code, fourth and sixth for the Expire month and year. Now It is a very simple and very easy to use. So we will create the following example by few following step.

Step 1: Installation

Now in this step we will work on laravel so need to installation and also need to package installation from scratch. So If you didn’t have laravel application then you can run the bellow command in your terminal for new Laravel application.

Install Laravel
composer create-project laravel/laravel blog "5.1.*"

Ok good, now we are ready to use the laravel/cashier package for get Stripe API services. So, let’s add the bellow line in your composer.json and then need to composer update.

composer.json

.....
"require": {

        .....

        "laravel/cashier": "^4.0"

    },

    ......

Composer Update

composer update

Now At last we have to add the Service Provider of laravel Cashier, need to open config/app.php and then need to add bellow line this way.

config/app.php

....
'providers' => [
	....,
	Laravel\Cashier\CashierServiceProvider::class,
]
	.....

So now we are ready to add the field in databse users table. so we have to just run the bellow command and it will create by automatically by migration for database field.

Migrate DB:

php artisan cashier:table usersphp artisan migrate
Step 2: Stripe Configration

Now in this step is a very important for step, because in this step we will create a stripe account if we don’t have account then need to create account from here : Stripe. After the create this account we will get a API key and Public Key from this way: need to Open Stripe account and Click on right corner “Your Account” and Click on Account Setting. Now hope we have several option and click on “API Keys”.

Ok, now we need to cope “Test secret Key” and “Test publishable Key” and paste in .env file.

.env

.....
STRIPE_SECRET=Paste Test secret Key
STRIPE_PUBLISHABLE_SECRET=Paste Test publishable Key

Now we will open config/services.php file and need to set configuration for stripe like this way:

config

....
'stripe' => [
        'model'  => 'User',
        'secret' => env('STRIPE_SECRET'),
    ],
....
Step 3: Subscription Payment Example

Now in this step we are ready to create an example of Stripe Subscription Payment by using Laravel Cashier. so at first need to open User Model and add Billable, BillableContract class this way:

app/Models/User.php

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'];
}

Ok, now need open app/Http/routes.php and bellow route this way:

app/Http/routes.php
Route::get('/', ['as'=>'home','uses'=>'[email protected]']);
Route::post('order-post', ['as'=>'order-post','uses'=>'[email protected]']);

Now If we don’t have HomeController then need to create new HomeController and put bellow code.

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Exception;
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {        
        return view('layouts.app');
    }
    public function orderPost(Request $request)
    {
            $user = User::find(3);
            $input = $request->all();
            $token = $input['stripeToken'];
            
            try {
                $user->subscription($input['plane'])->create($token,[
                        'email' => $user->email
                    ]);
                return back()->with('success','Subscription is completed.');
            } catch (Exception $e) {
                return back()->with('success',$e->getMessage());
            }
            
    }
}

Ok, now we are in last i will create only one view for this example. Now i will create new view in bellow path with bellow code.

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <!-- Styles -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
     <style>
        .alert.parsley {
            margin-top: 5px;
            margin-bottom: 0px;
            padding: 10px 15px 10px 15px;
        }
        .check .alert {
            margin-top: 20px;
        }
        .credit-card-box .panel-title {
            display: inline;
            font-weight: bold;
        }
        .credit-card-box .display-td {
            display: table-cell;
            vertical-align: middle;
            width: 100%;
        }
        .credit-card-box .display-tr {
            display: table-row;
        }
    </style>
    <!-- JavaScripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body id="app-layout">
<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <h1 class="text-primary text-center">
          <strong>Laravel 5 With Stripe Subscription Demo</strong>
        </h1>
    </div>
</div>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <div class="panel panel-default credit-card-box">
        <div class="panel-heading display-table" >
            <div class="row display-tr" >
                <h3 class="panel-title display-td" >Payment Details Form</h3>
                <div class="display-td" >                            
                    <img class="img-responsive pull-right" src="http://i76.imgup.net/accepted_c22e0.png">
                </div>
            </div>                    
        </div>
        <div class="panel-body">
            <div class="col-md-12">
              {!! Form::open(['url' => route('order-post'), 'data-parsley-validate', 'id' => 'payment-form']) !!}
                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                  <button type="button" class="close" data-dismiss="alert">×</button> 
                        <strong>{{ $message }}</strong>
                </div>
                @endif
                <div class="form-group" id="product-group">
                    {!! Form::label('plane', 'Select Plan:') !!}
                    {!! Form::select('plane', ['google' => 'Google ($10)', 'game' => 'Game ($20)', 'movie' => 'Movie ($15)'], 'Book', [
                        'class'                       => 'form-control',
                        'required'                    => 'required',
                        'data-parsley-class-handler'  => '#product-group'
                        ]) !!}
                </div>
                <div class="form-group" id="cc-group">
                    {!! Form::label(null, 'Credit card number:') !!}
                    {!! Form::text(null, null, [
                        'class'                         => 'form-control',
                        'required'                      => 'required',
                        'data-stripe'                   => 'number',
                        'data-parsley-type'             => 'number',
                        'maxlength'                     => '16',
                        'data-parsley-trigger'          => 'change focusout',
                        'data-parsley-class-handler'    => '#cc-group'
                        ]) !!}
                </div>
                <div class="form-group" id="ccv-group">
                    {!! Form::label(null, 'CVC (3 or 4 digit number):') !!}
                    {!! Form::text(null, null, [
                        'class'                         => 'form-control',
                        'required'                      => 'required',
                        'data-stripe'                   => 'cvc',
                        'data-parsley-type'             => 'number',
                        'data-parsley-trigger'          => 'change focusout',
                        'maxlength'                     => '4',
                        'data-parsley-class-handler'    => '#ccv-group'
                        ]) !!}
                </div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group" id="exp-m-group">
                        {!! Form::label(null, 'Ex. Month') !!}
                        {!! Form::selectMonth(null, null, [
                            'class'                 => 'form-control',
                            'required'              => 'required',
                            'data-stripe'           => 'exp-month'
                        ], '%m') !!}
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group" id="exp-y-group">
                        {!! Form::label(null, 'Ex. Year') !!}
                        {!! Form::selectYear(null, date('Y'), date('Y') + 10, null, [
                            'class'             => 'form-control',
                            'required'          => 'required',
                            'data-stripe'       => 'exp-year'
                            ]) !!}
                    </div>
                  </div>
                </div>
                  <div class="form-group">
                      {!! Form::submit('Place order!', ['class' => 'btn btn-lg btn-block btn-primary btn-order', 'id' => 'submitBtn', 'style' => 'margin-bottom: 10px;']) !!}
                  </div>
                  <div class="row">
                    <div class="col-md-12">
                        <span class="payment-errors" style="color: red;margin-top:10px;"></span>
                    </div>
                  </div>
              {!! Form::close() !!}
            </div>
        </div>
    </div>
    
  </div>
</div>
    
    <!-- PARSLEY -->
    <script>
        window.ParsleyConfig = {
            errorsWrapper: '<div></div>',
            errorTemplate: '<div class="alert alert-danger parsley" role="alert"></div>',
            errorClass: 'has-error',
            successClass: 'has-success'
        };
    </script>
    
    <script src="http://parsleyjs.org/dist/parsley.js"></script>
    
    <script type="text/javascript" src="https://js.stripe.com/v2/"></script>
    <script>
        Stripe.setPublishableKey("<?php echo env('STRIPE_PUBLISHABLE_SECRET') ?>");
        jQuery(function($) {
            $('#payment-form').submit(function(event) {
                var $form = $(this);
                $form.parsley().subscribe('parsley:form:validate', function(formInstance) {
                    formInstance.submitEvent.preventDefault();
                    alert();
                    return false;
                });
                $form.find('#submitBtn').prop('disabled', true);
                Stripe.card.createToken($form, stripeResponseHandler);
                return false;
            });
        });
        function stripeResponseHandler(status, response) {
            var $form = $('#payment-form');
            if (response.error) {
                $form.find('.payment-errors').text(response.error.message);
                $form.find('.payment-errors').addClass('alert alert-danger');
                $form.find('#submitBtn').prop('disabled', false);
                $('#submitBtn').button('reset');
            } else {
                var token = response.id;
                $form.append($('<input type="hidden" name="stripeToken" />').val(token));
                $form.get(0).submit();
            }
        };
    </script>
</body>
</html>

Read Also : How to convert Object into Array in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →