为什么Facebook PHP SDK getUser总是返回0?
我正在尝试使用一个需要Facebook用户提供一些信息的网站,我正在使用PHP和JS SDK 我在PHP中有一个函数:为什么Facebook PHP SDK getUser总是返回0?,php,facebook,facebook-graph-api,Php,Facebook,Facebook Graph Api,我正在尝试使用一个需要Facebook用户提供一些信息的网站,我正在使用PHP和JS SDK 我在PHP中有一个函数: public function isLoggedOnFacebook() { $user = $this->_facebook->getUser(); if ($user) { return $this->_facebook->api("/$user"); } return false; } 在一个类上,
public function isLoggedOnFacebook() {
$user = $this->_facebook->getUser();
if ($user) {
return $this->_facebook->api("/$user");
}
return false;
}
在一个类上,该类在$this->\u facebook
中保存来自SDK的facebook对象
然后在一个街区上,我这样做:
<?php if (!$this->isLoggedOnFacebook()): ?>
<div>
<fb:login-button show-faces="true" perms="email" width="500" />
</div>
<?php endif ?>
而且FB JS环境设置正确(我认为),因此可以正常工作。因此,用户获得弹出窗口并授权站点
问题是,即使在用户授权应用程序之后,$user始终为0,这意味着$facebook->getUser()
始终返回0,然后列出用户的面孔,包括登录的用户,但是如果我让它调用$facebook->api('/me')
或其他什么,那么它将抛出无效令牌异常
我见过这个问题,但我还没有找到解决办法,我不知道
问题出在哪里,我的想法也没有了
应用程序部分的开发者Facebook页面上有一个“网站”选项卡,您可以在其中设置您的网站URL和网站域,我认为这是我的问题的原因,但我不知道这些字段应该包含哪些内容。查看此博客帖子:
新的JS SDK已经发布-如果您使用新的SDK 3.1.1和JS,您需要向FB.init例程添加新变量
oauth:true
使用新的誓言2.0协议!
然后在不允许PERM时更新您的登录按钮。请使用范围而不是PERM。如果http服务器由于配置错误而丢弃了请求,PHP-SDK会自动失败。我使用了错误配置的nginx,在跟踪代码~3小时后,通过vhost配置更改解决了这个问题
我在这里写了一篇关于解决方案的评论:
我希望能有所帮助。我遇到了类似的问题$facebook->getUser()返回0,有时在用户未实际登录时返回有效的用户id,导致在我尝试调用graph api时出现致命的Oauth错误。我终于解决了这个问题。我不知道这是不是正确的方法,但它是有效的。代码如下:
<?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 i.e. 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'))}");
}
?>
我检查和测试了很长时间,现在我找到了原因
请登录开发者应用程序,在设置中-->高级-->迁移-->禁用脱机访问--禁用
你会发现$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();
检查配置数组。
设置值时,请确保使用正确的字符串封装引号
$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
这是从网站上直接复制/粘贴的,由于奇怪的扭曲引用,因此不起作用
答案很长,因为应用程序机密没有返回有效值(实际上没有返回任何值),所以用于“检查”应用程序签名的哈希值没有得到正确的检查。。。因此,hash_hmac函数返回的值不正确,不匹配,等等。请在您的代码中尝试以下操作:
如果条件为真,您将被重新定向到facebook,然后自己登录,我希望您能顺利完成,但请记住使用新的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";
}
我在我的Facebook应用程序上遇到了完全相同的问题,在经历了两天的沮丧之后,我终于解决了这个问题。原来是getLoginUrl()
中的重定向uri有问题!如果它与通过facebook注册的应用程序域不匹配,他们将返回错误,用户将返回为0(默认用户值)。我解决了这个问题,因为我遇到了同样的问题。
只需转到developers.facebook.com/apps,然后导航到您的应用程序
点击编辑应用程序按钮
如果您已选中“facebook上的应用程序”,并已输入指向该应用程序的画布url
该应用程序无法在facebook上运行
将在apps.facebook.com下工作/
只需删除此检查,它对我有效$facebook->getUser()
如果用户未对应用进行身份验证,将返回0
使用$facebook->getLoginUrl
获取URL以验证应用程序。我对getUser()
有同样的问题,它在IE 8中返回0。在做了一些研究之后,我找到了一个解决方案。请点击下面的链接。这很有魅力
<?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。(https://developers.facebook.com/docs/reference/php/facebook-getUser/)
为了解决这个问题,FacebookJSSDK提供了一个来自成功登录的访问令牌,您可以将其与FacebookPHP SDK一起使用
下面的javascript将检查Facebook登录是否已存在,并且您的Facebook应用程序是否已授权:
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.
函数_accessServer向服务器打开另一个请求,并发送访问令牌
函数_loginPopup应打开Facebook登录弹出窗口,请求用户“允许访问”您的应用程序的适当权限
然后,PHP应用程序应将访问令牌传递回Facebook API:
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;
}
希望有帮助 添加这一行为我解决了IE9中的这个问题:
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;
}
您需要确保应用程序设置为从查询字符串而不是uri_片段中提取代码参数,这可以在facebook应用程序页面apps>settings>permissions
上进行设置
我使用$facebook->getLoginUrl()
来提供登录URL。我遇到了同样的问题,我发现这是因为SDK使用变量$\u REQUEST
,在我的环境中,与$\u GET
、$\u POST
和$\u COOKIE
变量合并的不是真的
我认为这取决于PHP版本,这就是为什么有人通过启用Cookie使其工作的原因
我在base_facebook.php中找到了以下代码:
if ($facebook->getUser()) {
$userProfile = $facebook->api('/me');
// do logic
} else {
$loginUrl = $facebook->getLoginUrl($params = array('scope' => SCOPE));
header('Location:' . $loginUrl);
}
我通过创建$server\u info对其进行了修改,如下所示
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;
}
if ($facebook->getUser()) {
$userProfile = $facebook->api('/me');
// do logic
} else {
$loginUrl = $facebook->getLoginUrl($params = array('scope' => SCOPE));
header('Location:' . $loginUrl);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ( getenv( 'environment' ) === 'development' ) {
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
}
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;
}
}
/**
* 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
);