You are here

public function InstagramAuthController::accessToken in Social Feed 8

Get an Instagram access token.

1 string reference to 'InstagramAuthController::accessToken'
socialfeed.routing.yml in ./socialfeed.routing.yml
socialfeed.routing.yml

File

src/Controller/InstagramAuthController.php, line 52

Class

InstagramAuthController
Class InstagramAuthController.

Namespace

Drupal\socialfeed\Controller

Code

public function accessToken() {
  $code = $this->currentRequest->query
    ->get('code');
  $message = 'Something went wrong. The access token could not be created.';
  $token = '';
  if ($code) {
    $config = $this->configFactory
      ->getEditable('socialfeed.instagramsettings');
    $instagram = new InstagramBasicDisplay([
      'appId' => $config
        ->get('client_id'),
      'appSecret' => $config
        ->get('app_secret'),
      'redirectUri' => Url::fromRoute('socialfeed.instagram_auth', [], [
        'absolute' => TRUE,
      ])
        ->toString(),
    ]);

    // Get the short lived access token (valid for 1 hour)
    $token = $instagram
      ->getOAuthToken($code, TRUE);

    // Exchange this token for a long lived token (valid for 60 days)
    if ($token) {
      $token = $instagram
        ->getLongLivedToken($token, TRUE);
      $config
        ->set('access_token', $token);
      $config
        ->set('access_token_date', time());
      $config
        ->save();
      $message = 'Your Access Token has been generated and saved.';
    }
  }
  $build = [
    '#markup' => $this
      ->t($message) . ' ' . $token,
  ];
  return $build;
}