Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@gayanhewa gayanhewa commented Oct 21, 2014

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.