2

I would like to know which function I can use to create signature for Instamojo's payment links in PHP and what procedure should I follow if I had an array of read-only values?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504

1 Answers1

4

You can use the hash_hmac function in PHP to create the signature. Instamojo uses "sha1" algorithm, so, your hash_hmac call will looks like:

hash_hmac("sha1", $message, $salt)

Here $message is going to be the "|" separated values and $salt will be private salt from the developers page(make sure you are logged in).

The algorithm for generating $message is:

Arrange the read-only fields in the alphabetical order of their keys. If you have any keys with upper-case letters, convert them to lower-case letters first.

Let's say the url is:

https://www.instamojo.com/demo/demo-offer/?data_name=Aditya+Sengupta&data_email=aditya@instamojo.com&data_phone=9999999999&data_amount=123.45&data_readonly=data_name&data_readonly=data_email&data_readonly=data_phone&data_readonly=data_amount

For the above url you would get the following order:

  1. data_amount
  2. data_email
  3. data_name
  4. data_phone

Using the above order of keys we will get the values in following order:

  1. 123.45
  2. aditya@instamojo.com
  3. Aditya Sengupta
  4. 9999999999

Now concatenate the above values using |(pipe) operator, so $message will look like:

123.45|aditya@instamojo.com|Aditya Sengupta|9999999999

If your $salt is "abcde" then you will get this as signature:

$ php -a
Interactive shell

php > $message = "123.45|aditya@instamojo.com|Aditya Sengupta|9999999999";
php > $salt = "abcde";
php > echo hash_hmac("sha1", $message, $salt) . "\n";
676a4b5ba30e464f027249747a63ea587f8c4b9a

How to do this if I had an array of read-only values?

Well you need to sort the array by keys first, it should be case-insensive. If you're using PHP 5.4.0 + you can do something like this:

php > $read_only_fields = ["data_email" => "aditya@instamojo.com", "data_Phone" => "9999999999", "data_name" => "Aditya Sengupta", "data_Amount" => "123.45"];
php > ksort($read_only_fields, SORT_STRING | SORT_FLAG_CASE);
php > $message = implode('|', $read_only_fields);
php > echo $message . "\n";
123.45|aditya@instamojo.com|Aditya Sengupta|9999999999
php > $salt = "abcde";
php > echo hash_hmac("sha1", $message, $salt) . "\n";
676a4b5ba30e464f027249747a63ea587f8c4b9a

For older versions of PHP(older than 5.4.0) use this for sorting:

uksort($data, 'strcasecmp');

For more info read their Integration documentation and How do I ensure that the link is tamper proof?.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504