Integrate Stripe Payment Gateway in Laravel 10 Application
I believe at the end of this Stripe payment gateway tutorial, i will be able to explain all the Nitty-Gritty adequately.
Stipe is a noted and authentic payment gateway used for making online payments throughout the world. Managing things in Stripe is easy; it’s user-centric dashboard allows you to handle situations pretty quickly.
It doesn’t make you are solicitous when it comes to handling transactions and payment. It also gives you access for the testing account and prevents real payment from deteriorating.
However, there are many other payment gateways available. On one i made the tutorial earlier, How to Integrate Paypal Payment Gateway in Laravel.
I reckon on this stripe payment gateway, without wasting much time, let’s start this tutorial.
Table of Contents
Laravel Stripe Payment Gateway Example
Please follow all the processes respectively to know the nitty-gritty of how to integrate Stripe Payment Gateway in the Laravel application.
Evoke Laravel Application
In general, we start by installing a fresh new laravel application. You need to execute the below command to manifest the new laravel application.
composer create-project laravel/laravel laravel-stripe-example --prefer-dist
Afterward, move inside the newly installed application.
cd laravel-stripe-example
Establish stripe-php Package
This is a required step of this tutorial, and you must have composer installed on your development machine. We have to install the stripe-php plugin for making easy payments in laravel.
composer require stripe/stripe-php
Configure Stripe Public & Secret API Keys
To make the connection between laravel and Stripe payment gateway,
we have to define the Stripe Publishable and Secret key inside the .env
file. As we register the Stripe API keys in the env file, consensus will be made between them.
- Go to the Stripe website, register, and create your development account.
- Get the Public and Secret API key from your account.
- To restrain from making the real transaction, operate with a test account.
STRIPE_KEY=pk_test_51H7bbSE2RcKvfXD4DZhuhig
STRIPE_SECRET=sk_test_51H7bbSE2RcKvfXD4zKzr
If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.
UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
Configure Routes
We have to create the two routes that simultaneously handle GET and POST requests in the Laravel Stripe controller for managing Stripe Payments.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StripeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
Route::get('/stripe-payment', [StripeController::class, 'handleGet']);
Route::post('/stripe-payment', [StripeController::class, 'handlePost'])->name('stripe.payment');
Set Up Stripe Payment Controller
Run command to create a StripeController, in here we will write the entire memoir for handling the payments.
php artisan make:controller StripeController
Insert the following code in app/Http/Controllers/StripeController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stripe;
use Session;
class StripeController extends Controller
{
/**
* payment view
*/
public function handleGet()
{
return view('home');
}
/**
* handling payment with POST
*/
public function handlePost(Request $request)
{
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
Stripe\Charge::create ([
"amount" => 100 * 150,
"currency" => "inr",
"source" => $request->stripeToken,
"description" => "Making test payment."
]);
Session::flash('success', 'Payment has been successfully processed.');
return back();
}
}
Create Stipe Form and Validation
In this final step, we will be creating the form that accepts the card details along with the some validation rules to validate the card information.
Create a home.blade.php file, in here insert the following code altogether.
<!DOCTYPE html>
<html>
<head>
<title>Laravel 7 - Integrate Stripe Payment Gateway Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<style type="text/css">
.container {
margin-top: 40px;
}
.panel-heading {
display: inline;
font-weight: bold;
}
.flex-table {
display: table;
}
.display-tr {
display: table-row;
}
.display-td {
display: table-cell;
vertical-align: middle;
width: 55%;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row text-center">
<h3 class="panel-heading">Payment Details</h3>
</div>
</div>
<div class="panel-body">
@if (Session::has('success'))
<div class="alert alert-success text-center">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('success') }}</p>
</div>
@endif
<form role="form" action="{{ route('stripe.payment') }}" method="post" class="validation"
data-cc-on-file="false"
data-stripe-publishable-key="{{ env('STRIPE_KEY') }}"
id="payment-form">
@csrf
<div class='form-row row'>
<div class='col-xs-12 form-group required'>
<label class='control-label'>Name on Card</label> <input
class='form-control' size='4' type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-xs-12 form-group card required'>
<label class='control-label'>Card Number</label> <input
autocomplete='off' class='form-control card-num' size='20'
type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-xs-12 col-md-4 form-group cvc required'>
<label class='control-label'>CVC</label>
<input autocomplete='off' class='form-control card-cvc' placeholder='e.g 415' size='4'
type='text'>
</div>
<div class='col-xs-12 col-md-4 form-group expiration required'>
<label class='control-label'>Expiration Month</label> <input
class='form-control card-expiry-month' placeholder='MM' size='2'
type='text'>
</div>
<div class='col-xs-12 col-md-4 form-group expiration required'>
<label class='control-label'>Expiration Year</label> <input
class='form-control card-expiry-year' placeholder='YYYY' size='4'
type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-md-12 hide error form-group'>
<div class='alert-danger alert'>Fix the errors before you begin.</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-danger btn-lg btn-block" type="submit">Pay Now (₹100)</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
$(function() {
var $form = $(".validation");
$('form.validation').bind('submit', function(e) {
var $form = $(".validation"),
inputVal = ['input[type=email]', 'input[type=password]',
'input[type=text]', 'input[type=file]',
'textarea'].join(', '),
$inputs = $form.find('.required').find(inputVal),
$errorStatus = $form.find('div.error'),
valid = true;
$errorStatus.addClass('hide');
$('.has-error').removeClass('has-error');
$inputs.each(function(i, el) {
var $input = $(el);
if ($input.val() === '') {
$input.parent().addClass('has-error');
$errorStatus.removeClass('hide');
e.preventDefault();
}
});
if (!$form.data('cc-on-file')) {
e.preventDefault();
Stripe.setPublishableKey($form.data('stripe-publishable-key'));
Stripe.createToken({
number: $('.card-num').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeHandleResponse);
}
});
function stripeHandleResponse(status, response) {
if (response.error) {
$('.error')
.removeClass('hide')
.find('.alert')
.text(response.error.message);
} else {
var token = response['id'];
$form.find('input[type=text]').empty();
$form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
$form.get(0).submit();
}
}
});
</script>
</html>
To run the application you have to evoke the following command:
php artisan serve
Once the application invoked, you can test the app with the following URL:
http://127.0.0.1:8000/stripe-payment
You can use the following card details for testing purpose, if all this is not enough then you can test more card numbers and other information to make sure your integration works as planned.
Number | Brand | CVC | Date |
---|---|---|---|
4242424242424242 | Visa | Any 3 digits | Any future date |
4000056655665556 | Visa (debit) | Any 3 digits | Any future date |
5555555555554444 | Mastercard | Any 3 digits | Any future date |
2223003122003222 | Mastercard (2-series) | Any 3 digits | Any future date |
5200828282828210 | Mastercard (debit) | Any 3 digits | Any future date |
5105105105105100 | Mastercard (prepaid) | Any 3 digits | Any future date |
378282246310005 | American Express | Any 4 digits | Any future date |
371449635398431 | American Express | Any 4 digits | Any future date |
6011111111111117 | Discover | Any 3 digits | Any future date |
6011000990139424 | Discover | Any 3 digits | Any future date |
3056930009020004 | Diners Club | Any 3 digits | Any future date |
36227206271667 | Diners Club (14 digit card) | Any 3 digits | Any future date |
3566002020360505 | JCB | Any 3 digits | Any future date |
6200000000000005 | UnionPay | Any 3 digits | Any future date |
The Final Words
Eventually, without any recklessness, we have finished this basic tutorial of Laravel and Stripe Payment Gateway.
In this tutorial, we have learned things on three basic levels, creating a laravel app from starting, registering stripe public and secret API key in laravel and, integrating stripe payment gateway in laravel application.
Theoretically, we unfolded only a few chapters of payment gateway integration in this tutorial. However, there are many things yet to be done. But one thing is for sure you are good to go with this, especially if you are a beginner.
If you liked my intensive efforts, then please do share this tutorial with others as well, I would be grateful to you. Have a good day. Keep coding.