How to Integrate Instamojo Payment Gateway in Laravel 10

Category: Laravel
Updated on: 21 Dec, 2024
In this tutorial, I will show how to integrate instamojo payment gateway with Laravel 10. You will have to create a test or sandbox account in instamojo in order to get the API credential. Go to this link:
Click on the "Sign Up" button from the top to go to the Sign Up page. Then you will see a page like this:
Give your Email address and Password here and click on "Sign up as Business" button. You will be asked to give your mobile number. Give any Indian mobile number. It is not mandatory that you have to give a real number.

Then it will ask you to give OPT. Give "1234" as the OTP.

Then follow the next steps and in this way complete the signup process. This is very straightforward and easy method.

As I have account there already, I am not going to signup again. I will use my own API keys. You will get the API keys in this page:
One important thing to mention:
Sometimes, you can see the permission error in API integration response. If such thing happens, you have to contact the instamojo support. This thing is written in this article:
Installing Laravel
First, you have to install a fresh version of Laravel 10. You can go to the official documentation of Laravel:
You will see a section there: "Creating A Laravel Project". Here you will get your codes to install Laravel 10. I am going to write the commands you will need to install laravel. First, open your terminal where you want to install laravel on your computer. Then use these commands:
composer create-project laravel/laravel example-app
cd example-app
php artisan serve
You can run your application now using this url into your browser: http://127.0.0.1:8000

Now go to this location: resources > views > welcome.blade.php.

Change the codes of this page like this:
welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel - Instamojo Integration</title>
</head>
<body>
    <h2>Product: Mobile Phone</h2>
    <h3>Price: ₹300</h3>
    <form action="{{ route('instamojo') }}" method="post">
        @csrf
        <input type="hidden" name="product_name" value="Mobile Phone">
        <input type="hidden" name="price" value="300">
        <input type="hidden" name="quantity" value="1">
        <button type="submit">Pay with Instamojo</button>
    </form>
</body>
</html>
Go to this link to install a instamojo package in php:
Go to your terminal and run this command:
composer require instamojo/instamojo-php
Create a migration file using this command:
php artisan make:migration create_payments_table
A migration file will be created in this location: "database > migrations > 2023_11_28_011309_create_payments_table.php"

Now write the following code here:
2023_11_28_011309_create_payments_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->string('payment_id');
            $table->string('product_name');
            $table->string('quantity');
            $table->string('amount');
            $table->string('currency');
            $table->string('customer_name');
            $table->string('customer_email');
            $table->string('payment_status');
            $table->string('payment_method');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('payments');
    }
};
Write this command to create the "payments" table.
php artisan migrate
You have to create a model now. The model name will be the singular form of the table name. So it will be "Payment". Run this command in the terminal to create this model:
php artisan make:model Payment
I am going to create a controller now. So run this command in terminal:
php artisan make:controller InstamojoController
Modify the "route > web.php" file as this:
web.php
<?php

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

Route::get('/', function () {
    return view('welcome');
});

Route::post('instamojo', [InstamojoController::class, 'instamojo'])->name('instamojo');
Route::get('callback', [InstamojoController::class, 'callback'])->name('callback');
Route::get('success', [InstamojoController::class, 'success'])->name('success');
Route::get('cancel', [InstamojoController::class, 'cancel'])->name('cancel');
In previous section, we got the Private API key and Private Auth Token. See this:
Private API Key: test_765e78237d842d2edd78d885ae4
Private Auth Token: test_053bd3a571b1bb7daca95222eb7
Now you will have to use these values in your application. So, add the following lines in the bottom of your .env file:
INSTAMOJO_API_KEY=test_765e78237d842d2edd78d885ae4
INSTAMOJO_AUTH_TOKEN=test_053bd3a571b1bb7daca95222eb7
INSTAMOJO_ENVIRONMENT=sandbox
InstamojoController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Payment;

class InstamojoController extends Controller
{
    public function instamojo(Request $request)
    {

        if(env('INSTAMOJO_ENVIRONMENT') == 'sandbox') {
            $url = 'https://test.instamojo.com/api/1.1/payment-requests/';
        } else {
            $url = 'https://www.instamojo.com/api/1.1/payment-requests/';
        }

        $api_key = env('INSTAMOJO_API_KEY');
        $auth_token = env('INSTAMOJO_AUTH_TOKEN');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        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:$api_key",
                        "X-Auth-Token:$auth_token"));
        $payload = Array(
            'purpose' => env('APP_NAME'),
            'amount' => $request->price,
            'phone' => '9999999999',
            'buyer_name' => 'John Doe',
            'redirect_url' => route('callback'),
            'send_email' => true,
            'webhook' => 'http://www.example.com/webhook/',
            'send_sms' => true,
            'email' => 'test@yourwebsite.com',
            'allow_repeated_payments' => false
        );
        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);
        //dd($response);

        if($response->success == true) {
            session()->put('product_name', $request->product_name);
            session()->put('quantity', $request->quantity);
            return redirect($response->payment_request->longurl);
        } else {
            return redirect()->route('cancel');
        }

    }
    public function callback(Request $request)
    {
        //dd($request->all());

        if(env('INSTAMOJO_ENVIRONMENT') == 'sandbox') {
            $url = 'https://test.instamojo.com/api/1.1/payments/'.$request->payment_id;
        } else {
            $url = 'https://www.instamojo.com/api/1.1/payments/'.$request->payment_id;
        }

        $api_key = env('INSTAMOJO_API_KEY');
        $auth_token = env('INSTAMOJO_AUTH_TOKEN');

        if(isset($request->payment_id) && $request->payment_id != null) {
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            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:$api_key",
                            "X-Auth-Token:$auth_token"));
            $response = curl_exec($ch);
            curl_close($ch);
            $response = json_decode($response);
            //dd($response);

            if($response->success == true) {

                $payment = new Payment();
                $payment->payment_id = $response->payment->payment_id;
                $payment->product_name = session()->get('product_name');
                $payment->quantity = session()->get('quantity');
                $payment->amount = $response->payment->amount;
                $payment->currency = $response->payment->currency;
                $payment->customer_name = $response->payment->buyer_name;
                $payment->customer_email = $response->payment->buyer_email;
                $payment->payment_status = "Completed";
                $payment->payment_method = "Instamojo";
                $payment->save();

                session()->forget('product_name');
                session()->forget('quantity');

                return redirect()->route('success');
            }

        } else {
            return redirect()->route('cancel');
        } 

    }
    public function success()
    {
        return "Payment is successful";
    }
    public function cancel()
    {
        return "Payment is failed";
    }
}

See Full Tutorial on YouTube

If you want to see the full functionality in live, you can see my video on youtube.

Download Source Code

Please give your email address. We will send you the source code on your email.