如何使用Facebook PHP SDK 3.0正确处理会话和访问令牌? [英] How to properly handle session and access token with Facebook PHP SDK 3.0?

查看:110
本文介绍了如何使用Facebook PHP SDK 3.0正确处理会话和访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP 3.0 SDK中,没有可以从Facebook api以外的任何 getSession()或任何会话处理。几天前,Facebook的开发人员也以某种方式更新了JavaScript sdk,根据 此博客条目 此错误报告


在过去几天内,更改为
引入托管的JS SDK
,破坏了所有兼容性它
和当前的PHP SDK(2.x和3.x)。
在他们的网站上使用JS和
PHP SDK的开发人员可能会看到
看到服务器端的API失败。


但是,我不知道这是否真的会影响我的问题。像 此问题的答案 我正在使用PHP检索OAuth对话框的访问令牌,并在会话中保存新的访问令牌。



当前解决方法



以下代码显示了我如何处理此会话。 $ _ REQUEST ['session'] 是OAuth对话框响应的内容。

 code> 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']))
$这 - > API-> setAccessToken($ _ SESSION [ 'ACCESS_TOKEN']);
elseif(isset($ _ REQUEST ['signed_request'])){
Session :: invalidate('fbuser');
$ _SESSION ['access_token'] ='';
}

以下是我如何处理用户数据:

  try {
$ this-> user = Session :: getVar('fbuser');
if($ this-> user === false || is_null($ this-> user)){
$ facebookUser = $ this-> api-> api('me?字段= ID,名字,名字,姓氏');
$ this-> user = new FBUserModel(array('fbId'=> $ facebookUser ['fbId'],...));
Session :: setVar('fbuser',$ this-> user);
}
}




问题



测试时,一切都看起来不错。只有一次发生错误:第一次设置了权限后的。现在,由于应用程序在线,似乎平均每个第二个用户在

  $ facebookUser = $这 - > API-> API( '我的字段= ID,名字,名字,姓氏?'); 

与错误:

 必须使用活动的访问令牌来查询有关当前用户的信息。 




问题



那么为什么会这样呢?这是很难调试,因为错误似乎只发生在用户第一次进入应用程序后,在应用程序认证和访问令牌已更改后。即使这样也没有发生。如何处理会话并使用新的PHP SDK访问令牌?



任何帮助都将非常感谢!






编辑



我发现有一些IE问题,会话内部的iFrame。如 此博文 所示。有了这个提示和一些进一步的研究,我在我的引导中添加了以下几行:

  ini_set('session.use_trans_sid',1) ; 
header('P3P:CP =IDC DSP COR ADM DEVI TAII PSA PSD IVAi IVDi CONI HIS INDOR);

现在好多了,但50个用户中约2个的信息在登陆页面的步骤之间丢失(认证) - >正式 - >和注册。所以还有一些我错过的东西。






编辑2



我从

 中编辑我的用户处理if($ this-> user === false || is_null($ this-> user)){
//获取用户数据
}

  if((is_object($ this-> user)&& $ this - > user-> fbId =='')|| $ this-> user === false || is_null($ this-> user)){
//获取用户数据
}

这似乎有一点帮助。我认为主要问题是我的会话中的某个地方。



此外,我添加了一个try / catch块,看看我的应用程序中是否有某个Facebook OAuthException 被抛出。如果是这种情况,我将顶部位置重定向到Facebook页面和标签页以获取新的签名请求。虽然这可能有助于解决这个问题,我想阻止我的应用程序重定向用户。






编辑3



经过几天的强烈调试和日志记录,我发现, $ _ REQUEST ['session'] 来自 FB.ui permissions.request方法是空的。



这是我如何处理它: / p>

这是我总是包含的东西:

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

此函数在表单提交时调用。总是为我工作,但不知何故,它仍然发送表单,虽然 session =='

  function getPermission(form){

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

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

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();
}
});
返回;
}


解决方案

我的解决方案



嗯,因为我做的一切只是一个解决方法,直到新的JS SDK出来,似乎没有最佳实践。将 session.use_trans_sid 设置为1并添加P3P头可帮助克服IE iFrame cookie问题(请参阅我的第一个编辑)。经过几天的大量调试,我发现FB.ui的 permission_request 不会每次发送一个新的访问令牌(<5%)。



如果发生这种情况,出现问题。但这个小东西让我疯狂。由于这种情况很少发生,我可以将用户重定向到Facebook选项卡以获取新的签名请求。使用新的JS SDK,希望这不会再发生。



更新:最终解决方案



是一个小事情我已经监督,解决方案可以在这里找到: FB不是定义的问题

我没有异步加载JS SDK !这解释了一切。有时,all.js文件没有加载足够快,所以有一个JS错误。因此,许可对话框和JS验证都不工作,并且发送了一个空的#session输入值。


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;
}

解决方案

My solution

Well, since everything I did was just a workaround until the new JS SDK comes out, there seems to be no best practice. Setting session.use_trans_sid to 1 and adding the P3P header helped to overcome IE iFrame cookie issues (see my first edit). After a few days of heavy debugging I found out, that FB.ui's permission_request does not send a new access token everytime (<5%).

If this happens, something went wrong. But this little something is driving me crazy. Since this happens infrequently, I can bear redirecting users back to the facebook tab to get a new signed request. With the new JS SDK, hopefully, this won't happen anymore.

Update: final solution

There was one little thing I have overseen and the solution can be found here: FB is not defined problem
I did not load the JS SDK asynchronously! This explains everything. Sometimes the all.js file was not loaded fast enough, so there was a JS error. Due to that, neither the permission dialog nor the JS validation worked and an empty #session input value was sent.

这篇关于如何使用Facebook PHP SDK 3.0正确处理会话和访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆