You are here

protected function GoogleAnalyticsCounterFeed::fetchToken in Google Analytics Counter 8.3

Authenticate with the Google API.

Parameters

string $client_id: Client ID for Web application from Google API Console.

string $client_secret: Client secret for Web application from Google API Console.

string $redirect_uri: Callback url.

null $refresh_token:

2 calls to GoogleAnalyticsCounterFeed::fetchToken()
GoogleAnalyticsCounterFeed::finishAuthentication in src/GoogleAnalyticsCounterFeed.php
Complete the authentication process.
GoogleAnalyticsCounterFeed::refreshToken in src/GoogleAnalyticsCounterFeed.php
Fetches a fresh access token with the given refresh token.

File

src/GoogleAnalyticsCounterFeed.php, line 160

Class

GoogleAnalyticsCounterFeed
Authorize access and request data from Google Analytics Core Reporting API.

Namespace

Drupal\google_analytics_counter

Code

protected function fetchToken($client_id, $client_secret, $redirect_uri, $refresh_token = NULL) {
  if ($refresh_token) {
    $params = [
      'client_id=' . $client_id,
      'client_secret=' . $client_secret,
      'refresh_token=' . $refresh_token,
      'grant_type=refresh_token',
    ];
  }
  else {
    $params = [
      'code=' . $_GET['code'],
      'grant_type=authorization_code',
      'redirect_uri=' . $redirect_uri,
      'client_id=' . $client_id,
      'client_secret=' . $client_secret,
    ];
  }
  try {
    $client = \Drupal::httpClient();
    $this->response = $client
      ->post(self::OAUTH2_TOKEN_URI, [
      'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
      ],
      'body' => implode('&', $params),
    ]);
  } catch (RequestException $e) {
    $this->response = $e
      ->getResponse();
  }
  if (substr($this->response
    ->getStatusCode(), 0, 1) == '2') {
    $decoded_response = json_decode($this->response
      ->getBody()
      ->__toString(), TRUE);
    $this->accessToken = $decoded_response['access_token'];
    $this->expiresAt = time() + $decoded_response['expires_in'];
    if (!$this->refreshToken) {
      $this->refreshToken = $decoded_response['refresh_token'];
    }
  }
}