Skip to content

Instantly share code, notes, and snippets.

@stuartwilsondev
Created October 21, 2015 10:55
Show Gist options
  • Save stuartwilsondev/e003a864872de6aa64cb to your computer and use it in GitHub Desktop.
Save stuartwilsondev/e003a864872de6aa64cb to your computer and use it in GitHub Desktop.
<?php
/**
* Example class demonstrating how to create the authorization headers for accessing the Publisher API.
*
* Class APIAccessExample
*/
class APIAccessExample
{
private $apiEndpoint;
const PARAM_TOKEN = 'Authorization';
const PARAM_DATE = 'AuthDate';
/**
* @param $privateKey
* @param $publicKey
* @param $endpoint
*/
public function __construct($privateKey, $publicKey, $endpoint)
{
$this->privateKey = $privateKey;
$this->publicKey = $publicKey;
$this->apiEndpoint = $endpoint;
}
/**
* @param DateTime $date
* @return array
*/
private function createAuthHeader(\DateTime $date)
{
$encodedAuthString = base64_encode(hash_hmac('sha1', $date->format(\DateTime::ISO8601), $this->privateKey, true));
$headers = array(
'Content-length: 0',
'Accept: application/json',
'Authorization: ' . sprintf('%s:%s', $this->publicKey, $encodedAuthString),
'AuthDate: ' . utf8_encode($date->format(\DateTime::ISO8601)),
);
return $headers;
}
/**
* Makes a call to the API on the path provide using the headers
*
* @param $path
* @return mixed
*/
public function call($path)
{
$date = new \DateTime();
$url = sprintf('%s/%s', $this->apiEndpoint, $path);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->createAuthHeader($date));
$jsonResponse = curl_exec($curl);
curl_close($curl);
return $jsonResponse;
}
}
//Example usage
// keypair will be provided
$privateKey = "privatekey";
$publicKey = "publickey";
// endpoint
$endpoint = 'http://api-url';
$api = new APIAccessExample($privateKey, $publicKey, $endpoint);
$json = $api->call('createUserSubscription');
echo $json;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment