Skip to content

Instantly share code, notes, and snippets.

@stuartwilsondev
Last active October 20, 2015 13:14
Show Gist options
  • Save stuartwilsondev/abba5aa0a90cb3623092 to your computer and use it in GitHub Desktop.
Save stuartwilsondev/abba5aa0a90cb3623092 to your computer and use it in GitHub Desktop.
Auth Example
<?php
/**
* Example class demonstrating how to create the authorization hash for accessing the EditorEye API.
*
* Class APIAccessExample
*/
class APIAccessExample
{
const PARAM_TOKEN = 'Authorization';
const PARAM_DATE = 'AuthDate';
private $apiEndpoint = "https://acme.editoreye.com/api";
private $privateKey;
private $publicKey;
/**
* @param $privateKey
* @param $publicKey
*/
public function __construct($privateKey, $publicKey, $endpoint = null)
{
$this->privateKey = $privateKey;
$this->publicKey = $publicKey;
if ($endpoint) {
$this->apiEndpoint = $endpoint;
}
}
/**
* Generates an parameter value to present for authorization; the date is hashed using the HMAC method against the
* private key. In summary, the encoded auth string is created as follows:
*
* Base64(HMAC-SHA1(UTF-8(Date), UTF-8(PrivateKey))
*
* @param DateTime $date
* @return string
*/
private function generateAuthString(\DateTime $date)
{
$encodedAuthString = base64_encode(hash_hmac('sha1', $date->format('c'), $this->privateKey, true));
return sprintf('%s:%s', $this->publicKey, $encodedAuthString);
}
/**
* Makes a call to the API on the path and using the parameters provided; the authorization parameters will be
* added
*
* @param $path
* @param array $params
* @return mixed
*/
public function call($path, $params = array())
{
$date = new \DateTime();
$params[self::PARAM_TOKEN] = $this->generateAuthString($date);
// the date string should be in ISO 8601 format; the date+time is checked, and the request rejected if outside
// a reasonable 'recency' boundary
$params[self::PARAM_DATE] = $date->format(\DateTime::ISO8601);
$url = sprintf('%s%s?%s', $this->apiEndpoint, $path, http_build_query($params));
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, true); // verbose to demonstrate headers
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$jsonResponse = curl_exec($curl);
curl_close($curl);
return $jsonResponse;
}
}
// keypair will be provided
$privateKey = "v9sd0dsds";
$publicKey = "InRnHGI0";
// endpoint
$endpoint = 'http://127.0.0.1:8000/api';
$api = new APIAccessExample($privateKey, $publicKey, $endpoint);
$json = $api->call('/test');
echo $json;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment