Laravel 5 Stripe example using Laravel Cashier from Scratch

By Hardik Savani | April 11, 2016 | | 19321 Viewer | Category : Laravel


Share this post:

In this tutorial post i show you the example of Stripe subscription example using Laravel Cashier in Laravel 5.1 application. In this example i use Laravel Cashier(Billing) of Laravel 5. Whenever you are work on big project like ecommerce or ERP on that project mostly we need to use subscription plane for your application that way client can earn something. So the laravel include Billing subscription using Stripe. we will make bellow example for pay subscription payment method.

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

Preview:


Step 1: Installation

In this step we will work on laravel installation and laravel package installation from scratch. If you didn't get laravel application then you can run bellow command in your terminal for Laravel app.

Install Laravel

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

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

composer.json

.....

"require": {

.....

"laravel/cashier": "^4.0"

},

......

Composer Update

composer update

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

config/app.php

....

'providers' => [

....,

Laravel\Cashier\CashierServiceProvider::class,

]

.....

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

Migrate DB:

php artisan cashier:table users

php artisan migrate

If you find error like this 'There are no commands defined in the "cashier" namespace' then you can find solution here : How to solve 'There are no commands defined in the "cashier" namespace' in Laravel 5.

Step 2: Stripe Configration

This step is a very important step, because in this step we will create stripe account if you don't have account then create account from here : Stripe. After create this account we will get API key and Public Key from this way: Open Stripe account and Click on right corner "Your Account" and Click on Account Setting. Now you have sevaral option and click on "API Keys". You can find like this:

Ok, now we have 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 open config/services.php file and set configration for stripe like this way:

config

....

'stripe' => [

'model' => 'User',

'secret' => env('STRIPE_SECRET'),

],

....

Step 3: Subscription Payment Example

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

app/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 open app/Http/routes.php and bellow route this way:

app/Http/routes.php

Route::get('/', ['as'=>'home','uses'=>'HomeController@index']);

Route::post('order-post', ['as'=>'order-post','uses'=>'HomeController@orderPost']);

Now If you don't have HomeController then create new HomeController and put bellow code.

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\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 last i created only one view for this example, i don't have create js or css file that way we don't have to make many file for 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>

Now you are ready to run and check.