Facebook PHP SDK: Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user

facebookfacebook-php-sdk

I am using the PHP SDK to handle my Facebook connects. Everything was working fine for some time but my script suddenly stopped working. Here is what happens:

$facebook = new Facebook(array('appId' => $app_id, 'secret' => $app_secret, 'cookie' => true));

$user = $facebook->getUser();

if ($user) {

    $permissions = $facebook->api('/me/permissions');

} else {

    $params = array();
    $params['scope'] = 'publish_actions,user_photos';
    header('Location: ' . $facebook->getLoginUrl($params));
    exit();

}

Returns: Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.

The error is caused by the line

$permissions = $facebook->api('/me/permissions');

Any suggestions?

Best Answer

Always check exceptions! Here's a quick example: https://developers.facebook.com/docs/reference/php/facebook-api/

$user returns a user ID for the current user, however, that doesn't guarantee that the user didn't log out meanwhile or that his token is still active. So instead of just relying on this because you got a user_id, check for exceptions. You can either ask the user to click Login again or simply redirect the user to the login page automatically if an exception occurs.