Login and user profile data retrieval with Facebook PHP SDK V4

The Facebook PHP API has been revised dramatically. At the time of this writing it still appears to undergo significant changes so your mileage may vary depending on the revision of the SDK you downloaded. The SDK requires PHP version 5.4 or higher.

Either download the ZIP archive or use Composer to add the SDK to your project. I used Composer with Netbeans, resulting in a source tree in vendor/facebook/php-sdk-v4/src.

composer.json:

{
  "require" : {
    "facebook/php-sdk-v4" : "4.0.*"
  }
}

I tried out several approaches (including one with FacebookCanvasLoginHelper()) and eventually I only fully succeeded to log in with all required permissions using FacebookRedirectLoginHelper().

In the example we’ll retrieve the user’s profile and friends list after a successful login. I needed the following includes to do so:

require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/GraphObject.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/GraphSessionInfo.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/Entities/AccessToken.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/Entities/SignedRequest.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookResponse.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/HttpClients/FacebookCurl.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/HttpClients/FacebookCurlHttpClient.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookSignedRequestFromInputHelper.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookSession.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookSDKException.php');
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequestException.php');
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookServerException.php');
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequest.php');
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/GraphObject.php');
require_once( 'vendor/facebook/php-sdk-v4/src/Facebook/GraphUser.php');

And use the following namespaces:

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\GraphUser;

We’ll set up a Facebook session as well as a PHP user session to store the Facebook API access token in $_SESSION for reuse. So first start a user session and initialize the Facebook app:

session_start();
 
FacebookSession::setDefaultApplication(APP_ID, APP_SECRET);
$helper = new FacebookRedirectLoginHelper('https://www.yourdomain.com/yourapp/');

If we have an access token in our user session we’ll create a new Facebook session using that token:

if ($_SESSION['fb_token']) {
 
    $session = new FacebookSession($_SESSION['fb_token']);
 
    try {
        if (!$session->validate()) {
            $session = null;
        }
    } catch (Exception $e) {
        $session = null;
    }
}

If we have nothing we’ll attempt to retrieve it from the login helper:

if (!$session) {
 
    try {
        $session = $helper->getSessionFromRedirect();
    } catch (FacebookRequestException $e) {
        print_r($e);
    } catch (Exception $e) {
        print_r($e);
    }
}

If there’s still no Facebook session we need to redirect the user to the login URL:

if ($session) {
    // Store the access token here:
    $_SESSION['fb_token'] = $session->getToken();
    // User logged in. App logic goes here...
} else {
    $url = $helper->getLoginUrl(array('publish_stream', 'manage_notifications', 'user_friends'));
    echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}

Now we can use the API to retrieve the user profile as a GraphUser object:

try {
 
    $user_profile = (new FacebookRequest($session, 'GET', '/me'))
            ->execute()->getGraphObject(GraphUser::className());
 
    echo "Name: " . $user_profile->getName();
    var_dump($user_profile);
} catch (FacebookRequestException $e) {
 
    echo "Exception occurred, code: " . $e->getCode();
    echo "with message: " . $e->getMessage();
}

Some members can be accessed over getters and setters. You may want to var_dump the object and inspect its backedData member containing properties that can be retrieved with getProperty().

$user_id = $user_profile->getId();
 
$user_locale = $user_profile->getProperty('locale');

To retrieve the user’s friends first make sure you’ve included ‘user_friends’ in the scope at login above. Make the API call and extract the wanted data from the response to obtain an array of GraphUser objects:

try {
 
    $friends = (new FacebookRequest($session, 'GET', '/me/friends'))
            ->execute()->getGraphObject()->asArray();
    $friendGraphUsers = $friends[1];
} catch (FacebookRequestException $e) {
 
    echo "Exception occurred, code: " . $e->getCode();
    echo "with message: " . $e->getMessage();
}

Leave a Reply