You are here

protected function CommerceGuysMarketplaceManagerBase::getAccessToken in Commerce Guys Marketplace 7

Returns an OAuth2 access token for communicating with the remote API.

If there is no token, or the token is expired, performs an authorization grant request against the remote OAuth2 server.

Throws

CommerceGuysMarketplaceNoCredentialsException If the client credentials are empty.

CommerceGuysMarketplaceAuthorizationException If the authorization grant request failed.

1 call to CommerceGuysMarketplaceManagerBase::getAccessToken()
CommerceGuysMarketplaceAddonManager::getLicenses in includes/commerceguys_marketplace.addon.inc
Returns an array of addon licenses.

File

includes/commerceguys_marketplace.base.inc, line 74

Class

CommerceGuysMarketplaceManagerBase
Defines the base manager class for interacting with remote marketplace items.

Code

protected function getAccessToken() {
  if (empty($this->client)) {
    throw new CommerceGuysMarketplaceNoCredentialsException("Missing client credentials.");
  }
  $access_token = variable_get('commerceguys_marketplace_access_token', array());
  if (empty($access_token['token']) || $access_token['expires'] < time()) {
    $data = array(
      'grant_type' => 'client_credentials',
      'client_id' => $this->client['client_key'],
      'client_secret' => $this->client['client_secret'],
    );
    $options = array(
      'method' => 'POST',
      'data' => http_build_query($data),
      'headers' => array(
        'Content-Type' => 'application/x-www-form-urlencoded',
      ),
    );
    $response = drupal_http_request(COMMERCEGUYS_MARKETPLACE_URL . '/oauth2/token', $options);
    $result = json_decode($response->data);

    // Handle errors
    if ($response->code != 200 || isset($result->error)) {
      throw new CommerceGuysMarketplaceAuthorizationException($result->error_description);
    }
    $access_token = array(
      'token' => $result->access_token,
      'expires' => time() + $result->expires_in,
    );
    variable_set('commerceguys_marketplace_access_token', $access_token);
  }
  return $access_token;
}