Razorpay Payment Gateway Integration – Laravel 5.x

By | January 12, 2019

This tutorial is about Razorpay Payment Gateway Integration – Laravel 5.x you will get the step by step with screenshot all the steps to integrate this in your project.

Razorpay site home page - Razorpay Payment Gateway
Razorpay site home page

About Razorpay:- Its offers a fast, affordable and secure way for merchants, schools, eCommerce and other companies to accept payments online. It’s available only for Indian businesses.

Follow the below steps to integrate Razorpay easily on the Laravel website.

Step 1. Install laravel application.

The initial step to begin

Please refer article for this > [How to install Laravel 5.X] for how to install Laravel

Step 2. Create account in Razorpay and generate key and secret

Go to RAZORPAY and signup with basic details step by step.

Run test mode as per the screenshot

Follow the comments which mentioned in red fonts for guideline. - Razorpay Payment Gateway
Follow the comments which mentioned in red fonts for guideline.

Find key and secret from Razorpay account as per below screenshot.

Follow the comments which mentioned in red fonts for guideline.
Follow the comments which mentioned in red fonts for guideline.
This popup will have the information regarding the Razorpay credential. copy it somewhere safe.
This popup will have the information regarding the Razorpay credential. copy it somewhere safe.

Step 3. copy the credentials in .env file

Add these parameters in your env file

You need to add these parameters in your .env file and you will find this file in your root directory.


RAZORPAY_KEY=rzp_test_razor_key
RAZORPAY_SECRET=rzp_test_razor_secret

Note: For security, reason adds those credentials only in .env file.

Step 4. Install Razorpay package via composer

Install the package using composer in terminal

You need to run the below command for the install package in your terminal.
This command will update all the dependency of the package according to your version if you needed any in your project setup.

composer require razorpay/razorpay

Step 5. Create Route and Controller with actions and view

Create MVC files

Now, we are going to run the below command to generate a controller file.

php artisan make:controller RazorpayController

This generated file should look like this below code.

<?php
# Copy the code from below to that controller file located at app/Http/Controllers/RazorpayController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
//use Razorpay\Api\Api;

class RazorpayController extends Controller {

    public function pay() {
        return view('pay');
    }

    public function dopayment(Request $request) {
        //Input items of form
        $input = $request->all();

        // Please check browser console.
        print_r($input);
        exit;
    }

}

Include RajorPay js inside the layout file head section as below. the path will be [resources/views/layouts/app.blade.php]

<head>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<!-- Include whatever JQuery which you are using -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Other js and css scripts -->
</head>

Now we will create a view file at this path [resources/views/] folder with [pay.blade.php] file name.

@extends('layouts.app')

@section('content')

<div id="main-content">
    <div class="container clear">
        <div class="panel-body" style="border: 1px solid #ddd;padding: 10px;background: #eee;width: 30%;">
            <form id="rzp-footer-form" action="{!!route('dopayment')!!}" method="POST" style="width: 100%; text-align: center" >
                @csrf

                <a href="https://amzn.to/2RlZQXk">
                    <img src="https://images-na.ssl-images-amazon.com/images/I/31tPpWGQWzL.jpg" />
                </a>    
                <br/>
                <p><br/>Price: 2,475 INR </p>
                <input type="hidden" name="amount" id="amount" value="2475"/>
                <div class="pay">
                    <button class="razorpay-payment-button btn filled small" id="paybtn" type="button">Pay with Razorpay</button>                        
                </div>
            </form>
            <br/><br/>
            <div id="paymentDetail" style="display: none">
                <center>
                    <div>paymentID: <span id="paymentID"></span></div>
                    <div>paymentDate: <span id="paymentDate"></span></div>
                </center>
            </div>
        </div>

    </div>
</div>

<script>
    $('#rzp-footer-form').submit(function (e) {
        var button = $(this).find('button');
        var parent = $(this);
        button.attr('disabled', 'true').html('Please Wait...');
        $.ajax({
            method: 'get',
            url: this.action,
            data: $(this).serialize(),
            complete: function (r) {
                console.log('complete');
                console.log(r);
            }
        })
        return false;
    })
</script>

<script>
    function padStart(str) {
        return ('0' + str).slice(-2)
    }

    function demoSuccessHandler(transaction) {
        // You can write success code here. If you want to store some data in database.
        $("#paymentDetail").removeAttr('style');
        $('#paymentID').text(transaction.razorpay_payment_id);
        var paymentDate = new Date();
        $('#paymentDate').text(
                padStart(paymentDate.getDate()) + '.' + padStart(paymentDate.getMonth() + 1) + '.' + paymentDate.getFullYear() + ' ' + padStart(paymentDate.getHours()) + ':' + padStart(paymentDate.getMinutes())
                );

        $.ajax({
            method: 'post',
            url: "{!!route('dopayment')!!}",
            data: {
                "_token": "{{ csrf_token() }}",
                "razorpay_payment_id": transaction.razorpay_payment_id
            },
            complete: function (r) {
                console.log('complete');
                console.log(r);
            }
        })
    }
</script>
<script>
    var options = {
        key: "{{ env('RAZORPAY_KEY') }}",
        amount: '247500',
        name: 'CodesCompanion',
        description: 'TVS Keyboard',
        image: 'https://i.imgur.com/n5tjHFD.png',
        handler: demoSuccessHandler
    }
</script>
<script>
    window.r = new Razorpay(options);
    document.getElementById('paybtn').onclick = function () {
        r.open()
    }
</script>

@endsection

Note: Make sure jQuery added in a head section at the layout file.

Now you have to add routes in your routes/web.php file.

// route for to show payment form using get method
Route::get('pay', 'RazorpayController@pay')->name('pay');

// route for make payment request using post method
Route::post('dopayment', 'RazorpayController@dopayment')->name('dopayment');

Final Step 6. Run demo

You just need to serve the laravel now

At this stage, we are almost done with the integration and now we will un Laravel application using below command.

php artisan serve

Now in the browser manually type below URL.

http://127.0.0.1/pay

To run the above URL and it will display the result like the below screenshot.

Follow the steps mentioned in red comment in screenshot for further payment process.

Use below test credentials to run the demo

Card : 4111 1111 1111 1111
Expiry Date : 22/95
CCV  : 123
Card Holder Name : Your Name

You are done now you have successfully integrated Razorpay Payment Gateway Integration – Laravel 5.x.

If you need the whole laravel setup then I have also attached code in Github and attached GitHub link below.

21 thoughts on “Razorpay Payment Gateway Integration – Laravel 5.x

  1. prerna

    yeah you did not tell us how to acces key and how to send request to razorpay server

    Reply
    1. CodesCompanion

      You have to insert access key and secret key in .env file. Regarding sending a request on server ‘RazorPay’ handles itself with js “https://checkout.razorpay.com/v1/checkout.js”. Which you need to set in ‘resources/views/layouts/app.blade.php’ at head section. checkout github demo for more info

      Reply
  2. Damian

    Thank you its working perfect.
    Can anyone give me a heads up on how to store payment id and payment date in the database?
    Need help. I am new in Laravel.

    Reply
  3. anand

    this function is not working i have copied all the files and just loaded the files it says 404 not found

    Reply
    1. CodesCompanion

      Please send me your contact details in email so we can check your code and help you out.

      Reply
  4. n95 respirator

    I am very much grateful for your efforts put on this article.
    This article is updated very informative and translucent. Can I expect you may post this type of another article in near future?

    King regards,
    Abildgaard Duke

    Reply
  5. blog

    Just want to say your article is as amazing. The clearness
    in your post is simply cool and i could assume you’re an expert on this subject.
    Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post.
    Thanks a million and please keep up the enjoyable work.

    Reply
  6. Louvenia Sellers

    First time visiting your website, I really like your site!

    Reply
  7. Pingback: Pei payment gateway integration with PHP. pei.is - iceland.

Leave a Reply

Your email address will not be published. Required fields are marked *