Created
February 6, 2015 03:21
-
-
Save gayanhewa/842ffdd6a4456d296347 to your computer and use it in GitHub Desktop.
Signature ( GET requests )
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 = ""; | |
| $api_sec = ""; | |
| $url = "http://abc.com/programs/1"; | |
| // Method specific options | |
| $method = "GET"; | |
| $path = "api/programs/1"; | |
| //Query params | |
| $params = array(); | |
| $params['auth_version'] = "1.0"; | |
| $params['auth_key'] = $api_key; | |
| $params['auth_timestamp'] = time(); | |
| $array = array(); | |
| foreach($params as $k => $v) | |
| { | |
| // Set each param on the array | |
| $array[strtolower($k)] = $v; | |
| } | |
| ksort($array); | |
| $array = http_build_query($array); | |
| // prepare the string to sign | |
| $string_to_sign = implode("\n", array($method, $path, $array)); | |
| echo "<h1> String to Sign : </h1><pre>"; | |
| echo $string_to_sign; | |
| echo "</pre></hr>"; | |
| //generate the signature | |
| $signature = hash_hmac('sha256', $string_to_sign, $api_sec); | |
| $params['auth_signature'] = $signature; | |
| echo "<h1> Params Posted : </h1><pre>"; | |
| print_r(json_encode($params)); | |
| echo "</pre></hr>"; | |
| // When a GET request is sent the parameters are appended to the Query string. Submitting them as curl post fields has no effect. | |
| $url = $url."?". http_build_query($params); | |
| echo $url; | |
| // Calling the rest api with curl | |
| $ch = curl_init(); | |
| curl_setopt($ch, CURLOPT_URL, $url); | |
| // These curl options are only for POST request. | |
| //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 "<h1> Server Response : </h1>"; | |
| echo "<pre>"; | |
| print_r($server_output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment