We'll examine how to establish a laravel subscription system utilising laravel cashier in this Laravel laravel 8 stripe subscription tutorial. In this laravel 8 cashier tutorial, I'll walk you through the steps so you can better understand and replicate the code for your project.
You may be aware that Laravel provides us with their laravel cashier package, which allows us to conveniently handle the subscription system in Laravel. To make this laravel cashier stripe checkout page and laravel cashier subscription system, I'll utilise a Stripe payment gateway with Laravel cashier.
Table of Content
- Download Laravel
- Make Auth
- Install Cashier Package
- Update User Model
- Create Stripe Account to Get Stripe API Key and SECRET
- Add Route
- Create Controller
- Create View File
If we want to build a web application like Laracats or any other type of online application that requires a subscription system, we can utilise Laravel cashier to do so. We'll use Stripe and Laravel Billing subscriptions.
Step 1 : Download Laravel
We'll need a new Laravel application to make this laravel 8 stripe subscription tutorial. So run the following command to get it:
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Make Auth
In Laravel, we need users to create a subscription plan. As a result, we require authentication. To create an authentication system in Laravel, use the command below.
composer require laravel/ui
php artisan ui vue --auth
We'll make advantage of the Laravel collective form. As a result, run the following command to install it:
composer require laravelcollective/html
Step 3 : Install Cashier Package
You'll need the official Laravel cashier package for this stage. Using the command below, you can install the cashier package. So, open a terminal and type the following command:
composer require laravel/cashier
Then you should run.
php artisan migrate
You can publish them using the vendor: if we need to overwrite the migrations that come with the Cashier package. Artisan command: publish
php artisan vendor:publish --tag="cashier-migrations"
Step 4 : Update User Model
Before implementing Cashier, we must first add the Billable trait to the User model, as seen below.
app\Models\User.php
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Billable;
}
Cashier now thinks your Billable model is the App\Models\User
class that comes with Laravel once you add that Billable trait to the User model. You can modify this by specifying a different model in your.env file, such as:
.env
CASHIER_MODEL=App\Models\User
Step 5 : Create Stripe Account to Get Stripe API Key and SECRET
If you don't already have a Stripe account, you'll need one to receive a Stripe API key and secret key at this step. So, open your browser and go to the Stripe official website to obtain your client secret code.
.env
STRIPE_KEY=pk_test*****
STRIPE_SECRET=sk_test******
You'll need to construct all of your plans for your subscription plan system after that. As a result, make a comprehensive plan.
Step 6 : Add Route
We'll add a route to the route file in this stage, so open the web.php
file and add two routes: the first is form, and the second is store stripe subscription.
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SubscriptionController;
Route::get('/subscription/create', ['as'=>'home','uses'=>'SubscriptionController@index'])->name('subscription.create');
Route::post('order-post', ['as'=>'order-post','uses'=>'SubscriptionController@orderPost']);
Step 7 : Create Controller
Now we must develop a SubscriptionController
, which must be used above both methods.
app/Http/Controllers/SubscriptionController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Use App\Models\User;
use Stripe;
use Session;
use Exception;
class SubscriptionController extends Controller
{
public function index()
{
return view('subscription.create');
}
public function orderPost(Request $request)
{
$user = auth()->user();
$input = $request->all();
$token = $request->stripeToken;
$paymentMethod = $request->paymentMethod;
try {
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
if (is_null($user->stripe_id)) {
$stripeCustomer = $user->createAsStripeCustomer();
}
\Stripe\Customer::createSource(
$user->stripe_id,
['source' => $token]
);
$user->newSubscription('test',$input['plane'])
->create($paymentMethod, [
'email' => $user->email,
]);
return back()->with('success','Subscription is completed.');
} catch (Exception $e) {
return back()->with('success',$e->getMessage());
}
}
}
Step 8: Create View File
Last but not least, you can make a view blade file by first making a subscription directory and then making the blade file in the subscription directory.
resources/views/subscription/create.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>
<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>
<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 8 Stripe Subscription Example - CodeSolutionStuff</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" >
<strong>Laravel 8 Stripe Subscription Example - CodeSolutionStuff</strong>
</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', ['laravel' => 'Laravel ($10)', 'vue' => 'Vue ($20)', 'react' => 'React ($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>
<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>
Everything is ready to go. You can try it out and let me know if there are any problems.
I hope you will like the content and it will help you to learn Laravel 8 Stripe Subscription Tutorial Using Cashier Example
If you like this content, do share.