You are here

protected function GoogleAnalyticsReportsApiFeed::fetchToken in Google Analytics Reports 7.3

Authenticate with the Google Analytics API.

Parameters

String $client_id:

String $client_secret:

String $refresh_token:

Return value

GAFeed

2 calls to GoogleAnalyticsReportsApiFeed::fetchToken()
GoogleAnalyticsReportsApiFeed::finishAuthentication in google_analytics_reports_api/google_analytics_reports_api.lib.inc
Complete the authentication process.
GoogleAnalyticsReportsApiFeed::refreshToken in google_analytics_reports_api/google_analytics_reports_api.lib.inc
Fetches a fresh access token with the given refresh token.

File

google_analytics_reports_api/google_analytics_reports_api.lib.inc, line 108
Provides the Google Analytics Reports API Feed object type and associated methods.

Class

GoogleAnalyticsReportsApiFeed
GoogleAnalyticsReportsApiFeed 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 ($this->response->code == '200') {
    $decoded_response = json_decode($this->response->data, TRUE);
    $this->accessToken = $decoded_response['access_token'];
    $this->expiresAt = time() + $decoded_response['expires_in'];
    if (!$refresh_token) {
      $this->refreshToken = $decoded_response['refresh_token'];
    }
  }
  else {
    $error_vars = array(
      '@code' => $this->response->code,
      '@message' => $this->response->error,
      '@details' => print_r(drupal_json_decode($this->response->data), TRUE),
    );
    $this->error = t('<strong>Code</strong>: @code, <strong>Error</strong>: @message, <strong>Message</strong>: <pre>@details</pre>', $error_vars);
    watchdog('google analytics reports api', '<strong>Code</strong>: @code, <strong>Error</strong>: @message, <strong>Message</strong>: <pre>@details</pre>', $error_vars, WATCHDOG_ERROR);
  }
}