Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - How to properly handle session and access token with Facebook PHP SDK 3.0?

In the PHP 3.0 SDK there is no getSession() or any session handling from outside the Facebook api available. Some days ago the developers of facebook have also somehow updated the JavaScript sdk, according to this blog entry and this bug report.

Within the last few days, a change was introduced into the hosted JS SDK which broke all compatility between it and the current PHP SDK (2.x and 3.x). Developers who utilize both the JS and PHP SDK on their websites are likely to see server-side API failure.

However, I don't know if that really effects my problem. Like in this question's answer I am retrieving the access token of the OAuth dialog with PHP and save the new access token in the session.

Current workaround

The following code shows how I am handling this sessions. $_REQUEST['session'] is the content of the response of the OAuth dialog.

if(isset($_REQUEST['session'])) {

    $response = json_decode(stripslashes($_REQUEST['session']), true);

    if(isset($response['access_token'])) {
        $this->api->setAccessToken($response['access_token']);
        $_SESSION['access_token'] = $this->api->getAccessToken();
    }

}
elseif(isset($_SESSION['access_token']) && ! isset($_REQUEST['signed_request'])) 
    $this->api->setAccessToken($_SESSION['access_token']);
elseif(isset($_REQUEST['signed_request'])) {
    Session::invalidate('fbuser');
    $_SESSION['access_token'] = '';
}

Here is how I handle the user data:

try {
    $this->user = Session::getVar('fbuser');
    if ($this->user === false || is_null($this->user)) {
        $facebookUser = $this->api->api('me?fields=id,name,first_name,last_name');
        $this->user = new FBUserModel(array('fbId' => $facebookUser['fbId'], ...));
        Session::setVar('fbuser', $this->user);
    }
}


The Problem

Everything looks fine while testing. Only once an error occured: the first time after permission was set. Now, since the app is online, it seems as if the error occurs on average with every second user in

$facebookUser = $this->api->api('me?fields=id,name,first_name,last_name');

with the error:

An active access token must be used to query information about the current user.


Question

So why is this happening? It is very hard to debug since the error seems to only occur when a user enters the app the first time, after the app authentication and the access token has changed. And even that is not happening every time. How should I handle the session and access token right with the new PHP SDK?

Any help would be highly appreciatied!


Edit

I found out that there are some IE issues with cookies/session inside an iFrame. As seen in this blog post. With that hint and some further research I added the following lines in my bootstrap:

ini_set('session.use_trans_sid', 1);
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

Now its much better, but the information from about 2 of 50 users get lost between the steps landing page (authentication) -> formular -> and registration. So there is still something I missed.


Edit 2

I edited my user handling from

if ($this->user === false || is_null($this->user)) {
    // get user data
}

to

if ((is_object($this->user) && $this->user->fbId == '') || $this->user === false || is_null($this->user)) {
    // get user data
}

This seems to help a little bit. I think the main problem is somewhere in my session.

Furthermore I added a try/catch block to see if somewhere in my app a Facebook OAuthException is thrown. If this is the case, I redirect the top location to the Facebook Page and Tab to get a new signed request. Though this might help solve this problem, I want to prevent my app from having to redirect the user.


Edit 3

After some days of intense debugging and logging I found out, that the $_REQUEST['session'] coming from the FB.ui permissions.request method is empty infrequently.

Here is how I handle it:

This is the stuff I always included:

FB.provide("UIServer.Methods", {'permissions.request': {size : {width: 575, height: 300}, url: 'connect/uiserver.php', transform : FB.UIServer.genericTransform}});

And this function is called on form submit. Always worked for me, but somehow it still sends the form although session == ''.

function getPermission(form) {

    session = $('#' + $(form).attr('id') + ' input[name="session"]');

    if($(session).val() != '') {
        form.submit();
        return;
    }

    FB.ui({method: "permissions.request", "perms": 'user_photos'}, function callback(info){
        if(info.status=='connected' && info.session !== null) {
            $(session).val(JSON.stringify(info.session));
            form.submit();
        }
    });
    return;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm using now PHP SDK 3.x without any problem.

Naitik the class author removed the getSession() function, and now if you want to know if the user is authenticated or not, use getUser().

For Access token, it's very simple, use this function getAccessToken(), and you'll get the access token to make Graph or Rest API calls.

$user = $facebook->getUser();

if ($user) {
//USER Logged-In
}
else {
//USER not Logged-In
}

//TO GET ACCESS TOKEN
$access_token = $facebook->getAccessToken();


//MAKE AN API CALL WITH IT
$user_info = $facebook->api('me?fields=id,name,first_name,last_name&access_token='.$access_token);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...