How to use Stripe Payment Gateway with Laravel 8.0

How to use Stripe Payment Gateway with Laravel 8.0


Published at - Sep 21, 2021

Hello, Today I will discuss how to integrate the Stripe payment gateway with our laravel 8.0 project to start accepting payments. As we all know that the stripe is a globally known payment and accepting payment in almost all currencies and countries. for more information please visit stripe's official website - https://stripe.com

 

Stripe payment countries

So to integrate the Stripe payment gateway with laravel 8.0 we need a running laravel 8.0 project, so to create a new project we required a composer. If the composer is not installed please refer to the link

Create Laravel 8.0 project

To install laravel, we need to refer to its official documentation - Laravel Installation  or open your terminal and run the following command and this will create a fresh new laravel project in the chosen directory and you will see output on your terminal as screenshot attached

composer create-project --prefer-dist laravel/laravel stripe-payment-gateway "8.*"

Install Laravel

Install stripe package for laravel

In this step we need to install the stripe-PHP package in the newly created project, to do that first we need to change our directory in the terminal by running cd stripe-payment-gateway/ and then need to run another command given below.

composer require stripe/stripe-php

Stripe PHP

Setup Stripe Payment Gateway Keys

This step required setting up a stripe payment gateway, please follow the following steps to get your keys

  • Create Stripe account

You can create your account by clicking on the following links (Log in if you already have an account) Login or Register.

  • Get your Tokens

You can get tokens by navigating to `Developers -> API Keys` from the sidebar of your dashboard.

  • Setup token in .env

In this step, we need to add the following lines in the .env file 

STRIPE_KEY=pk_test_reFxwbsm9cdCKASdTfxAR
STRIPE_SECRET=sk_test_oQMFWteJiPd4wj4AtgApY

Creating Routes

Next, we need to create routes to interact with the application. to create routes we need to edit routes/web.php the file and need to add the following code.

routes/web.php

<?php

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


Route::get('/', function () {
    return redirect()->route('stripe');
});

Route::GET('stripe', [StripeCtrl::class, 'stripe'])->name('stripe');
Route::POST('stripe', [StripeCtrl::class, 'stripePost'])->name('stripe.post');

Creating Controller

As we have used StripeCtrl in our routes so, we need to create StripeCtrl in our application and copy and paste the following code in that file. to create a controller we need to run php artisan make:controller StripeCtrl and this will create StripeCtrl.php the file in /app/Http/Controllers/ the directory. Next, we need to edit that file

app/Http/Controllers/StripeCtrl.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Session;
use Stripe;

class StripeCtrl extends Controller
{
    //
     /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function stripe()
    {
        return view('stripe');
    }
  
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function stripePost(Request $request)
    {
        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
        Stripe\Charge::create ([
                "amount" => 500 * 100,
                "currency" => "usd",
                "source" => $request->stripeToken,
                "description" => "Test payment from hackeradda.com." 
        ]);
  
        Session::flash('success', 'Payment successful!');
          
        return back();
    }
}

Creating the View

To display and submit the payment request it is required to create a form from where we can generate the payment request.

resources/views/stripe.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 8 - Stripe Payment Gateway Integration - https://hackeradda.com</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style type="text/css">
        .panel-title {
        display: inline;
        font-weight: bold;
        }
        .display-table {
            display: table;
        }
        .display-tr {
            display: table-row;
        }
        .display-td {
            display: table-cell;
            vertical-align: middle;
            width: 61%;
        }
    </style>
</head>
<body>
  
<div class="container">
  
    <h1 class="text-center">Laravel 8 - Stripe Payment Gateway Integration <br/> <a href="https://hackeradda.com">hackeradda.com</a></h1> <hr>
  
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-default credit-card-box">
                <div class="panel-heading" >
                    <div class="row text-center" >
                        <div class="col-xs-12">
                            <h3 class="panel-title" >Payment Details</h3>
                        </div>
                        
                        
                    </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.post') }}" method="post" class="require-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-number' 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='ex. 311' 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 error form-group hide'>
                                <div class='alert-danger alert'>Please correct the errors and try
                                    again.</div>
                            </div>
                        </div>
  
                        <div class="row">
                            <div class="col-xs-12">
                                <button class="btn btn-success btn-block" type="submit">Pay ($500)</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         = $(".require-validation");
  $('form.require-validation').bind('submit', function(e) {
    var $form         = $(".require-validation"),
        inputSelector = ['input[type=email]', 'input[type=password]',
                         'input[type=text]', 'input[type=file]',
                         'textarea'].join(', '),
        $inputs       = $form.find('.required').find(inputSelector),
        $errorMessage = $form.find('div.error'),
        valid         = true;
        $errorMessage.addClass('hide');
 
        $('.has-error').removeClass('has-error');
    $inputs.each(function(i, el) {
      var $input = $(el);
      if ($input.val() === '') {
        $input.parent().addClass('has-error');
        $errorMessage.removeClass('hide');
        e.preventDefault();
      }
    });
  
    if (!$form.data('cc-on-file')) {
      e.preventDefault();
      Stripe.setPublishableKey($form.data('stripe-publishable-key'));
      Stripe.createToken({
        number: $('.card-number').val(),
        cvc: $('.card-cvc').val(),
        exp_month: $('.card-expiry-month').val(),
        exp_year: $('.card-expiry-year').val()
      }, stripeResponseHandler);
    }
  
  });
  
  function stripeResponseHandler(status, response) {
        if (response.error) {
            $('.error')
                .removeClass('hide')
                .find('.alert')
                .text(response.error.message);
        } else {
            // token contains id, last4, and card type
            var token = response['id'];
            // insert the token into the form so it gets submitted to the server
            $form.find('input[type=text]').empty();
            $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
            $form.get(0).submit();
        }
    }
  
});
</script>
</html>

Now run your project by php artisan serve and open localhost:8000 in your browser, you will see the following screen.

Stripe Payment

Test card details

You can use the below card number for test mode and for the expiry date you have entered any date greater than today’s date for CVV number use any 3 digit number it will work and in the zip code box, you have to enter your zip code.

Name on Card – Hackeradda

Card Number - 4242424242424242

CVC - 123

Expiration Month - 12

Expiration Year - 2030

Click here to download the code

Summary

So, We have successfully integrated the Stripe payment gateway in our laravel application with proper validation. It may help you if you are creating an application or learning stripe payment gateway with laravel. I also have How to use Stripe Payments in Node.js? you can check it out.

Thank you for reading. Please feel free to ask any doubt.





About author

Harendra
Harendra Kanojiya

Hello, I am Harendra Kumar Kanojiya - Owner of this website and a Fullstack web developer. I have expertise in full-stack web development using Angular, PHP, Node JS, Python, Laravel, Codeigniter and, Other web technologies. I also love to write blogs on the latest web technology to keep me and others updated. Thank you for reading the articles.



Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile