You are here

public function InstagramAccount::refreshToken in Instagram Feeds 8

Tries to refresh long-lived Instagram access token.

Parameters

\GuzzleHttp\Client $http_client: Guzzle HTTP Client.

bool $save: Save entity or not after token has been refreshed successfully.

Return value

bool True if success, false otherwise.

Throws

\Exception

Overrides InstagramAccountInterface::refreshToken

File

src/Entity/InstagramAccount.php, line 278

Class

InstagramAccount
Defines the instagram_account entity class.

Namespace

Drupal\instagram_feeds\Entity

Code

public function refreshToken(Client $http_client, $save = FALSE) : bool {
  $time = \Drupal::time();

  // Token can be refreshed only once per day. It lives 60 days. Expired
  // token cannot be refreshed anymore. 60 days - 1 day = 59 days.
  if (!$this
    ->tokenIsValid() || (int) $this
    ->get('token_expiration')
    ->first()
    ->getString() - 5097600 >= $time
    ->getCurrentTime()) {
    return FALSE;
  }
  try {
    $response = $http_client
      ->get(self::INSTAGRAM_GRAPH_ENDPOINT . '/refresh_access_token?' . http_build_query([
      'grant_type' => 'ig_refresh_token',
      'access_token' => $this
        ->getToken(),
    ]));
    $body = $this
      ->extractInstagramData($response);
    $this
      ->set('token', $body['access_token']);
    $this
      ->set('token_expiration', $body['expires_in'] + $time
      ->getCurrentTime());
  } catch (\Exception $e) {
    \Drupal::logger('instagram_feeds')
      ->error('An error Occurred when refreshing Instagram token for account @name: <br />@error', [
      '@name' => $this
        ->label(),
      '@error' => $e
        ->getMessage(),
    ]);
  }
  if (!$this
    ->isNew() && $save) {
    return (bool) $this
      ->save();
  }
  return TRUE;
}