Simplified Laravel 9 Instamojo Integration Tutorial for Beginners

Last Updated: 02 Feb, 2023

In this simple tutorial, you will be learning the easy and comprehensive way of integrating Instamojo Payment Gateway inside Laravel 9 application. We will be using available REST APIs that have been provided by Instamojo.

Instamojo is a secured, flexible and reliable online payment gateway that may be best suitable for your eCommerce business. It offers flexible, safe and fast payment options that allow you to collect online payments very easily anytime anywhere on the internet. It offers the following featues:

  • Easily create and get payment links
  • Easily embed pay button on your website
  • Simple payment gateway integration
  • Offers 100+ online payment modes
  • Offers smooth online payments process

Easy way to integrate Instamojo Payment Gateway inside Laravel 9 app

Hi friends, I am going to share my experience with integratiion of Instamojo Payment Gateway in laravel application. You just follow the below given steps to get this done.

Step 1: Install a New Laravel 9 Application

At first, we will install a very fresh laravel 9 application. In your system, open your terminal and run the following command:

composer create-project laravel/laravel l9instamojopg

Step 2: Update Database Credentials inside .env file

Next, you have to update your database credentials in .env file as follows:

DB_DATABASE=l9instamojopg
DB_USERNAME={dbusername}
DB_PASSWORD={dbpassword}

Step 3: Configure Instamojo Credentials

In this step, we have to setup Instamojo ApiKey and ApiAuthToken inside .env file. Visit Instamojo official website (https://www.instamojo.com/), login to your account and get these API Keys. If you don't have Instamojo account, it is very easy to create a one. Once you have signed up to Instamojo, you can get API_KEY and AUTH_TOKEN from Instamojo dashboard and configure it as follows:

IMPG_API_KEY=test_ku34d3a8dg3445drdc7a5g4f067w2
IMPG_AUTH_TOKEN=test_gd32955ddt432a2yt34df3kj56d
IMPG_ENDPOINT=https://test.instamojo.com/api/1.1/

Next, open app/config/services.php file and add below provided code inside it:

'instamojo' => [
    'api_key' => env('IMPG_API_KEY'),
    'auth_token' => env('IMPG_AUTH_TOKEN'),
    'endpoint' => env('IMPG_ENDPOINT'),
],

Step 4: Create IMPGPayment Model & Migration

Next, you have to create a model and a migration files that will allow you to capture and store Instamojo payment details. Run below provided command in your thermina

php artisan make:model IMPGPayment
php artisan make:migration create_impgpayments_table

Above commands will generate a model and a migration file. Open app/Models/IMPGPayment.php file and copy below given code into it:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class IMPGPayment extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'email',
        'mobile',
        'amount'
    ];
}

Open the databse/migrations/*_create_impgpayments_table.php file and copy below given code inside it:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('impgpayments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('mobile');
            $table->string('amount');
            $table->string('purpose');
            $table->string('payment_request_id');
            $table->string('payment_link');
            $table->string('payment_status')->nullable();
            $table->string('payment_id')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('impgpayments');
    }
};

Next, you have to run below command that will run the laravel migrattion and necessary tables will be created in the mysql db:

php artisan migrate

Step 5: Create IMPGPayment Controller

Next, create app/Http/Controllers/IMPGPaymentController.php file and copy below given code in it:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Validator;
use App\Models\IMPGPayment;

class IMPGPaymentController extends Controller
{
    protected $rpp = 10;

    public function index(Request $request)
    {
        $request_data = $request->all();
        $view_data = [];
        if (!$request->ajax()){
            $view_data['title'] = 'Instamojo Payment List';
            return view('impgpayments.index')->with($view_data);
        } else {
            $page = $request_data['page'];
            $view_data['page'] = $page;
            $records = IMPGPayment::orderBy('created_at', 'desc')->paginate($this->rpp);
            $record_starts = $this->rpp * ($page - 1) + 1;
            $record_ends = $this->rpp * ($page - 1) + count($records);
            $view_data['records'] = $records;
            $view_data['record_starts'] = $record_starts;
            $view_data['record_ends'] = $record_ends;
            return view('impgpayments.list')->with($view_data);
        }
    }

    public function create(Request $request)
    {
        $view_data['title'] = 'Create New Instamojo Payment';
        return view('impgpayments.create')->with($view_data);
    }

    public function store(Request $request)
    {
        $posted_data = $request->all();
        $validator = Validator::make($posted_data, array(
            'name' => 'required|min:3',
            'email' => 'required',
            'mobile' => 'required',
            'amount' => 'required'
        ), array(
            'name.required' => 'Enter your name.',
            'name.min' => 'Min of 3 characters.',
            'email.required' => 'Enter email address.',
            'mobile.required' => 'Enter mobile number.',
            'amount.required' => 'Enter amount.'
        ));

        if ($validator->fails()) {
            return redirect()->back()->withInput($request->only('name', 'email', 'mobile', 'amount'))->withErrors($validator->errors());
        }

        try {
            $instamojo = config('services.instamojo');
            $payload = array(
                "purpose" => "IMORDER" . Str::random(9),
                "amount" => intval($request->amount),
                "buyer_name" => $request->name,
                "email" => $request->email,
                "phone" => $request->mobile,
                "send_email" => true,
                "send_sms" => true,
                "redirect_url" => url('/instamojopayments/success')
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $instamojo['endpoint'].'payment-requests/');
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "X-Api-Key:".$instamojo['api_key'],
                "X-Auth-Token:".$instamojo['auth_token']
            ));
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
            $response = curl_exec($ch);
            curl_close($ch);

            $response = json_decode($response, true);

            if ($response['success'] == 1) {
                $payment_request = $response['payment_request'];
                IMPGPayment::insert([
                    'name' => $payment_request['buyer_name'],
                    'email' => $payment_request['email'],
                    'mobile' => $payment_request['phone'],
                    'amount' => $payment_request['amount'],
                    'purpose' => $payment_request['purpose'],
                    'payment_request_id' => $payment_request['id'],
                    'payment_link' => $payment_request['longurl'],
                    'payment_status' => $payment_request['status'],
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                header('Location: ' . $payment_request['longurl']);
                exit();
            } else {
                echo "<pre>";
                print_r($response);
                exit;
            }
        }catch (Exception $e) {
            echo "<pre>";
            print('Error: ' . $e->getMessage());
            exit;
        }
    }

    public function success(Request $request)
    {
        $request_data = $request->all();
        $payment_id = $request_data['payment_id'];
        $payment_status = $request_data['payment_status'];
        $payment_request_id = $request_data['payment_request_id'];
        
        $im_payment = IMPGPayment::where('payment_request_id', $payment_request_id)->first();
        if ($payment_status == 'Credit') {
            $im_payment->payment_status = $payment_status;
            $im_payment->payment_id = $payment_id;
            $im_payment->save();
            dd('Payment Successful');
        } else {
            dd('Payment Failed!');
        }
        dd($request_data);
    }
}

Step 6: Create Application Routes

Next, open routes/web.php file and copy the below provided code in it:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\IMPGPaymentController;
Route::group(['prefix' => 'instamojopayments'], function () {
    Route::get('/', [IMPGPaymentController::class, 'index']);
    Route::get('/create', [IMPGPaymentController::class, 'create']);
    Route::post('/', [IMPGPaymentController::class, 'store']);
    Route::any('/success', [IMPGPaymentController::class, 'success']);
});

Step 7: Create Blade View Pages

Next, create the below mentioned blade files under resources/views/impgpayments directory:

resources/views/impgpayments/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Instamojo Payment Gateway Integration - Laravel 9 </title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<div class="container mt-3">
    <div class="row text-center"><h1>Instamojo Payment Gateway Integration</h1></div>
    <div class="row" id="result-div"><strong style="color: #0cf;text-align: center;">Fetching records...</strong></div>
</div>
<script>
var pageNo = 1;
$(function(){
    $.ajax({
        url: "{{url('instamojopayments')}}",
        type: "GET",
        dataType: "HTML",
        data: {'page': pageNo}
    }).done(function(data){
        $("#result-div").empty().html(data);
    }).fail(function(jqXHR, ajaxOptions, thrownError){
        console.log('No response from server');
    }).always(function(){
    });
});
</script>
</body>
</html>

resources/views/impgpayments/list.blade.php

<div class="col-12 mb-3">
    <div class="card text-white bg-success mb-3">
        <div class="card-header">
            <h3 class="card-title" style="display: inline-block;">Instamojo Payments List</h3>
            <a href="{{url('/instamojopayments/create')}}" class="btn btn-primary float-end">Create New Instamojo Payment</a>
        </div>
        <div class="card-body table-responsive">
            <table class="table table-striped text-white">
                <thead>
                <tr style="text-transform: uppercase;">
                    <th>#</th>
                    <th>Name</th>
                    <th>EMail</th>
                    <th>Mobile</th>
                    <th>Amount</th>
                    <th>Purpose</th>
                    <th>Status</th>
                    <th>PaymentId</th>
                    <th>CreatedAt</th>
                </tr>
                </thead>
                <tbody>
                @if($records->count() > 0)
                    @foreach($records as $rec)
                    <tr>
                        <td>{{$loop->iteration}}</td>
                        <td>{{$rec->name}}</td>
                        <td>{{$rec->email}}</td>
                        <td>{{$rec->mobile}}</td>
                        <td>{{$rec->amount}}</td>
                        <td>{{$rec->purpose}}</td>
                        <td><button class="btn btn-info">{{$rec->payment_status}}</button></td>
                        <td>{{$rec->payment_id}}</td>
                        <td>{{$rec->created_at}}</td>
                    </tr>
                    @endforeach
                @else
                    <tr class="text-center"><td colspan="8">Record not found!!</td></tr>
                @endif
                </tbody>
            </table>
            {!! $records->links() !!}
        </div>
    </div>
</div>

resources/views/impgpayments/create.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Instamojo Payment Gateway Integration - Laravel 9</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-3">
        <div class="row justify-content-center">
            <div class="col-12 col-md-6 mb-3">
                <div class="card text-dark bg-success mb-3">
                    <div class="card-header">
                        <h3 class="card-title text-white" style="display: inline-block;">Create New Instamojo Payment</h3>
                        <a href="{{url('/instamojopayments')}}" class="btn btn-primary float-end">Instamojo Payments List</a>
                    </div>
                    <div class="card-body">
                        <form action="{{ url('instamojopayments') }}" method="POST" name="laravel9-instamojo-integration">
                            {{ csrf_field() }}
                            <div class="form-floating">
                              <input type="text" class="form-control" name="name" id="name" value="{{ old('name') }}" placeholder="name">
                              <label for="name">Full Name</label>
                            </div>
                            <div class="form-floating">
                              <input type="email" class="form-control" name="email" id="email" value="{{ old('email') }}" placeholder="email">
                              <label for="email">Email Address</label>
                            </div>
                            <div class="form-floating">
                              <input type="text" class="form-control" name="mobile" id="mobile" value="{{ old('mobile') }}" placeholder="mobile">
                              <label for="mobile">Mobile Number</label>
                            </div>
                            <div class="form-floating">
                              <input type="text" class="form-control" name="amount" id="amount" value="{{ old('amount') }}" placeholder="amount">
                              <label for="amount">Amount</label>
                            </div>
                            <button class="w-100 btn btn-lg btn-primary" type="submit">Place Order</button>
                        </form>
                        @if ($errors->any())
                        <div class="alert alert-danger text-start" role="alert">
                            <strong>Opps!</strong> Something went wrong<br>
                            <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                            </ul>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 8: Run Laravel Application

Great, let's start the application development server by using below given command in terminal:

php artisan serve

Once development server is started, in your browser, open below URL:

http://127.0.0.1:8000/instamojopayments

Note: You can use below given Instamojo Test Card Credentials to test your newly created application:

CardNo: 4242 4242 4242 4242
Date: Any valid future date
CVV: 111
Name: abc
3D-secure Password: 1221

 

Thank You, Please Share.

Recommended Posts

Simplified Laravel 9 REST API Tutorial using Sanctum  Authentication

Simplified Laravel 9 REST API Tutorial using Sanctum Authentication

In this simplified tutorial, you will learn the simplest way to create a REST API application in Laravel 9 that will be authenticated using Laravel Sanctum.

Simplified Laravel 9 Cashfree Integration Tutorial for Beginners

Simplified Laravel 9 Cashfree Integration Tutorial for Beginners

In this awesome tutorial, we are going to learn the simplest way of integrating Cashfree Payment Gateway inside Laravel 9 application.

Simplified Laravel 9 Razorpay Integration Tutorial for Beginners

Simplified Laravel 9 Razorpay Integration Tutorial for Beginners

This simplified tutorial will show you the easy and simplest way of integrating Razorpay Payment Gateway in Laravel 9 Application.