PHP facebook SDK 4.0 login error

2019-03-04 17:35发布

问题:

I was looking for docs on official page but there is no anything helpful, so i build this code and it don't work.

    FacebookSession::setDefaultApplication('app-id', 'app-secret');
$helper = new \Facebook\FacebookRedirectLoginHelper('http://my-return-url');

if (isset($_SESSION['token'])) {
    $session = new FacebookSession($_SESSION['token']);
    if (!$session->validate()) {
        $session = null;
    }
} else {
    try {
        $session = $helper->getSessionFromRedirect();
    } catch(FacebookRequestException $ex) {
        die("Oops! :/");
    } catch(Exception $ex) {
        die($ex->message());
    }
}

if (isset($session)) {
    $_SESSION['token'] = $session->getToken();
    $session = new FacebookSession($session->getToken());

    $request = new FacebookRequest($session, 'GET', '/me');
    $response = $request->execute();
    $graphObject = $response->getGraphObject()->asArray();

    echo '<pre>';
    print_r($graphObject);
    echo '</pre>';
} else {
    echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';
}

I think the problem is in SDK but i'm not sure. I always get this error:

Fatal error: Uncaught exception 'Facebook\FacebookSDKException' with message 'Session has expired, or is not valid for this app.' in /var/www/html/Facebook/FacebookSession.php:238 Stack trace: #0 /var/www/html/Facebook/FacebookSession.php(216): Facebook\FacebookSession::validateSessionInfo(Object(Facebook\GraphSessionInfo), 'my-app-id', 'app-secret...') #1 /var/www/html/verify.php(98): Facebook\FacebookSession->validate() #2 {main} thrown in /var/www/html/Facebook/FacebookSession.php on line 238

I also tried through incognito mode tried setting up new app but always i get this error.

回答1:

I agree, FB documentations are pretty bad. Also, they are frequently changing thier SDK versions, a few days back they release v 4.0.5. Try this ->

<?php

// include required files form Facebook SDK

// added in v4.0.5
require_once( 'Facebook/FacebookHttpable.php' );
require_once( 'Facebook/FacebookCurl.php' );
require_once( 'Facebook/FacebookCurlHttpClient.php' );

// added in v4.0.0
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookOtherException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphSessionInfo.php' );

// added in v4.0.5
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;

// added in v4.0.0
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

// start session
session_start();

// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxx','yyy' );

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://yourwebsite.com/app/' );

// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
  // create new session from saved access_token
  $session = new FacebookSession( $_SESSION['fb_token'] );

  // validate the access_token to make sure it's still valid
  try {
    if ( !$session->validate() ) {
      $session = null;
    }
  } catch ( Exception $e ) {
    // catch any exceptions
    $session = null;
  }

} else {
  // no session exists

  try {
    $session = $helper->getSessionFromRedirect();
  } catch( FacebookRequestException $ex ) {
    // When Facebook returns an error
  } catch( Exception $ex ) {
    // When validation fails or other local issues
    echo $ex->message;
  }

}

// see if we have a session
if ( isset( $session ) ) {

  // save the session
  $_SESSION['fb_token'] = $session->getToken();
  // create a session using saved token or the new one we generated at login
  $session = new FacebookSession( $session->getToken() );

  // graph api request for user data
  $request = new FacebookRequest( $session, 'GET', '/me' );
  $response = $request->execute();
  // get response
  $graphObject = $response->getGraphObject()->asArray();

  // print profile data
  echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';

  // print logout url using session and redirect_uri (logout.php page should destroy the session)
  echo '<a href="' . $helper->getLogoutUrl( $session, 'http://yourwebsite.com/app/logout.php' ) . '">Logout</a>';

} else {
  // show login url
  echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends' ) ) . '">Login</a>';
}

Source



回答2:

Steps to avoiding PHP facebook SDK 4.0 login error

  1. First install composer in your PC if your are using windows OS.
  2. Download facebook SDK 4.0 and rename what ever you want (Like: fbsdk).
  3. Run Command prompt and locate your recently downloaded sdk folder.
  4. Check if there are composer.json file exist or not
  5. if composer.json file exist then type this command: composer install otherwise you have create new file composer.json in same folder with following code: { "require" : { "facebook/php-sdk-v4" : "4.0.*" } }
  6. If you will type correct command as above mentioned in line number 5 then you will get this message : Loading composer repositories with package information Installing dependencies (including require-dev).
  7. Create index.php file and include autoload.php top of the file.
  8. For example follow the sample codes for login with facebook

    session_start();
    
    require_once('/home3/users/public_html/fbsdk/vendor/autoload.php');
    
    use Facebook\FacebookSession;
    
    use Facebook\FacebookRequest;
    
    use Facebook\GraphUser;
    
    use Facebook\FacebookRequestException;
    
    use Facebook\FacebookRedirectLoginHelper;
    
    FacebookSession::setDefaultApplication(YOUR APP_ID, YOUR SECRET_KEY);
    
    $helper = new FacebookRedirectLoginHelper('http://example.com/fbsdk/login.php');
    
    if(isset($_SESSION['access_token'])) {
    
        $access_token = $_SESSION['access_token'];
    
        $session = new FacebookSession($access_token);
    
    } else {
    
        unset($_SESSION['access_token']);
    
        try {
    
            $session = $helper->getSessionFromRedirect();
    
            if($session)                    
                $_SESSION['access_token'] = $session->getToken();
    
        } catch(FacebookRequestException $ex) {
    
            // When Facebook returns an error
    
        } catch(Exception $ex) {
    
            // When validation fails or other local issues
    
        }
    
    }
    
    if ($session) {
    
        $request = new FacebookRequest($session, 'GET', '/me');
        $response = $request->execute();
        $graphObject = $response->getGraphObject();
    
        header('Location: ./home.php');
    
    } else {
    
        $loginUrl = $helper->getLoginUrl();
    
        header('Location: ' . $loginUrl);
    
    }