Skip to content

Instantly share code, notes, and snippets.

@gayanhewa
Created January 19, 2015 03:48
Show Gist options
  • Select an option

  • Save gayanhewa/489d7d89376572764877 to your computer and use it in GitHub Desktop.

Select an option

Save gayanhewa/489d7d89376572764877 to your computer and use it in GitHub Desktop.
Signature ( POST with json_encode )
<?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/signin";
// Method specific options
$method = "POST";
$path = "api/signin";
//Query params
$params = [];
$params['username'] = 'demo';
$params['password'] = 'admin';
$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, json_encode($params));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
echo "<pre>";
var_dump($server_output);
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment