You are here

public function SimpleFbConnectFbManager::getAccessTokenFromFb in Simple FB Connect 8.3

Reads user's access token from Facebook and set is as default token.

This method can only be called from route simple_fb_connect.return_from_fb because RedirectLoginHelper will use the URL parameters set by Facebook.

Return value

\Facebook\Authentication\AccessToken|null User's Facebook access token, if it could be read from Facebook. Null, otherwise.

File

src/SimpleFbConnectFbManager.php, line 117

Class

SimpleFbConnectFbManager
Contains all Simple FB Connect logic that is related to Facebook interaction.

Namespace

Drupal\simple_fb_connect

Code

public function getAccessTokenFromFb() {
  $helper = $this->facebook
    ->getRedirectLoginHelper();

  // URL where Facebook returned the user.
  $return_url = $this->urlGenerator
    ->generateFromRoute('simple_fb_connect.return_from_fb', [], [
    'absolute' => TRUE,
  ]);
  try {
    $access_token = $helper
      ->getAccessToken($return_url);
  } catch (FacebookResponseException $ex) {

    // Graph API returned an error.
    $this->loggerFactory
      ->get('simple_fb_connect')
      ->error('Could not get Facebook access token. FacebookResponseException: @message', [
      '@message' => json_encode($ex
        ->getMessage()),
    ]);
    return FALSE;
  } catch (FacebookSDKException $ex) {

    // Validation failed or other local issues.
    $this->loggerFactory
      ->get('simple_fb_connect')
      ->error('Could not get Facebook access token. Exception: @message', [
      '@message' => $ex
        ->getMessage(),
    ]);
  }

  // If login was OK on Facebook, we now have user's access token.
  if (isset($access_token)) {

    // All FB API requests use this token unless otherwise defined.
    $this->facebook
      ->setDefaultAccessToken($access_token);
    return $access_token;
  }

  // If we're still here, user denied the login request on Facebook.
  $this->loggerFactory
    ->get('simple_fb_connect')
    ->error('Could not get Facebook access token. User cancelled the dialog in Facebook or return URL was not valid.');
  return NULL;
}