Dj Techblog

A blog on web development

Instamojo payment gateway integration in php

Last modified on Jan 15, 2021
Instamojo payment gateway integration in php

Instamojo is India's simplest online selling platform. It powers small, independent businesses, MSMEs & startups with online stores and online payment solutions like pay button, payment link, payment gateway integration etc. Instamojo is easy to integrate yet powerful and secured. It can be used for embeding payment button in the website, generating payment links and sending it to customers via whatsapp, email and different online medium.

In this tutorial we will use php wrapper class for Instamojo API to generate payment url dynamically. We can also use pre-generated payment link and share it to customers via email, Whatsapp or embed a pay button at our convenience. Pay button and payment links are not flexible and it has very few options for modifications. But payment gateway integration gives us full freedom of modification as we wish.

Every payment gateway offers a testing environment to check for errors in the code. Instamojo also provides us with an option to create a sandbox(dummy) account to test our code.

Steps to instamojo integration in php.

  1. Create an Instamojo test account.
  2. Generate API key, auth token and private salt.
  3. Download the project, replace with test data.
  4. Create a demo product details page.
  5. Form to fill user details with final pay button
  6. Redirect user to fill the card details
  7. Redirect user to Thank you page on successful transaction.
  8. Configure webhook for email notification and save order to database.

Create an instamojo test account by going to Instamojo Test. Go to dashboard then in the left navigation bar click API and plugins. In the integration settings you will see three values api key, auth token and private salt. Copy them to use in the project.

Landing page : products.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="../../favicon.ico">
  <title>Demo Shopping Page</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"  crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"  crossorigin="anonymous"></script>
</head>
<body>
  <div class="container">
    <div class="page-header">
      <h1><a href="index.php">Instamojo Payment Gateway Integration</a></h1>
      <p class="lead">A test product page</p>
    </div>
    <h3>Details</h3>
<div class="col-md-4">
<img src="/payments/download.jpg" width="300" alt="..." class="img-rounded">
<h4> Shirts Mens </h4>
<h6> Price: 500</h6>
<h5> ID: 111</h5>
<a href="order.php?id=111" class="btn btn-success"> Buy Now </a>
</div>
<div class="col-md-4">
<img src="/payments/demo-shirt.jpg" width="300" height="300" alt="..." class="img-rounded">
<h4> T Shirt Mens </h4>
<h6> Price: 700</h6>
<h5> ID: 112</h5>
<a href="order.php?id=112" class="btn btn-success"> Buy Now </a>
</div>
<div class="col-md-4">
<img src="/payments/demo-jeans.jpg" width="300" height="300" alt="..." class="img-rounded">
<h4> Jeans Mens </h4>
<h6> Price:1000</h6>
<h5> ID: 113</h5>
<a href="order.php?id=113" class="btn btn-success"> Buy Now </a>
</div>
  </div> <!-- /container -->
</body>
</html>
                          

Getting product id

On the products page, you need to fetch the product id for each product. For the demo test, I have made things simple. The products you are seeing here are not showing from the database. It's just included on the page. For a real website, you need to fetch the products from the database. After the user clicks on Buy Now, it is redirected to a page where the buyer fills in all his details.

landing page

order.php

<?php 

if(isset($_GET['id']) && $_GET['id'] == 111){

  $prd_name = "Shirt Mens #111";
$price = 500;

// Price calculation with tax and fee
$fee = 3 +($price*.02);
$tax = $fee * .15;
$prd_price = $fee + $tax + $price;	


} 
 else if(isset($_GET['id']) && $_GET['id'] == 112){
  $prd_name = "T Shirt Mens #112";
   $price = 500;

// Price calculation with tax and fee
$fee = 3 +($price*.02);
$tax = $fee * .15;
$prd_price = $fee+ $tax + $price;	
} 
 else if(isset($_GET['id']) && $_GET['id'] == 113){
  $prd_name = "Jeans Mens #113";
  $price = 1000;

// Price calculation with tax and fee
$fee = 3 +($price*.02);
$tax = $fee * .15;
$prd_price = $fee+ $tax + $price;	
} else {

 echo "No such a prodcut to purchase :(";
 exit();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="../../favicon.ico">

  <title>Buy <?php echo $prd_name; ?></title>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"  crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>

<body>
  <div class="container">

    <div class="page-header">
      <h1><a href="index.php">Test Payment for Instamojo</a></h1>
      <p class="lead">A test payment integration for instamojo payment gateway. Written in PHP</p>
    </div>

  <p>
  <b>Product name :</b> <?php echo $prd_name; ?>
  </p>
  <p>
  <b>Price : </b> <?php echo $price; ?>
  </p>
  <p><b>Bank Fee : </b> <?php echo $tax + $fee ; ?> <small> (Rs:3+ 2% of fee+ 15% Service Tax)</small></p>

  <p><b>Total : </b> <?php echo $prd_price; ?></p>

  <h3>Payment Details for the product <?php echo $prd_name; ?></h3>
  <hr>
  <form action="pay.php" method="POST" accept-charset="utf-8">

  <input type="hidden" name="product_name" value="<?php echo $prd_name; ?>"> 
  <input type="hidden" name="product_price" value="<?php echo $prd_price; ?>"> 

  <div class="form-group">
    <label>Your Name</label>
     <input type="text" class="form-control" name="name" placeholder="Enter your name">	 <br/>
  </div>

  <div class="form-group">
    <label>Your Mobile</label>
     <input type="text" class="form-control" name="phone" placeholder="Enter your phone number"> <br/>
  </div>


  <div class="form-group">
    <label>Your Email</label>
     <input type="email" class="form-control" name="email" placeholder="Enter you email"> <br/>
  </div>
  
  <div class="form-group">
    <label>Shipping Address</label>
     <textarea class="form-control" name="shipping-address" placeholder="Enter shipping address"></textarea> <br/>
  </div>
  
  <div class="form-group">
    <label>Billing Address</label>
     <textarea class="form-control" name="billing-addrss" placeholder="Enter billing address"> </textarea><br/>
  </div>

  
  <input type="submit" class="btn btn-success btn-lg" value="Click here to Pay Rs:<?php echo $prd_price; ?> ">

   </form>
<br/>
<br/>     
  </div> <!-- /container -->


</body>
</html>

Getting price of the product

On the order.php page, we retrieve the price of the product. Again for the sake of simplicity, I have coded the price on the page itself but in real-time, where a large number of products will be available you need to fetch everything product id, image, and price from the database and let every detail show here. The user now fills in his details and proceed to pay the amount.

demo order page

pay.php

<?php
$product_name = $_POST["product_name"] ;
$price = $_POST["product_price"];
$name = $_POST["name"];
$phone = $_POST["mobile"];
$email = $_POST["email"];

include 'src/instamojo.php';

$api = new Instamojo\Instamojo('api_key', 'auth_token','https://test.instamojo.com/api/1.1/');

try {
      $response = $api->paymentRequestCreate(array(
      "purpose" => $product_name,
      "amount" => $price,
      "buyer_name" => $name,
      "phone" => $phone,
      "send_email" => true,
      "send_sms" => true,
      "email" => $email,
      'allow_repeated_payments' => false,
      "redirect_url" => "https://djtechblog.com/payments/thankyou.php",
      "webhook" => "https://djtechblog.com/payments/webhook.php"
      ));

  $pay_ulr = $response['longurl'];
  


  header("Location: $pay_ulr");
  exit();

}
catch (Exception $e) {
  print('Error: ' . $e->getMessage());
}

?>
                           

Calls Instamojo API and generates payment url

pay.php page receives all the data given by the user on the previous page and stores in different variables. Now we create an object of php wrapper class to call Instamojo API. The wrapper class takes three parameters the private api key, auth-token, and the base url of the Instamojo api. (You need to provide your key details here). It returns a longurl which is happened to be the payment url. User is automatically redirected to the payment url for the final payment where he enters his payment option like credit card /debit card/net banking/wallet or QR code scanning.

The base url of the instamojo test api is https://test.instamojo.com/api/1.1/. For live payment use https://instamojo.com/api/1.1/

thankyou.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="../../favicon.ico">

  <title>BNCA: Payment Success</title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style>
    #details-container
    {
        padding-left: 50px;
    }
    @media(max-width: 600px)
    {
        #details-container
        {padding-left: 20px;}
    }
</style>
</head>

<body>
  <div class="container">

    <div class="page-header">
      <h1>Bhanjanagar Computer Academy : Course Fee Payment</h1>
   </div>

    <h3 style="color:#6da552">Thank You, Payment Successful!</h3>
    <h4 style="color:#6da552">Keep payment deatils safe for future reference.</h4>


<?php

include 'src/instamojo.php';

$api = new Instamojo\Instamojo('test_471c4569e7c0bbec66bacecaea1', 'test_dbd4f9391fd3909c0736a61506d','https://test.instamojo.com/api/1.1/');

$payid = $_GET["payment_request_id"];


try {
  $response = $api->paymentRequestStatus($payid);


  echo "<h4>Payment ID: " . $response['payments'][0]['payment_id'] . "</h4>";
  echo "<h4>Amount Paid: " . $response['payments'][0]['amount'] . "</h4>"; 
  echo "<h4>Applicant Name: " . $response['payments'][0]['buyer_name'] . "</h4>";
  echo "<h4>Applicant Email: " . $response['payments'][0]['buyer_email'] . "</h4>";
  echo "<h4>Applicant Mobile Number: " . $response['payments'][0]['buyer_phone'] . "</h4>";
echo "<pre>";
 print_r($response);
echo "</pre>";
  ?>


  <?php
}
catch (Exception $e) {
  print('Error: ' . $e->getMessage());
}



?>


    
  </div> <!-- /container -->


</body>
</html>
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.

webhook.php

<?php
$data = $_POST;
$mac_provided = $data['mac'];  // Get the MAC from the POST data
unset($data['mac']);  // Remove the MAC key from the data.
$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];

if($major >= 5 and $minor >= 4){
   ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
   uksort($data, 'strcasecmp');
}
// You can get the 'salt' from Instamojo's developers page(make sure to log in first): https://www.instamojo.com/developers
// Pass the 'salt' without the <>.
$mac_calculated = hash_hmac("sha1", implode("|", $data), "private salt");
if($mac_provided == $mac_calculated){
  echo "MAC is fine";
  // Do something here
  if($data['status'] == "Credit"){
     // Payment was successful, mark it as completed in your database  
              $to = 'debabrattaj@gmail.com';
              $subject = 'Website Payment Request ' .$data['buyer_name'].'';
              $message = "<h1>Payment Details</h1>";
              $message .= "<hr>";
              $message .= '<p><b>ID:</b> '.$data['payment_id'].'</p>';
              $message .= '<p><b>Amount:</b> '.$data['amount'].'</p>';
              $message .= "<hr>";
              $message .= '<p><b>Name:</b> '.$data['buyer_name'].'</p>';
              $message .= '<p><b>Email:</b> '.$data['buyer'].'</p>';
              $message .= '<p><b>Phone:</b> '.$data['buyer_phone'].'</p>';
              $message .= "<hr>";
              $headers .= "MIME-Version: 1.0\r\n";
              $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
              // send email
              mail($to, $subject, $message, $headers);
  }
  else{
     // Payment was unsuccessful, mark it as failed in your database
  }
}
else{
  echo "Invalid MAC passed";
}
?>
                              

This page needs to be configured if you want to receive an email for every purchase. Replace the private salt and email id.


Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.