简体   繁体   中英

Facebook SDK-PHP - Always returns 0 when calling getUser()

The PHP Facebook-SDK returns 0 for me, everytime I call the getUser() method. I am looking for a solution without using JS. That what I have so far.

$user = null;
    $facebook = new Facebook(array(
            'appId'  => '140739xxxx46068',
            'secret' => '46dff7362e86xxxxx06fe9050a86a22',
            'cookie' => true,
    ));

    // Get User ID
    $login = $facebook->getLoginUrl(array("scope" => "publish_stream,manage_pages"));
    $user = $facebook->getUser();

    echo $facebook->getUser()."//".$facebook->getAccessToken();

    if ($user <> '0' && $user <> '')
    {
        try {
            //header("location:".$login);
        }
        catch (FacebookApiException $e)
        {
            echo $e->getType();
            echo $e->getMessage();

        }

Think about it for a second. You're saving the loginURL into your $login var and after that you try to retrieve user data.

That will never work. You are not prompting the user to use the login URL, so he did not grant access. The user needs to visit the URL manually and confirm the permissions. After that you may be able to retrieve user data.

Let's sum it up:

  1. Initialize the Facebook SDK
  2. Check if the user already permitted access ( getUser() will be fine for that)
  3. If yes, proceed as you normally would. Your user granted access.
  4. If not ( getUser() is 0), tell the user to visit the URL you get via getLoginUrl() )
  5. Make sure you include the redirect_uri key in your array you pass in 4. you can redirect to the same uri since we are checking whether we retrieve user data or prompting the user to log in
  6. After permitting access (or not) your user will be redirected from facebook to your redirect_uri
  7. If everything was ok while requesting the access you should be at step 3

The logical flaw you have, is that you think getLoginURL() automatically grants you access to the userdata. But that is not true, you need your users to visit that very URL so that they can grant access by themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM