Skip to content

Instantly share code, notes, and snippets.

@gayanhewa
Created September 24, 2014 04:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gayanhewa/142c48162f72e68a4a23 to your computer and use it in GitHub Desktop.
Save gayanhewa/142c48162f72e68a4a23 to your computer and use it in GitHub Desktop.
HMAC + Sha256 hashed API Auth - This snippet implements the logic behing https://github.com/philipbrown/signplz
<?php
/**
* This snippet implements the logic behing https://github.com/philipbrown/signplz , simply to explain the functionality of generating the auth signature
* for non-php programmers so that they can authenticate with the API without a problem.
**/
$api_key = "key";
$api_sec = "sec";
$url = "http://abc.com/api/test";
// Method specific options
$method = "POST";
$path = "api/test";
//Query params
$params = [];
$params['custom_parameters'] = 'value1';
$params['auth_version'] = "1.0";
$params['auth_key'] = $api_key;
$params['auth_timestamp'] = time();
$array = [];
foreach($params as $k => $v)
{
// Set each param on the array
$array[strtolower($k)] = $v;
}
ksort($array);
$array = urldecode(http_build_query($array));
// prepare the string to sign
$string_to_sign = implode("\n", array($method, $path, $array));
//generate the signature
$signature = hash_hmac('sha256', $string_to_sign, $api_sec);
$params['auth_signature'] = $signature;
// Calling the rest api with curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
echo "<pre>";
var_dump($server_output);
@gayanhewa
Copy link
Author

To use the local virtualhosts with this script follow this link

// This is your Virtual Hosts name
$request_host   = 'customer1.mydomain.com'; 

// This is the IP
$request_url    = '192.168.0.1/api/test';

$headers = array("Host: ".$request_host);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);     
curl_setopt($ch, CURLOPT_URL, $request_url.'?'.$request_args);

@frantique
Copy link

The method is nice, but if the array's any element contains & symbol, it will break. At line 29 make it:

array_walk_recursive($array, function (&$elem, $index){ $elem = str_replace('&', '__AMP_AND__', $elem);});
$array = str_replace('__AMP_AND__', urlencode('&'), urldecode(http_build_query($array))); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment