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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6790272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:15:08  来源:igfitidea点击:

Why is Facebook PHP SDK getUser always returning 0?

phpfacebookfacebook-graph-api

提问by fd8s0

I'm trying to work with a website that requires some information from a Facebook user, I'm using PHP and JS SDKs.

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

I have a function in PHP:

我在 PHP 中有一个函数:

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

On a class that is holding the facebook object from the SDK in $this->_facebook.

在一个类上,该类在$this->_facebook.

Then on a block I do this:

然后在一个街区我这样做:

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

And the FB JS environment is properly set up (I think) so it works. So the user gets the pop up and authorizes the site.

并且 FB JS 环境设置正确(我认为)所以它可以工作。所以用户得到弹出窗口并授权该站点。

The problem is even after the app is been authorized by the user $user is always 0, meaning $facebook->getUser()always returns 0, and then lists the faces of users, including the logged user, but if I make it call $facebook->api('/me')or whatever, then it'll throw the invalid token exception.

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

I've seen this problem, but I haven't seen a solution, I have no idea where the problem is and I run out of ideas.

我见过这个问题,但我还没有看到解决方案,我不知道问题出在哪里,我的想法也用完了。

There's a Website tab on the developers' Facebook page in the apps section, where you can set up your Site URL and your Site Domain, and I'm thinking this are the cause of my problem, but I have no knowledge of exactly what these fields are supposed to contain.

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

采纳答案by fd8s0

The answer to my specific issue was that there were incompatibilities between the versions of the JS SDK and PHP SDK I was using and just upgrading them solved it.

我的具体问题的答案是我使用的 JS SDK 和 PHP SDK 的版本之间存在不兼容,只需升级它们就可以解决它。

The symptom of this issue is similar when it's caused by a variety of different things so you may do very well in scouting through the different answers available in this page.

当这个问题是由各种不同的事情引起时,它的症状是相似的,因此您可以很好地探索本页提供的不同答案。

回答by Norberto Yoan

I had the same problem and I figured it out that is because SDK uses the variable $_REQUESTand in my environment is not true that is merged with $_GET, $_POSTand $_COOKIEvariables.

我遇到了同样的问题,我发现这是因为 SDK 使用了该变量,$_REQUEST而在我的环境中与$_GET,$_POST$_COOKIE变量合并的情况并非如此。

I think it depends on the PHP version and that is why someone made it work by enabling cookies.

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

I found this code in base_facebook.php:

我在 base_facebook.php 中找到了这段代码:

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

And I modified it as you can see below by creating $server_info variable.

我通过创建 $server_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;
}

回答by anujkk

I ran into similar problem. $facebook->getUser() was returning 0 and sometimes it returned valid user id when user wasn't actually logged in, resulting in Fatal Oauth error when I tried to make graph api calls. I finally solved this problem. I don't know if it is the right way but it works. Here is the code :

我遇到了类似的问题。$facebook->getUser() 返回 0,有时当用户实际上没有登录时它返回有效的用户 ID,当我尝试进行图形 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'))}");
}

?>

回答by Stephen Creasey

You need to ensure that your app is set to pick up the code parameter from the Query String rather than the uri_fragment, this can be set on facebook apps page apps>settings>permissions.

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

That did it for me using $facebook->getLoginUrl()to provide the login URL.

这为我$facebook->getLoginUrl()提供了登录 URL。

回答by Ian

After debugging through the base_facebook.php I found, because somehow I had lost my .crt file the access token is forever invalid. Make sure you have your fb_ca_chain_bundle.crt available at: https://github.com/facebook/facebook-php-sdk/blob/master/src/fb_ca_chain_bundle.crt

在通过 base_facebook.php 调试后,我发现,因为不知何故我丢失了我的 .crt 文件,访问令牌永远无效。确保您的 fb_ca_chain_bundle.crt 位于:https: //github.com/facebook/facebook-php-sdk/blob/master/src/fb_ca_chain_bundle.crt

回答by levans

Hours and hours down the drain. None of the posts about this on Stack Overflow or other sites provided the solution to my problem. I finally went in to the library code and figured out exactly where it was dying.

数小时和数小时的流失。Stack Overflow 或其他网站上关于此的帖子都没有提供解决我的问题的方法。我终于进入了库代码并弄清楚了它到底在哪里消亡。

On my development machine, which uses XAMPP for Windows, I kept getting the 0 for logging in, while my test server would work properly. After realizing an exception was being thrown but hidden, I put an $e->getMessage() in base_facebook.php, which pointed out I was having an SSL error. The following post, HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK, led me to a solution.

在我的开发机器上,它使用 XAMPP for Windows,我一直得到 0 进行登录,而我的测试服务器可以正常工作。在意识到异常被抛出但被隐藏后,我在 base_facebook.php 中放置了一个 $e->getMessage(),它指出我遇到了 SSL 错误。以下帖子HTTPS 和 SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK,让我找到了解决方案。

The solution:

解决方案:

In base_facebook.php, add the following before curl_exec($ch):

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

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

You should probably wrap the above in whatever flags you use to determine if you are in development mode, because you won't want the above line in a production system. For instance:

您可能应该将上述内容包装在用于确定您是否处于开发模式的任何标志中,因为您不希望在生产系统中使用上述行。例如:

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

回答by Jared Mark

Check your config array. Ensure that you are using proper string encaps quotes when setting the values.

检查您的配置数组。确保在设置值时使用正确的字符串封装引号。

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

This works.

这有效。

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

This is a direct copy/paste from the website http://developers.facebook.com/docs/reference/php/and does NOT work because of the odd squiggly quotes.

这是来自网站http://developers.facebook.com/docs/reference/php/的直接复制/粘贴,由于奇怪的波浪形引号而不起作用。

the long answer is that your hash for your "checking" of the app signature is not coming out to a correct check, because the app secret is not returning a valid value (it's returning nothing, actually)... so the hash_hmac function is returning an incorrect value that doesn't match properly, etc...

长的答案是你的应用程序签名的“检查”散列没有得到正确的检查,因为应用程序秘密没有返回一个有效的值(它实际上什么都不返回)......所以 hash_hmac 函数是返回不正确匹配的错误值等...

回答by Faizan Qadri

Try this in your piece of code: on if condition true you'll be reirected to facebook then login yourself and i hope you'll good to go by then but remember use new libraries of php SDK

在你的一段代码中试试这个:如果条件为真,你将被重定向到 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";
}

回答by Nick

I was having the exact same problem on my Facebook app, and I finally figured it out after 2 days of hair pulling frustration. It turned out to be an issue with the redirect-uri in the getLoginUrl()! if it doesn't match the registered app domain through facebook, they return the error, and the user gets returned as 0 (the default user value).

我在我的 Facebook 应用程序上遇到了完全相同的问题,经过 2 天的挫败感后,我终于弄清楚了。原来是getLoginUrl()! 如果它与通过 facebook 注册的应用程序域不匹配,它们将返回错误,并且用户将返回为 0(默认用户值)。

回答by Hemen Ashodia

i solved this as i faced the same problem. Just goto developers.facebook.com/apps then navigate to your app hit EDIT APP button

我解决了这个问题,因为我遇到了同样的问题。只需转到developers.facebook.com/apps 然后导航到您的应用程序点击编辑应用程序按钮

IF you have check "App on facebook" and have entered a canvas url to it the app will not work out side the facebook will work under apps.facebook.com/

如果您已选中“Facebook 上的应用程序”并为其输入了画布网址,则该应用程序将无法运行,而 facebook 将在 apps.facebook.com/ 下运行

just remove this check it worked for me

只需删除此检查它对我有用