Why is Facebook PHP SDK getUser always returning 0

2019-01-01 11:12发布

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

I have a function in 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.

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.

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.

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.

26条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 11:30

I had the same problem and I figured it out that is because SDK uses the variable $_REQUEST and in my environment is not true that is merged with $_GET, $_POST and $_COOKIE variables.

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

I found this code in 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.

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;
}
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 11:30

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).

查看更多
余生无你
5楼-- · 2019-01-01 11:30

After some desperate hours, here is what caused the same issue on my server: If you use SSL, make sure that port 443 is not blocked! I opened the port last year, but it appeared that my webhoster somehow did a reset recently.

查看更多
回忆,回不去的记忆
6楼-- · 2019-01-01 11:31

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

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";
}
查看更多
浅入江南
7楼-- · 2019-01-01 11:32

I also spent many hours looking at this and also found a solution. Might not be for you but it seems there is some issue with $_SERVER['QUERY_STRING'] so you need to set it into the $_REQUEST array.

I was using codeigniter and found that the following code above the library load worked.

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

}
查看更多
登录 后发表回答