2012-10-11 21 views
0

我试图获得一个随机朋友。我找到了this线程,它看起来应该工作。 这里是我的代码:Facebook API:使用PHP获取随机朋友

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

      $params = array(
       'method' => 'fql.query', 
       'query' => "SELECT uid, name, sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) order by rand() limit 1", 
      ); 

      $result = $facebook->api($params); 
      echo print_r($result); 

但我得到的错误:

Fatal error: Uncaught Exception: 102: Requires user session thrown in /home/path/to/base_facebook.php on line 1050 

问题出在哪里?我试图搜索可能的问题,但我没有太多成功......

+0

你有FB登录按钮吗?我认为问题是没有认证用户 – Jason

回答

2

是的,正如Jason所评论的,看起来您没有经过身份验证的用户。

由于您使用的PHP SDK,最快捷的方式来解决这个问题如下:

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

// This will redirect the user to a login/authentication dialog. 
if (!$facebook->getUser()) { 
    echo "<script>window.location = '".$facebook->getLoginUrl()."'</script>"; 
    exit(); 
} 

$params = array().. etc, the rest of your code 

缺乏最佳实践代码,尽管 - 这应该做的伎俩。

+0

感谢您的消息乔。那么,我有两个页面 - “index.php”和“data.php”。用户在页面'index.php'上开始(用户被认证)。从这个页面他发送表单('action =“data.php”method =“get”)并且在这个页面('data.php')我需要得到一个随机用户...有什么办法可以通过认证用户从'index.php'页面转换为'data.php'?谢谢 – user984621

+0

一旦他们登录/认证了应用程序,你可以在data.php页面上使用上面的代码,它将工作相同 - 只会在$ facebook-> getUser()方法失败时回显脚本。 –