You are here

protected function GoogleAnalyticsCounterFeed::fetchToken in Google Analytics Counter 7.3

Authenticate with the Google API

Parameters

String $client_id:

String $client_secret:

String $refresh_token:

Return value

GAFeed

2 calls to GoogleAnalyticsCounterFeed::fetchToken()
GoogleAnalyticsCounterFeed::finishAuthentication in ./google_analytics_counter_oauth2.lib.inc
Complete the authentication process. We got here after being redirected from a successful authorization grant. Fetch the access token
GoogleAnalyticsCounterFeed::refreshToken in ./google_analytics_counter_oauth2.lib.inc
Fetches a fresh access token with the given refresh token.

File

./google_analytics_counter_oauth2.lib.inc, line 124
Provides the Google Analytics Counter Feed object type and associated methods. Most of the Google Analytics authentication process is taken over from http://drupal.org/project/google_analytics_reports because all we need here is its Google Analytics…

Class

GoogleAnalyticsCounterFeed
GoogleAnalyticsCounterFeed class to authorize access to and request data from the Google Analytics Core Reporting API.

Code

protected function fetchToken($client_id, $client_secret, $redirect_uri, $refresh_token = NULL) {
  if ($refresh_token) {
    $params = array(
      'client_id=' . $client_id,
      'client_secret=' . $client_secret,
      'refresh_token=' . $refresh_token,
      'grant_type=refresh_token',
    );
  }
  else {
    $params = array(
      'code=' . $_GET['code'],
      'grant_type=authorization_code',
      'redirect_uri=' . $redirect_uri,
      'client_id=' . $client_id,
      'client_secret=' . $client_secret,
    );
  }
  $data = implode('&', $params);
  $this->response = drupal_http_request(self::OAUTH2_TOKEN_URI, array(
    'headers' => array(
      'Content-Type' => 'application/x-www-form-urlencoded',
    ),
    'method' => 'POST',
    'data' => $data,
  ));
  if (substr($this->response->code, 0, 1) == '2') {
    $decoded_response = json_decode($this->response->data, true);
    $this->access_token = $decoded_response['access_token'];
    $this->expires_at = time() + $decoded_response['expires_in'];
    if (!$refresh_token) {
      $this->refresh_token = $decoded_response['refresh_token'];
    }
  }
  else {
    $error_msg = 'Code: !code - Error: !message - Message: !details';
    $error_vars = array(
      '!code' => $this->response->code,
      '!message' => $this->response->error,
      '!details' => strip_tags($this->response->data),
    );
    $this->error = t($error_msg, $error_vars);
    watchdog('Google Analytics Counter', $error_msg, $error_vars, WATCHDOG_ERROR);
  }
}