Search code examples
facebookfacebook-graph-apibrowseraccess-tokenfacebook-access-token

Facebook invalid access token after clearing cache&cookies


My app is not loaded and I get the erro below in these two scenarios:

a) The first time I access my app after clearing cache & cookies, or from a PC I haven't used before, with any browser.

b) When USER A tries to access the app straight after USER B has logged out from the app (and Facebook), from the same PC and browser, without clearing cache or cookies.

However, when I press F5 to update the webpage, it is working properly.

This is the error I get on the log file:

{"readyState":4,"responseText":"Invalid access token","status":200,"statusText":"OK"}

User validation code:

require_once(dirname(__DIR__).'/lib/common/AppInfo.php');
require_once(dirname(__DIR__).'/sdk/src/facebook.php');
require_once(dirname(__DIR__).'/lib/logic/UsersLogic.php');
require_once(dirname(__DIR__).'/lib/common/Log.php');

if (substr(AppInfo::getUrl(), 0, 8) != 'https://' && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
    header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

try {
    $facebook = new Facebook(array(
            'appId'  => AppInfo::appID(),
            'secret' => AppInfo::appSecret(),
    ));
    $user_id = $facebook->getUser();
} catch (Exception $e) {
    exit("Error getting facebook data");
}

if ($user_id) {
    try {
        $basic = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        if (!$facebook->getUser()) {
            exit("Invalid access token");
        }
    }
    if($basic==null){
        exit("Application not installed");
    }
    $user=UsersLogic::getUser($user_id);
    if($user==null){
        exit("User not registered in database");
    }

}
else{
    exit("No user logged");
}

Any ideas why does it happen? Perhaps I should force to request a new user access token? (how)

THANKS


Solution

  • This is totally expected - in the first scenario there are not cookies, no knowledge of who the user is, and hence no way of getting hold of a valid access token, and in the second scenario, logging out from Facebook (or de-authorizing your app) will cause any access tokens you have to be invalidated.

    But that error, that is from the client side code right? In that case, you need to wrap the code you're using with FB.getLoginStatus or similar so that you don't run it unless you actually have the needed access token.