You are here

public function Callback::getToken in Instagram API 8

Fetch Instagram Token.

1 call to Callback::getToken()
Callback::callbackUrl in src/Controller/Callback.php
Callback URL for Instagram Auth.

File

src/Controller/Callback.php, line 82

Class

Callback
Class Instagram Callback Controller.

Namespace

Drupal\instagram_api\Controller

Code

public function getToken($code) {

  // Guzzle Client.
  $guzzleClient = new GuzzleClient([
    'base_uri' => $this->config
      ->get('api_uri'),
  ]);

  // Params.
  $parameters = [
    'client_id' => $this->config
      ->get('client_id'),
    'client_secret' => $this->config
      ->get('client_secret'),
    'redirect_uri' => Url::fromUri('internal:/instagram_api/callback', [
      'absolute' => TRUE,
    ])
      ->toString(),
    'grant_type' => 'authorization_code',
    'code' => $code,
  ];
  try {
    $response = $guzzleClient
      ->request('POST', 'access_token', [
      'form_params' => $parameters,
    ]);
    if ($response
      ->getStatusCode() == 200) {

      // TODO Add debugging options.
      // kint($response->getBody()->getContents());
      $contents = $response
        ->getBody()
        ->getContents();
      return Json::decode($contents)['access_token'];
    }
  } catch (GuzzleException $e) {

    // TODO Add debugging options.
    // kint($e);
    $this->loggerFactory
      ->get('instagram_api')
      ->error("@message", [
      '@message' => $e
        ->getMessage(),
    ]);
    return FALSE;
  }
}