Search code examples
phpfacebooksessionfacebook-access-tokenfacebook-sdk-4.0

Facebook PHP SDK v4 get current accessToken


I have no problem getting a FacebookSession with the getSessionFromRedirect() function, but I am having a problem returning a token from it.

Facebook\FacebookSession::setDefaultApplication(
    Config::get('api/facebook/app_id'), 
    Config::get('api/facebook/app_secret')
);

$fb = new Facebook\FacebookRedirectLoginHelper(Config::get('api/facebook/url'));

if(Session::exists(Config::get('session/facebook'))) {
    //echo Session::get(Config::get('session/facebook'));
    $session = Session::get(Config::get('session/facebook'));
} else {
    $session = $fb->getSessionFromRedirect();
    var_dump($session);
    //Session::put(Config::get('session/facebook'), $session->getToken());
}

if(isset($session)) {

    //Do Facebook stuff here

} else {
    $params = array(
        'scope' => 'email, user_birthday'
    );
    echo "<a href='".$fb->getLoginUrl($params)."'>Login</a>";
}

As you can see, I was playing around with the FacebookSession object like var_dumping it but I still can't seem to get a token. I've read the docs and the FacebookSession object has a getToken() function but it doesn't seem to be working for me.

Here is what I get back after dumping the session

object(Facebook\FacebookSession)#9 (2) { ["accessToken":"Facebook\FacebookSession":private]=> object(Facebook\Entities\AccessToken)#4 (3) { ["accessToken":protected]=> string(220) "*INSERT TOKEN HERE, THIS WAS REPLACED FOR THE QUESTION*" ["machineId":protected]=> NULL ["expiresAt":protected]=> NULL } ["signedRequest":"Facebook\FacebookSession":private]=> NULL }

Solution

  • I actually ended up figuring it out. I already had an init file that ran session_start() for me so that wasn't it.

    Facebook\FacebookSession::setDefaultApplication(
        Config::get('api/facebook/app_id'), 
        Config::get('api/facebook/app_secret')
    );
    
    $fb = new Facebook\FacebookRedirectLoginHelper(Config::get('api/facebook/url'));
    
    if(Session::exists(Config::get('session/facebook'))) {
        $session = new Facebook\FacebookSession(Session::get(Config::get('session/facebook')));
    } else {
        $session = $fb->getSessionFromRedirect();
    }
    
    if(isset($session)) {
        if(!Session::exists(Config::get('session/facebook'))) {
            Session::put(Config::get('session/facebook'), $session->getToken());
        }
        //Do Facebook stuff here
    
    } else {
        $params = array(
            'scope' => 'email, user_birthday'
        );
        echo "<a href='".$fb->getLoginUrl($params)."'>Login</a>";
    }
    

    Because the page didn't refresh, the $session variable wasn't a real object yet, I just had to place it once isset($session) was called