Created
September 24, 2014 04:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
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
To use the local virtualhosts with this script follow this link