You are here

public static function Authorization::getToken in Twitter Profile Widget 3.x

Retrieve an 'Application Only' authorization token.

Parameters

string $key: The application consumer key.

string $secret: The application consumer secret.

Return value

bool Whether or not an authorization token was retrieved.

3 calls to Authorization::getToken()
SettingsForm::buildForm in src/Form/SettingsForm.php
Form constructor.
SettingsForm::submitForm in src/Form/SettingsForm.php
Form submission handler.
twitter_profile_widget_update_8101 in ./twitter_profile_widget.install
Save access token via new methodology.

File

src/Authorization.php, line 28

Class

Authorization
Handle Application Only authorization.

Namespace

Drupal\twitter_profile_widget

Code

public static function getToken($key, $secret) {
  $client = new Client([
    'base_uri' => self::BASE_URI,
    'auth' => [
      $key,
      $secret,
    ],
  ]);
  $options = [
    'form_params' => [
      'grant_type' => 'client_credentials',
    ],
  ];
  try {
    $response = $client
      ->post('/oauth2/token', $options);
    $body = json_decode($response
      ->getBody(), TRUE);
    \Drupal::state()
      ->set('twitter_api_access_token', $body['access_token']);

    // Invalidate the cache so that potentially broken widgets now display.
    Cache::invalidateTags([
      'twitter_profile_widget',
    ]);
    \Drupal::logger('twitter_profile_widget')
      ->error('Refreshed Twitter API token.');
  } catch (RequestException $e) {
    if ($e
      ->hasResponse()) {
      $messenger = \Drupal::messenger();
      $messenger
        ->addMessage($e
        ->getResponse()
        ->getBody()
        ->getContents(), 'error');
      \Drupal::logger('twitter_profile_widget')
        ->error(Psr7\str($e
        ->getResponse()));
      return FALSE;
    }
  }
  return TRUE;
}