Skip to content

Instantly share code, notes, and snippets.

@sameg14
Created March 4, 2015 22:24
Show Gist options
  • Save sameg14/73ab454a0cfb6f932b46 to your computer and use it in GitHub Desktop.
Save sameg14/73ab454a0cfb6f932b46 to your computer and use it in GitHub Desktop.
Oauth3
<?php
/**
* Get access token via OAuth2 three legged dance
* @see https://sagedocs.wholelabs.com/wiki/index.php?title=Sage-api/v2/authorize
* @throws Exception
* @return string
* @todo: Doc #experiment
*/
protected function getAccessToken()
{
$code = null;
$client = $this->getClient();
$url = $this->baseUrl . '/v' . $this->apiVersion
. '/oauth20/authorize?response_type=code&redirect_uri='
. urlencode($this->baseUrl) . '&client_id=' . $this->apiKey;
try {
$client->get($url);
} catch (ClientException $e) {
$code = $this->extractCode($e->getMessage());
} catch (\Exception $e) {
throw $e;
}
if (empty($code)) {
throw new Exception('Cannot initiate authentication via GET');
}
// Create a base64 authorization code
$authorizationCode = 'Basic ' . base64_encode($this->apiKey . ':' . $this->apiSecret);
$response = $client->post(
$this->baseUrl . '/v' . $this->apiVersion . '/oauth20/token',
array(
'headers' => array(
'Authorization' => $authorizationCode,
'Content-Type' => 'application/x-www-form-urlencoded',
'response_content_type' => 'application/json',
'hdr_auth_code' => $authorizationCode
),
'body' => array(
'code' => $code,
'grant_type' => 'authorization_code',
'response_type' => 'code',
'redirect_uri' => urlencode($this->baseUrl . '/v' . $this->apiVersion)
)
)
);
$body = $response->getBody();
pre($body, '$body');
pre($code);
}
/**
* Extract the code HTTP query string parameter from the error message guzzle returns
* @param string $message Message to extract the auth code from an exception message
* @throws Exception
* @return string
*/
protected function extractCode($message)
{
$url = null;
$parts = explode(" ", $message);
// Doing it this way for BC reasons, I would have rather used array_map()
foreach ($parts as $part) {
if (preg_match('/^(http|https):\/\//', $part)) {
$url = $part;
break;
}
}
if (empty($url)) {
throw new Exception('Cannot initiate authentication');
}
$parts = explode("code=", $url);
return array_pop($parts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment