Instamojo Payment Gateway Integration in PHP

Hello,

Instamojo is one of the easiest payment gateway to integrate in PHP. It gives your user option to pay with Cards, NetBanking and even Wallets.

After you set up an account with Instamojo, you will get an Api-Key, Auth-Token and Salt.

First Step is to pass the required data to the Instamojo API through POST method.

These are the data to be passed:

  • amount – The amount to be paid by the customer.
  • phone – Phone number of the customer.
  • buyer_name – Customer name.
  • purpose – Purpose of the payment.
  • email – Email address of the customer.

Here’s is the sample code:

Pass the Api-Key and Auth-Token here.

<?php

if((isset($_POST['amount'])) && (!empty($_POST['amount']))){
 $amount = $_POST['amount'];
 $purpose = $_POST['amount'];
 $phone = $_POST['phone'];
 $buyername = $_POST['buyername'];
 $email = $_POST['email'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/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:yourApiKeyHere",
 "X-Auth-Token:yourAuthTokenHere"));
$payload = Array(
 'purpose' => $purpose,
 'amount' => $amount,
 'phone' => $phone,
 'buyer_name' => $buyername,
 'redirect_url' => 'https://www.yourwebsitename.com/webhook.php',
 'webhook' => 'https://www.yourwebsitename.com/webhook.php',
 'send_email' => true,
 'send_sms' => true,
 'email' => $email,
 '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); 


$data = json_decode($response,true);
var_dump($data);
$site=$data["payment_request"]["longurl"];
header('HTTP/1.1 301 Moved Permanently');
header('Location:'.$site); 

} else {
 header("Location:payment.php");
}

?>

In webhook.php, pass the Salt.

<?php
/*
Basic PHP script to handle Instamojo RAP webhook.
*/

$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 <>
$mac_calculated = hash_hmac("sha1", implode("|", $data), "<yourSaltHere>");
if($mac_provided == $mac_calculated){
 $payment_id = $data['payment_id'];
 $status = $data['status'];
 $amount = $data['amount'];
 $purpose = $data['purpose'];
 if($data['status'] == "Credit"){

 // Payment was successful, mark it as successful in your database.
 // You can acess payment_request_id, purpose etc here. 
 }
 else{

 // Payment was unsuccessful, mark it as failed in your database.
 // You can acess payment_request_id, purpose etc here.
 }
}
else{
 echo "MAC mismatch";
}
?>

Here based on the data you can update status in database and redirect the user to corresponding urls.

All the instruction will be available in https://www.instamojo.com/developers/

Thanks for reading. Happy Coding.

Advertisements

Git basics for beginners

Git is a free and open-source software that is used for version control and for source code management.

For a beginner, it might be a little difficult to grasp the concepts of Git. So this post is for the newbies out there.

The Setup : 

First you have to download Git to your system. You can either go to https://git-scm.com/downloads/ and download, or you can use the terminal.

I am using ubuntu, so I used this command to install git:

sudo apt-get install git

Configurations:

Now let’s create a directory in out system where we will be working. Navigate to the location you want to store the project and create the directory.

mkdir myproject
cd myproject

Now initialize git in your directory :

git init

You can configure your name and email id with the following code :

git config --global user.name "yourname"
git config --global user.email "youremailid"

If you already have a repository in github or if you want to clone someone else’s code, you can do it now :

git clone /path/to/the/repository

If you are cloning from a remote server use this:

git clone username@host:/path/to/the/repository

Now you can go ahead and start coding. And you can start pushing the code.

Check the status of your code. You can see all the changes you have made here.

git status

Stage all the files to be pushed

git add .

or if you don’t want to stage every change, use

git add <filename>

Then you can go ahead and commit the changes.

git commit -m "Commit message"

Then push the code to the master branch.

git push origin master

You can pull the new changes from the remote repository to your local by pulling the code.

git pull

Branching : 

If multiple coders are working on the same repository, it’s advised to branch out from the master. You can branch out even if you want to work on something else without changing the existing code. Suppose you are going to work on a bug fix. You can create a branch for that by using :

git checkout -b branchname

Now you have made a copy of the master branch in the new branch. You can commit and push the code to this branch and it wont change the code in the master branch.

But remember to use this branch name while pushing the code

git push origin branchname

After working on the changes, you can checkout to the master branch and merge the code, if you want to.

git checkout master
git merge branchname

And delete the branch if needed

git branch -d branchname

You can check which branch you are currently in by the command

git branch

You can view the log of your commits using

git log

I think these are all the git commands that you need to know when you are starting out.

Good Luck. Happy coding.

Get Browser Details Using PHP

This PHP function can be used to get the details of the browser.


function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";

//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}

// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
$bname = 'Google Chrome';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$u_agent))
{
$bname = 'Apple Safari';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
}
else
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
//echo "B: ".$bname."<br>";

// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}

// see how many we have
$i = count($matches['browser']);
//echo "i: ".$i."<br>";
if($i==0)
{
$version = 11;
}
elseif ($i != 1 && $i!=0) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
}
else {
$version= $matches['version'][1];
}
}
else {
$version= $matches['version'][0];
}
//echo "V: ".$version;exit;

// check if we have a number
if ($version==null || $version=="") {$version="?";}

return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}

Tested In all the major browsers.

Go back to the previous page in PHP

Although there are many methods to do this, I prefer the following code to go back to the previous page in PHP.

11


session_start();
$url = basename($_SERVER['PHP_SELF']);
$query = $_SERVER['QUERY_STRING'];
if($query){
$url .= "?".$query;
}
$_SESSION['current_page'] = $url;

In the page you want to come back to, add the above code. In the variable $url, even the query string attached to the added. This helps in case you want to go back to page like userprofile.php?userid=1234567 .Store this in a session variable.

In the second page, get the value from the session variable.


session_start();
$previous_page = $_SESSION['current_page'];

To go back to the previous page using a button:


<a href="<?php echo $previous_page;?>"><button>BACK</button></a>

Or

By Using header:


header("location:$previous_page");

Hope this helps!

Re-sampling Image In PHP

When a user uploads a high quality image, you might have to reduce the image size or re-sample to show it in smaller screens or as thumbnails so the loading time can be reduced.

The below code will help you generate a copy of the original image in the destination folder and dimensions you specify.


//FUNCTION TO REDUCE IMAGE SIZE
function reduce_image_size($destination,$image_name,$files)
{
//REDUCE IMAGE RESOLUTION
if($files)
{
$dest = $destination.$image_name;
$width = 300; //in pixels
$height = 300;
list($original_width, $original_height) = getimagesize($files);
$original_ratio = $original_width/$original_height;
if ($width/$height > $original_ratio)
{
$width = $height*$original_ratio; //To maintain the aspect ratio
}
else
{
$height = $width/$original_ratio;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($files);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $original_width, $original_height);
imagejpeg($image_p,$dest, 100);
ImageDestroy ($image_p);
}
//END OF REDUCING IMAGE RESOLUTION
}

Codeigniter – Placing assets folder

While many practices are followed while placing the assets folder in Codeigniter, I feel that the best place is in the root folder along with the application directory as shown below.

structure

Edit the .htaccess file as shown below :


RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

You can directly call the assets files in the View pages as shown below :


<link rel="stylesheet" type="text/css" href="assets/css/style.css">

Remove index.php from URL in Codeigniter

Open applications/config/config.php and make the following changes :

Replace


$config['index_page'] = 'index.php';

With


$config['index_page'] = '';

And add the following code to a new file and save it as .htaccess inside the root folder :


RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]