You are here

public function ApiAuthorize::getToken in FormAssembly 8

Retrieve an active access_token.

Either returns the current valid token or if the expire date is passed then the renewal process is used to obtain a new token.

Return value

string An access token if available or an empty string.

Throws

\Exception Any exception passed through from the Oauth request.

File

src/ApiAuthorize.php, line 104

Class

ApiAuthorize
Service class for FormAssembly API: Handles authorization.

Namespace

Drupal\formassembly

Code

public function getToken() {

  /** @var \League\OAuth2\Client\Token\AccessToken $accessToken */
  $accessToken = $this->state
    ->get('fa_form.access_token');
  if ($accessToken
    ->hasExpired()) {

    // Get the provider.
    $provider = $this
      ->getOauthProvider();

    // Try to get an access token using the authorization code grant.
    try {
      $newAccessToken = $provider
        ->getAccessToken('refresh_token', [
        'refresh_token' => $accessToken
          ->getRefreshToken(),
      ]);
      $this->state
        ->set('fa_form.access_token', $newAccessToken);
    } catch (\Exception $e) {
      $this->logger
        ->critical('FormAssembly new token request failed with Exception: %exception_type.', [
        '%exception_type' => get_class($e),
      ]);
      throw $e;
    }
    return $newAccessToken
      ->getToken();
  }
  return $accessToken
    ->getToken();
}