为什么Facebook的PHP SDK getUser总是返回0?

我正在尝试使用需要Facebook用户的一些信息的网站,我正在使用PHP和JS SDK。

我有一个PHP的function:

public function isLoggedOnFacebook() { $user = $this->_facebook->getUser(); if ($user) { return $this->_facebook->api("/$user"); } return false; } 

$this->_facebook从SDK中持有Facebook对象的类。

然后在一个块我做到这一点:

 <?php if (!$this->isLoggedOnFacebook()): ?> <div> <fb:login-button show-faces="true" perms="email" width="500" /> </div> <?php endif ?> 

FB JS环境设置正确(我认为),所以它的工作原理。 因此,用户popup并授权该网站。

问题是,即使在用户授权应用程序后,$ user始终为0,意味着$facebook->getUser()总是返回0,然后列出用户的面孔,包括logging的用户,但如果我打电话$facebook->api('/me')或其他,然后它会抛出无效的令牌exception。

我已经看到了这个问题,但是我还没有看到一个解决scheme,我不知道问题出在哪里,而且我没有想法。

在应用程序部分的开发人员的Facebook页面上有一个网站标签,您可以在其中设置您的网站url和您的网站域名,我认为这是我的问题的原因,但我不知道这些是什么字段应该包含。

我有同样的问题,我觉得这是因为SDK使用variables$_REQUEST并在我的环境是不正确的与$_GET$_POST$_COOKIEvariables合并。

我认为这取决于PHP版本,这就是为什么有人通过启用cookie来使其工作。

我在base_facebook.php中find了这个代码:

 protected function getCode() { if (isset($_REQUEST['code'])) { if ($this->state !== null && isset($_REQUEST['state']) && $this->state === $_REQUEST['state']) { // CSRF state has done its job, so clear it $this->state = null; $this->clearPersistentData('state'); return $_REQUEST['code']; } else { self::errorLog('CSRF state token does not match one provided.'); return false; } } return false; } 

我通过创build$ server_infovariables来修改它,如下所示。

 protected function getCode() { $server_info = array_merge($_GET, $_POST, $_COOKIE); if (isset($server_info['code'])) { if ($this->state !== null && isset($server_info['state']) && $this->state === $server_info['state']) { // CSRF state has done its job, so clear it $this->state = null; $this->clearPersistentData('state'); return $server_info['code']; } else { self::errorLog('CSRF state token does not match one provided.'); return false; } } return false; } 

我遇到了类似的问题。 $ facebook-> getUser()返回0,有时当用户没有真正login时返回有效的用户标识,导致致命的Oauth错误,当我试图做graphicsapi调用。 我终于解决了这个问题。 我不知道这是否正确,但是有效。 这里是代码:

 <?php include 'includes/php/facebook.php'; $app_id = "APP_ID"; $app_secret = "SECRET_KEY"; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true )); $user = $facebook->getUser(); if ($user <> '0' && $user <> '') { /*if valid user id ie neither 0 nor blank nor null*/ try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { /*sometimes it shows user id even if user in not logged in and it results in Oauth exception. In this case we will set it back to 0.*/ error_log($e); $user = '0'; } } if ($user <> '0' && $user <> '') { /*So now we will have a valid user id with a valid oauth access token and so the code will work fine.*/ echo "UserId : " . $user; $params = array( 'next' => 'http://www.anujkumar.com' ); echo "<p><a href='". $facebook->getLogoutUrl($params) . "'>Logout</a>"; $user_profile = $facebook->api('/me'); echo "<p>Name : " . $user_profile['name']; echo "<p>"; print_r($user_profile); } else {/*If user id isn't present just redirect it to login url*/ header("Location:{$facebook->getLoginUrl(array('req_perms' => 'email,offline_access'))}"); } ?> 

看看这个博客文章: http : //thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/

新的JS SDK已经发布 – https://developers.facebook.com/blog/post/525

您需要确保您的应用程序设置为从查询string而不是uri_fragment中选取代码参数,可以在facebook应用程序页面apps>settings>permissions

这对我使用$facebook->getLoginUrl()来提供loginURL。

检查你的configuration数组。 确保在设置值时使用正确的string封装引号。

 $config = array(); $config["appId"] = $APP_ID; $config["secret"] = $APP_SECRET; $config["fileUpload"] = false; // optional 

这工作。

 $config = array(); $config['appId'] = 'YOUR_APP_ID'; $config['secret'] = 'YOUR_APP_SECRET'; $config['fileUpload'] = false; // optional 

这是从网站http://developers.facebook.com/docs/reference/php/的直接复制/粘贴,并不工作,因为奇怪的引文。;

很长的答案是你的应用程序签名“检查”哈希不出来一个正确的检查,因为应用程序的秘密没有返回一个有效的值(实际上它没有返回任何东西)…所以哈希_马克function是返回不正确的值不正确,等等…

通过base_facebook.php进行debugging后发现,由于某种原因,我丢失了我的.crt文件,访问令牌永远无效。 确保你有你的fb_ca_chain_bundle.crt在: https : //github.com/facebook/facebook-php-sdk/blob/master/src/fb_ca_chain_bundle.crt

几小时和几小时下来。 在Stack Overflow或其他站点上没有任何关于这个的post提供了解决我的问题的方法。 我终于进入图书馆的代码,并确切地知道它在哪里死去。

在我的开发机器上,使用XAMPP for Windows,我一直得到0login,而我的testing服务器将正常工作。 在意识到exception被抛出但隐藏后,我在base_facebook.php中放置了一个$ e-> getMessage(),指出我有一个SSL错误。 下面的post, HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书validation失败,CA是好的 ,导致我的解决scheme。

解决scheme:

在base_facebook.php中,在curl_exec($ ch)之前添加以下内容:

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

你应该把上面的代码包装在你使用的任何标志中,以确定你是否处于开发模式,因为你不需要在生产系统中使用上面的代码。 例如:

 if ( getenv( 'environment' ) === 'development' ) { curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); } 

我查了很久,现在我find了原因。

请login开发人员的应用程序,在设置 – > 高级 – > 迁移 – > 弃用脱机访问 – – > 禁用

你会发现$ facebook-> getUser()将工作。

另一件事。 新的facebook类时最好添加域名;

 $facebook = new Facebook(array( 'appId' => APP_ID,//$app_id, 'secret' => APP_SECRET,//$app_secret, 'cookie' => true, 'domain'=>'xxxdomain.com', )); $session = $facebook->getUser(); 

在你的一段代码中试试这个:如果条件正确,你将被redirect到Facebook然后login你自己,我希望你会好,但记得使用新的PHP SDK库

 if(($facebook->getUser())==0) { header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}"); exit; } else { $accounts_list = $facebook->api('/me/accounts'); echo "i am connected"; } 

我解决了这个问题,因为我面临同样的问题。 刚刚goto developers.facebook.com/apps然后导航到您的应用程序点击编辑应用程序button

如果你有检查“在Facebook上的应用程序”,并已input一个canvasurl的应用程序将无法工作的一面Facebook的将在apps.facebook.com/

只是删除这个检查它为我工作

 <?php require 'facebook.php'; // Create our application instance // (replace this with your appId and secret). $facebook = new Facebook(array( 'appId' => 'YOUR_APP_ID', 'secret' => 'YOUR_APP_SECRET', )); // Get User ID $user = $facebook->getUser(); // We may or may not have this data based // on whether the user is logged in. // If we have a $user id here, it means we know // the user is logged into // Facebook, but we don't know if the access token is valid. An access // token is invalid if the user logged out of Facebook. if ($user) { try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } } // Login or logout url will be needed depending on current user state. if ($user) { $logoutUrl = $facebook->getLogoutUrl(); } else { $loginUrl = $facebook->getLoginUrl(); } // This call will always work since we are fetching public data. $naitik = $facebook->api('/naitik'); ?> <!doctype html> <html xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title>php-sdk</title> <style> body { font-family: 'Lucida Grande', Verdana, Arial, sans-serif; } h1 a { text-decoration: none; color: #3b5998; } h1 a:hover { text-decoration: underline; } </style> </head> <body> <h1>php-sdk</h1> <?php if ($user): ?> <a href="<?php echo $logoutUrl; ?>">Logout</a> <?php else: ?> <div> Login using OAuth 2.0 handled by the PHP SDK: <a href="<?php echo $loginUrl; ?>">Login with Facebook</a> </div> <?php endif ?> <h3>PHP Session</h3> <pre><?php print_r($_SESSION); ?></pre> <?php if ($user): ?> <h3>You</h3> <img src="https://graph.facebook.com/<?php echo $user; ?>/picture"> <h3>Your User Object (/me)</h3> <pre><?php print_r($user_profile); ?></pre> <?php else: ?> <strong><em>You are not Connected.</em></strong> <?php endif ?> <h3>Public profile of Naitik</h3> <img src="https://graph.facebook.com/naitik/picture"> <?php echo $naitik['name']; ?> </body> </html> 

$facebook->getUser()将返回0,如果用户不authentication的应用程序。

使用$facebook->getLoginUrl获取URL来validation应用程序。

我在Facebook应用上遇到了同样的问题,经过两天的沮丧,我终于find了答案。 原来是getLoginUrl()的redirect-uri问题! 如果通过Facebook不匹配已注册的应用程序域,则返回错误,并将用户返回为0(默认用户值)。

我有同样的问题getUser() ,它在IE 8中返回0。我做了一些研究后find了一个解决scheme。 按照下面的链接。 这工作像一个魅力。

http://www.andugo.com/facebook-php-sdk-getuser-return-0-value-on-ie/

经过一些绝望的时间,这是什么在我的服务器上造成同样的问题:如果您使用SSL,请确保端口443不被阻止 ! 去年我打开了这个港口,但似乎我的webhoster最近不知何故重置了。

如果您使用新的SDK 3.1.1和JS,则需要将新variables添加到调用的FB.init例程中

oauth : true使用新的OATH 2.0协议! 然后更新您的loginbutton,而不允许烫发请使用范围,而不是烫发

如果_REQUEST像通过错误configuration由http服务器丢弃的全局variables, getUser()和PHP-SDK会自动失败。 我正在使用configuration错误的nginx,跟踪代码〜3小时后,通过vhostconfiguration更改解决了这个问题。

我在这里写了关于解决scheme的评论: https : //github.com/facebook/php-sdk/issues/418#issuecomment-2193699

我希望有所帮助。

当没有login的用户时,facebook-> getUser()将返回0。 (https://developers.facebook.com/docs/reference/php/facebook-getUser/);

为了解决这个问题,Facebook JS SDK提供了一个成功login的访问令牌,您可以使用Facebook PHP SDK。

下面的JavaScript将检查Facebooklogin是否已经存在,并且您的Facebook应用程序已被授权:

 FB.getLoginStatus(function($response) { if ($response.status === 'connected') { var uid = $response.authResponse.userID; var accessToken = $response.authResponse.accessToken; _accessServer(uid, accessToken); } else if ($response.status === 'not_authorized') { _loginPopup(); } else { _loginPopup(); } }); 

_accessServer函数打开另一个请求回到您的服务器,发送访问令牌。

函数_loginPopup应该打开Facebookloginpopup窗口,请求用户允许访问你的应用程序的权限。

PHP应用程序应该将访问令牌传递回Facebook API:

 $facebook->setAccessToken($new_access_token); $uid = $facebook->getUser(); 

https://developers.facebook.com/docs/reference/php/facebook-setAccessToken/

希望有所帮助。

添加这条线在IE9中为我解决了这个问题:

 header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); // This is the main cause to use on IE. 

如果这个问题仍然与人有关,我想贡献我的2分钱,因为我挣扎了相当长的一段时间才搞定了事情。

首先,试一下适合你的SDK,无论是PHP还是JS。 实质上,他们都做同样的事情,只是JS可能会处理它更优雅(与popup对话框,什么不是)。 有很多不同的教程,手册和例子! 我花了一个星期的时间才find一个适合我的东西,而且我可以使用它。 一旦你find了一个与你计划使用的SDK一起工作的代码,现在是时候改变代码来满足你的特定需求了。

一旦我完成了我的代码,我开始testing它。 我注意到我在localhost上运行我的代码,而且我也没有从我的数组中得到任何结果。 要回答您的问题,请将您的代码上传到(子)域,然后重试。 我的代码一直工作,但因为我没有在线,它没有工作。 如果你已经在网上,那么我的答案是不适合你。

对不起,如果这样的小故事不是真的想要这样做,但它可以帮助人们。

祝你好运!

  if ($facebook->getUser()) { $userProfile = $facebook->api('/me'); // do logic } else { $loginUrl = $facebook->getLoginUrl($params = array('scope' => SCOPE)); header('Location:' . $loginUrl); } 

那我如何解决我的问题,现在它正在返回我的用户configuration文件的细节进一步处理。 (这真是头疼)

这些都是很好的build议,但对我而言,这一切都是在Facebook本身。 重构代码很多次后,我意识到这是在Facebook上的configuration问题。
以下步骤解决了我的问题。

1.)在Facebook的基本>应用程序…我取消了,虽然你可以离开它,如果你想

2.)在权限>隐私 – >设置为公共

权限>身份validation令牌 – >设置为查询string

3.)在高级 – >authentication>应用程序types – > Web

第三步是真正解决这个问题的那个,但是不完全确定为什么,希望有帮助

确保任何输出之前调用此Facebook API函数getUser,因为它使用会话variables和Cookie。 如果你的头不能被正确的发送/阅读。

我也花了很多时间看这个,也find了解决办法。 可能不适合你,但似乎有$ _SERVER ['QUERY_STRING']的问题,所以你需要将其设置到$ _REQUEST数组。

我正在使用codeigniter,发现上面的代码库加载下面的代码工作。

parse_str($ _ SERVER [ 'QUERY_STRING'],$ _ REQUEST);

  parse_str($_SERVER['QUERY_STRING'],$_REQUEST); $config = array(); $config["appId"] = "63xxxxx39"; $config["secret"] = "dexxxx3bf"; $this->load->library('facebook',$config); $this->user = $user = $this->facebook->getUser(); if ($user) { try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $this->facebook->api('/me'); //print_r($user_profile);exit; } catch (FacebookApiException $e) { echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>'; $user = null; } $logout = $this->facebook->getLogoutUrl(); $this->fb_logout = $logout; $this->fb_user = $user_profile; } else { $login = $this->facebook->getLoginUrl(array("scope"=>"email","redirect_uri"=>"http://domain/login/login_fbmember/")); $this->fb_login = $login; } } 

这个问题真的很奇怪。 我发现问题是base_facebook.php中的静态$ CURL_OPTS数组。

尝试从这个编辑它:

  /** * Default options for curl. * * @var array */ public static $CURL_OPTS = array( CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_USERAGENT => 'facebook-php-3.2', ); 

  /** * Default options for curl. * * @var array */ public static $CURL_OPTS = array( CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_USERAGENT => 'facebook-php-3.2', CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4 ); 

我的具体问题的答案是,我使用的JS SDK和PHP SDK的版本之间存在不兼容性,只是升级他们就解决了这个问题。

这个问题的症状是由各种不同的事情造成的,所以你可以通过本页面的不同答案进行探索。