Facebook PHP SDK在第一页加载时失败

时间:2013-02-22 14:11:25

标签: php facebook facebook-php-sdk

我的index.php加载的第一次调用时得到值0

$facebook->getUser();//returning 0 instead of id on first page load

该呼叫在任何后续页面加载时都能正常工作。

这是我的代码:

$facebook = new Facebook(array(
        'appId'  => $FB_APP_ID, 
        'secret' => $FB_APP_SECRET
    ));
$user_id = $facebook->getUser();//Returns 0 on first load.

还有其他人经历过这个吗?如果$facebook->getUser();没有返回有效用户,我可能会自动重新加载页面吗?

1 个答案:

答案 0 :(得分:-1)

可能是第一次没有对它进行身份验证,你可以这样做:

<?php

    $facebook = new Facebook(array(
        'appId'  => xxx, 
        'secret' => xxx
    ));

    $user_id = $facebook->getUser();

    if($user_id) {

      // We have a user ID, so probably a logged in user.
      // If not, we'll get an exception, which we handle below.
      try {

        $me = $facebook->api('/me','GET');
        echo "Name: " . $me['name'];

      } catch(FacebookApiException $e) {
        // If the user is logged out, you can have a 
        // user ID even though the access token is invalid.
        // In this case, we'll get an exception, so we'll redirect and
        // just ask the user to login again here.
        $login_url = $facebook->getLoginUrl(); 
        echo("<script>top.location.href = '" . $loginUrl . "';</script>");
      }   
    } else {

      // No user, redirect for the user to login
      $login_url = $facebook->getLoginUrl();
      echo("<script>top.location.href = '" . $loginUrl . "';</script>");

    }

  ?>

修改

如果错误仍然存​​在,请尝试使用此修改,只需更改此行:

$me = $facebook->api('/me','GET');

到此:

$me= $facebook->api('/'.$user_id, 'GET');

希望这能解决您的问题。