Search code examples
phpjavascriptsessionfacebook-php-sdkfacebook-oauth

Is the FB PHP SDK's getAccessToken() a reliable way to retrieve a user's auth token?


So I have a FB app and in some situations I need my Javascript to load content into a div using a php file that lives in the same domain as index.php. For some of these I like to make sure that the user is still valid and/or have need of an auth token and FB user id. I achieved this by making creating an instance of the FB PHP SDK in the php file being ajax injected by the javascript and using getUser() and getAccessToken(). I have noticed, however, that sometimes inexplicably the getAccessToken() call will fail and report that it needs a valid access token to perform the action.

Is getAccessToken() a reliable (or even ideal) way to ensure a user is logged into FB or should I be doing something else (e.g. storing the access token I parse from the signed request in Javscript and passing it as a variable to the php files I am injecting)? Thanks.


Solution

  • Most reliable would probably be to get their details. I have, in hte past, had an instance of "getUser" return true, but the user has not actually logged on. So now I also get all their details and this works more reliably:

    $facebook = new Facebook(array(
                                'appId' => FB_APP_ID,
                                'secret' => FB_APP_SECRET,
                                'cookie' => true
                        ));
    $FB_UID=false;
    try {
        $FB_UID = $facebook->getUser();
        // This verifies the user is actually logged in. teh above can return "true" but the following will crap out and throw exception
        $FB_me = $facebook->api('/me');  // 'birthday'
        // Not needed:
        // $FB_token = $facebook->getAccessToken();
    
    } catch (FacebookApiException $e) {
        $FB_UID = false;
        $FB_me = false;
        // $FB_token = false;
    }