Skip to content

Commit

Permalink
Implemented missing Harvest stuff and added example
Browse files Browse the repository at this point in the history
  • Loading branch information
Marc Neuhaus committed Aug 19, 2014
1 parent 2d0da3d commit 2dafb0a
Show file tree
Hide file tree
Showing 3 changed files with 159 additions and 6 deletions.
74 changes: 74 additions & 0 deletions examples/harvest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

/**
* Example of retrieving an authentication token of the harvest service
*
* PHP version 5.4
*
* @author David Desberg <[email protected]>
* @author Pieter Hordijk <[email protected]>
* @copyright Copyright (c) 2012 The authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/

use OAuth\Common\Consumer\Credentials;
use OAuth\Common\Storage\Session;
use OAuth\Common\Token\Exception\ExpiredTokenException;
use OAuth\OAuth2\Service\Harvest;

/**
* Bootstrap the example
*/
require_once __DIR__ . '/bootstrap.php';

$serviceName = 'Harvest';
$scopes = array();

// Session storage
$storage = new Session();

// Setup the credentials for the requests
$credentials = new Credentials(
$servicesCredentials['harvest']['key'],
$servicesCredentials['harvest']['secret'],
$currentUri->getAbsoluteUri()
);

// Instantiate the Harvest service using the credentials, http client and storage mechanism for the token
/** @var $harves Harves */
$harvest = $serviceFactory->createService($serviceName, $credentials, $storage, $scopes);

if (!empty($_GET['clearToken'])) {
// Clear the current AccessToken and go back to the Beginning.
$storage->clearToken($serviceName);
header('Location: ' . $currentUri->getAbsoluteUri());

} elseif ($storage->hasAccessToken($serviceName)) {
// fetch the accessToken for the service
$accessToken = $storage->retrieveAccessToken($serviceName);

// is the accessToken expired? then let's refesh it!
if ($accessToken->isExpired() === TRUE) {
$harvest->refreshAccessToken($accessToken);
}

// use the service with the valid access token to fetch my email
$result = json_decode($harvest->request('account/who_am_i'), true);
echo 'The email on your harvest account is ' . $result['user']['email'];

$url = $currentUri->getRelativeUri() . '?clearToken=1';
echo " <a href='$url'>Click here to clear the current access token</a>";

} elseif (!empty($_GET['code'])) {
// This was a callback request from harvest, get the token
$harvest->requestAccessToken($_GET['code']);
header('Location: ' . $currentUri->getAbsoluteUri());

} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') {
// Redirect to the Authorization uri
$url = $harvest->getAuthorizationUri();
header('Location: ' . $url);
} else {
$url = $currentUri->getRelativeUri() . '?go=go';
echo "<a href='$url'>Login with Harvest!</a>";
}
7 changes: 7 additions & 0 deletions src/OAuth/Common/Token/AbstractToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,11 @@ public function setRefreshToken($refreshToken)
{
$this->refreshToken = $refreshToken;
}

public function isExpired()
{
return ($this->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES
&& $this->getEndOfLife() !== TokenInterface::EOL_UNKNOWN
&& time() > $this->getEndOfLife());
}
}
84 changes: 78 additions & 6 deletions src/OAuth/OAuth2/Service/Harvest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

namespace OAuth\OAuth2\Service;

use OAuth\OAuth2\Token\StdOAuth2Token;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Token\TokenInterface;
use OAuth\OAuth2\Token\StdOAuth2Token;

class Harvest extends AbstractService
{
Expand All @@ -23,8 +24,32 @@ public function __construct(
parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri);

if (null === $baseApiUri) {
$this->baseApiUri = new Uri('https://api.github.com/');
$this->baseApiUri = new Uri('https://api.harvestapp.com/');
}
}

/**
* {@inheritdoc}
*/
public function getAuthorizationUri(array $additionalParameters = array())
{
$parameters = array_merge(
$additionalParameters,
array(
'client_id' => $this->credentials->getConsumerId(),
'redirect_uri' => $this->credentials->getCallbackUrl(),
'state' => 'optional-csrf-token',
'response_type' => 'code',
)
);

// Build the url
$url = clone $this->getAuthorizationEndpoint();
foreach ($parameters as $key => $val) {
$url->addToQuery($key, $val);
}

return $url;
}

/**
Expand Down Expand Up @@ -66,7 +91,8 @@ protected function parseAccessTokenResponse($responseBody)

$token = new StdOAuth2Token();
$token->setAccessToken($data['access_token']);
$token->setEndOfLife($data['expires_in']);
$token->setLifetime($data['expires_in']);
$token->setRefreshToken($data['refresh_token']);

unset($data['access_token']);

Expand All @@ -75,11 +101,57 @@ protected function parseAccessTokenResponse($responseBody)
return $token;
}

/**
* Refreshes an OAuth2 access token.
*
* @param TokenInterface $token
*
* @return TokenInterface $token
*
* @throws MissingRefreshTokenException
*/
public function refreshAccessToken(TokenInterface $token)
{
$refreshToken = $token->getRefreshToken();

if (empty($refreshToken)) {
throw new MissingRefreshTokenException();
}

$parameters = array(
'grant_type' => 'refresh_token',
'type' => 'web_server',
'client_id' => $this->credentials->getConsumerId(),
'client_secret' => $this->credentials->getConsumerSecret(),
'refresh_token' => $refreshToken,
);

$responseBody = $this->httpClient->retrieveResponse(
$this->getAccessTokenEndpoint(),
$parameters,
$this->getExtraOAuthHeaders()
);
$token = $this->parseAccessTokenResponse($responseBody);
$this->storage->storeAccessToken($this->service(), $token);

return $token;
}

/**
* @return array
*/
protected function getExtraOAuthHeaders()
{
return array('Accept' => 'application/json');
}

/**
* Return any additional headers always needed for this service implementation's API calls.
*
* @return array
*/
protected function getExtraApiHeaders()
{
return array('Accept' => 'application/json');
}
}

0 comments on commit 2dafb0a

Please sign in to comment.