In this tutorial I will explain how to integrate the Instamojo payment gateway in PHP step by step. we will use a PHP wrapper class for Instamojo API to dynamically generate a payment URL. We can also use a pre-created payment link and share it with customers via email or WhatsApp, or insert a buy button if that suits you. The buy button and payment links are not flexible and have very little editing options. But payment gateway integration gives us complete freedom to customize as per our wish.
Instamojo is India’s easiest online selling platform. We empower small independent businesses, MSMEs and start-ups with online shops and online payment solutions such as Pay-Button, Payment-Link and Payment-Gateway-Integration. It comes with all modern payment option like debit card, credit card, net banking, UPI, EMI option etc. Instamojo is easy to integrate, yet powerful and secure.
It is very easy to integrate in your website, App. Also you send Payment link for a particular amount through Instamojo payment button.
See also:
Please follow the below step to integrate Instamojo in your PHP website.
- Create an Instamojo test account
- Put your auth key, private key and working key in the files where it required.
- Create Database and Table by SQL query
- Create Database Configuration File
- Create a demo product details page.
- Create HTML Checkout Form
- Form to fill user details with final pay button
- Redirect user to Thank you page on successful transaction.
Create an Instamojo test account
Go to Instamojo test and create an instamojo test account. Go to your dashboard and click APIs & Plugins in the left navigation panel. The integration settings display three values: API Key, Auth Token, and Private Salt. Copy them and use them in your project.

Choose your programming language from the supported libraries and download the instamojo folder from Github landing page.
File Structure
File Name | Purpose |
---|---|
index.php | Contains the Products listing |
config.php | Contains the database connection |
checkout.php | Contains the checkout code |
pay.php | Contains the Checkout parameters. |
thankyou.php | Contains the payment signature verification codes. |
Create Database and Table by SQL query
We need to create database and table, so here I created webscodex database payment_transaction & products table. payment_transaction table holds the records which will be payment success or failed. You can simply create table as following SQL query.
-- -- Database: `webscodex` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `product_name` varchar(100) NOT NULL, `image` varchar(100) NOT NULL, `description` text NOT NULL, `price` float(10,2) NOT NULL, `status` tinyint(4) NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; CREATE TABLE `payment_transaction` ( `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `order_id` varchar(100) NOT NULL, `full_name` varchar(100) NOT NULL, `mobile_number` varchar(100) NOT NULL, `amount` float(10,2) NOT NULL, `status` varchar(100) NOT NULL, `txns_id` varchar(100) NOT NULL, `currency` varchar(100) NOT NULL, `txns_date` datetime NOT NULL, `address` text NOT NULL, `pincode` varchar(100) NOT NULL, `city` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Create Database Configuration File
In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your root directory and put bellow code:
config.php
<?php // Database configuration define('DBSERVER', 'localhost'); define('DBUSERNAME', 'root'); define('DBPASSWORD', ''); define('DBNAME', 'webscodex'); // Create database connection $con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create a demo product details page.
On the products page, you need to fetch the products. I made it easy for myself to do a demo test. The products you see here are shown from the database. After the user clicks on “Buy Now”, he will be redirected to a page where the buyer can fill in all his details.
index.php
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Instamojo Payment Gateway Integration</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container"> <div class="py-5 text-center"> <h2> Products List (Instamojo Payment Gateway Integration) </h2> </div> <div class="row"> <?php // Database configuration require "inc/config.php"; $sql = "SELECT * FROM products WHERE status = '1' order by id DESC"; $query = $con->query($sql); if ($query->num_rows > 0) { while ($row = $query->fetch_assoc()) { ?> <div class="card col-md-4" style="width: 18rem;"> <img src="images/<?php echo $row['image']?>" class="card-img-top" alt="<?php echo $row['product_name']?>" style="width: 350px; height: 250px;"> <div class="card-body"> <h5 class="card-title"><?php echo $row['product_name']?></h5> <p class="card-text"><?php echo $row['description']?></p> <a href="checkout.php?product_id=<?php echo $row['id']?>" class="btn btn-sm btn-primary">Buy Now</a> <b><span style="float: right;"> ₹<?php echo $row['price']?></span></b> </div> </div> <?php } } ?> </div> </div> </body> </html>

Create HTML Checkout Form
Create an HTML checkout form on your website with the required fields so that it can be passed to the Instamojo library to retrieve the order id and other information needed for the payment step. An example HTML form field is shown below. product name, quantity, amount, item description, item address, email, and so on.
checkout.php
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Instamojo Payment Gateway Integration Checkout</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container" style="background: #f2f2f2; padding-bottom:20px; border: 1px solid #d9d9d9; border-radius: 5px;"> <div class="py-5 text-center"> <h2>Instamojo Payment Gateway Integration Checkout</h2> <p class="lead">This Checkout page using Instamojo Payment Gateway for Testing purpose </p> </div> <form action="pay.php" method="POST"> <div class="row"> <div class="col-md-8"> <h4>Billing address</h4> <div class="card p-3"> <div class="mb-3"> <label for="firstName">Full Name </label> <input type="text" class="form-control" name="full_name" placeholder="Full Name" required=""> </div> <div class="mb-3"> <label for="mobile">Mobile Number</label> <input type="text" class="form-control" name="mobile_number" placeholder="Mobile Number" required=""> </div> <div class="mb-3"> <label for="email">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" name="email" placeholder="Email"> </div> </div> </div> <div class="col-md-4"> <?php // Include Database configuration require "inc/config.php"; if (!empty($_GET['product_id']) && isset($_GET['product_id'])) { $pid = $_GET['product_id']; } $sql = "SELECT * FROM products WHERE id = $pid"; $query = $con->query($sql); if ($count = $query->num_rows > 0) { $row = $query->fetch_assoc(); ?> <h4 class="d-flex justify-content-between align-items-center"> <span>Order Summary</span> <span class="badge badge-secondary badge-pill"><?php echo $count; ?></span> </h4> <ul class="list-group mb-3 sticky-top"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div class="product-list"> <img src="images/<?php echo $row['image']?>" class="card-img-top" style="width:100px; height: 100px;"> <h6><?php echo $row['product_name']?></h6> <small class="text-muted"><?php echo $row['description']?></small> </div> <span class="text-muted">₹<?php echo $row['price']?></span> </li> <li class="list-group-item d-flex justify-content-between"> <strong> Order Total: </strong> <strong>₹<?php echo $row['price']?></strong> <input type="hidden" name="amount" value="<?php echo $row['price']?>" /> <input type="hidden" name="product_id" value="<?php echo $row['id']?>" /> </li> </ul> <?php } else{ header("Location:index.php"); } ?> <div> <input class="btn btn-success btn-block" type="submit" name="check_out" value="Continue to Checkout"> </div> </div> </div> </form> </div> </body> </html>

Form to fill user details with final pay button
The pay.php page gets all the data provided by the user in the previous page and stores it in different variables. Now let’s create a PHP wrapper class object to call the Instamojo API. The wrapper class takes three parameters: a private API key, an authentication token, and the base URL of the Instamojo API. (You must provide your key details here). It returns a long URL which happens to be the payment URL. Users will be automatically redirected to the final payment payment URL where they will enter their payment options such as credit/debit card/net banking/wallet or QR code scanning.
pay.php
<?php session_start(); ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Instamojo Payment Gateway Integration in PHP</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <?php // Include Database configuration require "inc/config.php"; if (isset($_POST['check_out']) && !empty($_POST['product_id'])) { date_default_timezone_set("Asia/Kolkata"); $productId = $_POST['product_id']; $fullName = $_POST['full_name']; $email = $_POST['email']; $mobileNumber = $_POST['mobile_number']; $amount = $_POST['amount']; $orderId = "WC".rand(1111, 9999); $query = "SELECT * FROM products WHERE id = $productId"; $result = $con->query($query); if ($result->num_rows > 0) { $apiKey = ""; // Your Private API Key $authToken = ""; // Your Private Auth Token $mojoURL = "test.instamojo.com"; // Change development to production mode (https://www.instamojo.com) //initialize session $ch = curl_init(); //set the URL curl_setopt($ch, CURLOPT_URL, "https://$mojoURL/api/1.1/payment-requests/"); // //https://api.instamojo.com/1.1/payment_requests/ //set options 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:$apiKey", "X-Auth-Token:$authToken")); $payload = Array( 'purpose' => 'Web Development', 'amount' => $amount, 'buyer_name' => $fullName, 'email' => $email, 'phone' => $mobileNumber, 'send_email' => false, // Pass true if you want to send email to customer email address 'send_sms' => false, // Pass true if you wany to send sms to customer mobile number 'redirect_url' => 'http://localhost/BlogPost/Instamojo-Payment-gateway-in-php/verify.php', 'webhook' => '', 'allow_repeated_payments' => false ); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload)); //execution $response = curl_exec($ch); //close curl_close($ch); //decode the json $decode = json_decode($response); if ($decode->success == true) { $txnsId = $decode->payment_request->id; $paymentURL = $decode->payment_request->longurl; $txnsDate = $decode->payment_request->created_at; $status = $decode->payment_request->status; $_SESSION['TXNS_ID'] = $decode->payment_request->id; // Insert Payment Transaction Details $sqlQuery = "INSERT INTO payment_transaction (order_id, full_name, mobile_number, amount, status, txns_id, txns_date) VALUES ('$orderId', '$fullName', '$mobileNumber', '$amount', '$status', '$txnsId', '$txnsDate')"; if ($con->query($sqlQuery)) { header("Location:$paymentURL"); exit(); } }else{ echo "$response"; echo "Contact the developer's email ID tv.agathiya@gmail.com with screenshot for technical support"; } } } ?> </body> </html>

User to fill the card details and click on the pay button to redirect to the success of failed page.
Redirect user to Thank you page on successful transaction.
The user is redirected to the thankyou.php page after successful payment and necessary details regarding the payment also printed on the screen. On this page, you need to replace the private api key and auth-token with yours.
thankyou.php
<?php session_start(); ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Instamojo Payment Gateway Integration Success</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="py-5 text-center"> <h1>Instamojo Payment Gateway Integration Success</h1> </div> <?php if ($_SESSION['TXNS_ID'] == $_GET['payment_request_id']) { echo"<div class='alert alert-success col-md-6 offset-3'> Payment Successful </div>"; } // You can udpate Payment transaction status here.. echo "<div class='col-md-6 offset-3'> <table class='table table-striped'> <thead> <tr> <th scope='col'>Payment Id</th> <th scope='col'>Payment Status</th> </tr> </thead> <tbody> <tr> <td>" . $_GET['payment_request_id'] . "</td> <td>" . $_GET['payment_status'] . "</td> </tr> </tbody> </table> </div><br> <p class='text-center'>Continue Shopping <a href='index.php'>Home Page</a></p>"; ?>
