How to Integrate Stripe Payment gateway in Laravel 9

Throughout this tutorial, you will learn stripe payment gateway integration in laravel application with a real-world example and that too from scratch.

Stripe This laravel stripe payment gateway example tutorial is primarily based on Stripe, It’s a San Francisco based tech company that offers payment acceptance services worldwide.

Stripe majorly provides payment processing software and application programming interfaces exclusively for e-commerce websites not only but also mobile applications.

For the laravel stripe integration tutorial, you have to opt for a stripe developer account to generate a secret and API key.

Furthermore, we will install a stripe/stripe-php composer package in order to bring the laravel stripe payment integration example into action.

Laravel Stripe Payment Gateway Integration Example

In this tutorial, you will see every process from the absolute beginning, project installation, stripe-php library configuration, manifesting routes to make HTTP requests.

Creating a controller for stripe payment integration, creating payment gateway form using Bootstrap CSS framework.

Install Laravel App

Begin with creating a new laravel project with below command:

composer create-project laravel/laravel laravel-stripe-integration-example --prefer-dist

Install Stripe PHP Package

Get inside your project root, then install the stripe-php library:

composer require stripe/stripe-php

Add Stripe Key and Secret in ENV

This step tells you how to add Stripe key and secret in the laravel app. Nonetheless, you have to generate the key and secret at the stripe developer account and use the test account to make transactions.

Open .env configuration file and define the stripe credentials simultaneously:

STRIPE_KEY = stripe_key_xxxxxxxxxxxxxxxxxxx
STRIPE_SECRET = stripe_secret_xxxxxxxxxxxxxxxxxxx

Create Controller

In this step, you have to create and configure a new controller to handle the stripe payment method immaculately.

php artisan make:controller PaymentController

The index() function initialize payment gateway form, while makePayment() function executes the payment process.

Place code in app/Http/Controllers/PaymentController.php:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Stripe;
use Session;

class PaymentController extends Controller
{

    public function index()
    {
        return view('welcome');
    }
  
    public function makePayment(Request $request)
    {
        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
        Stripe\Charge::create ([
                "amount" => 120 * 100,
                "currency" => "inr",
                "source" => $request->stripeToken,
                "description" => "Make payment and chill." 
        ]);
  
        Session::flash('success', 'Payment successfully made.');
          
        return back();
    }
}

Create Routes

Open .env file, import payment controller and define two routes to show and process payments:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaymentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [PaymentController::class, 'index']);
Route::post('/transaction', [PaymentController::class, 'makePayment'])->name('make-payment');

Build Blade View

Create a form that can let you make the payments in laravel with stripe. Add bootstrap CSS and jQuery within the head section, create a bootstrap form with bootstrap form component, add the code in welcome.blade.php:

<!DOCTYPE html>
<html>

<head>
    <title>Laravel Stripe Payment Gateway Integrate 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>

</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-body">

                        @if (Session::has('success'))
                        <div class="alert alert-primary text-center">
                            <p>{{ Session::get('success') }}</p>
                        </div>
                        @endif

                        <form role="form" action="{{ route('make-payment') }}" method="post" class="stripe-payment"
                            data-cc-on-file="false" data-stripe-publishable-key="{{ env('STRIPE_KEY') }}"
                            id="stripe-payment">
                            @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 595'
                                        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">
                                <button class="btn btn-success btn-lg btn-block" type="submit">Pay</button>
                            </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 = $(".stripe-payment");
        $('form.stripe-payment').bind('submit', function (e) {
            var $form = $(".stripe-payment"),
                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()
                }, stripeRes);
            }

        });

        function stripeRes(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>

Here is fake card details making towards test payments.

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

Start the laravel development server:

php artisan serve
http://127.0.0.1:8000

The laravel stripe payment gateway integration tutorials is over, i hope you liked it.