php必须使用活动访问令牌进行查询

时间:2014-01-14 07:03:28

标签: php facebook

我使用facebook SDK获取facebook好友列表。如果我使用Javascript FB.init()调用API;它完美无缺。

但如果我直接使用它

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

$fbuser = $facebook->getUser();
try{
    $user_profile = $facebook->api('/me');
    print_r($user_profile);
} catch(Exception $e){
    echo $e->getMessage();
}

(用户在同一浏览器中使用facebook登录) 它总是给我一个错误:必须使用活动访问令牌来查询有关当前用户的信息。

如果没有FB.init()或在任何地方重定向,请帮助我如何使用..

1 个答案:

答案 0 :(得分:3)

使用此

facebook = new Facebook(array(
'appId'  => $appid,
'secret' => $secret,
'cookie' => true
));

$fbuser = $facebook->getUser();
if($fbuser){
   $access_token = $facebook->getAccessToken();
   $facebook->setAccessToken($access_token);
   try{
       $user_profile = $facebook->api('/me');
       print_r($user_profile);
   } catch(Exception $e){
      echo $e->getMessage();
   }
}else{
  // User not logged in generate the login button or link here
}

在上面的脚本中确保当用户首次重新加载页面时登录f,换句话说你需要提供redirect_uri https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

您也可以使用以下API获取用户详细信息

$user_profile =  $facebook->api('/'. $fbuser,'GET');

然后在页面下方添加以下内容。这将检查用户是否已经登录,它将重定向到同一页面,换句话说,它不会要求用户再次登录

<div id="fb-root"></div>

<script type="text/javascript">
    window.fbAsyncInit = function()
            {
                FB.init
                ({
                    appId   : 'your fb app id',
                    status  : true, // check login status
                    cookie  : true, // enable cookies to allow the server to access the session
                    xfbml   : true, // parse XFBML
                    oauth   : true
                });
                FB.Event.subscribe('auth.login', function()
                {
                    window.location.reload();
                });
            };

          (function()
          {
            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
            }());
</script>
相关问题