Raviya Technical
Published in

Raviya Technical

Laravel with Packages | Laravel 5 Stripe example using Laravel Cashier from Scratch

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 working on a big project like eCommerce or ERP on that project mostly we need to use a subscription plan for your application that way client can earn something. So the laravel includes a Billing subscription using Stripe. we will make the below example for the pay subscription payment method.

In the below preview you can see I added 5 input fields to the form. one for the select plane, second for add credit card number or debit card number, third for CVC code, fourth and sixth for Expire month and year. It is very simple and very easy to use. we will create the following example with a few following steps.

Step 1: Installation

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

Install Laravel

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

Ok, now we are ready to use laravel/cashier package forget the Stripe API services. So, let’s add the below 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 the bellow line this way.

config/app.php

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

Now we are ready to add a field to the database user table. so we have to just run the below command and it will create automatically migration for the database field.

Migrate DB:

php artisan cashier:table usersphp artisan migrate

Step 2: Stripe Configuration

This step is a very important step because in this step we will create a stripe account if you don’t have an account then create an account from here: Stripe. After creating this account we will get the API key and Public Key this way: Open Stripe account Click on the right corner “Your Account” and Click on Account Setting. Now you have several options and click on “API Keys”. You can find it like this:

Ok, now we have to cope with “Test secret Key” and “Test publishable Key” and paste them into the .env file.

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

Now open the config/services.php file and set the configuration for stripe this way:

config

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

Step 3: Subscription Payment Example

In this step, we are ready to create an 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 below 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 a new HomeController and put the below 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 to create a js or CSS file that way we don’t have to make many files for creating a new view in the below path with the below 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.

--

--

--

PHP, Laravel And Flutter Development

Recommended from Medium

Organizational Refactoring: Making Change to Our Teams in a Human Way

Bee2 Finance FAQ

Programming AWS IAM using AWS python SDK boto3 — Part 3

Real-world Room migration strategies

4 Tips For Computer Science Freshmen

3 pieces of advice for someone who’s just beginning their journey with software development!

AppSheet Tutorial Series: Create an Expense Tracking App

Why there is a need of Kubernetes and it’s use cases

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Raviya Technical

Raviya Technical

raviyatechnical.blogspot.com

More from Medium

Laravel REST API | Laravel Sanctum SPA API Authentication Example

Laravel with Packages | Laravel 6 CORS Middleware Tutorial

Laravel Package Development | Developing Laravel Packages with Local Composer Dependencies

Laravel Basic | How to send mail using queue in Laravel?