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.

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 below steps to integrate Razorpay easily in 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 https://razorpay.com 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.

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

Follow the comments which mentioned in red fonts for guideline.
This popup will have the information regarding 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 you .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 credential only in .env file.

Step 4. Install Razorpay package via composer

Install the package using composer in terminal

You need to run below command for 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 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 layout file head section as below. 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 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 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 integrate Razorpay Payment Gateway Integration – Laravel 5.x.

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

4 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

Leave a Reply

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