如何使用用户访问令牌获取Facebook帖子?

时间:2012-11-27 05:03:54

标签: facebook-graph-api

问题:我想获取Facebook墙上的所有帖子。

说明:为此,我正在使用访问令牌。但我无法检索Facebook墙上的帖子。下面是我使用的代码。

<?php 

   $app_id = "xxxxxxxxxxxxxx";
   $app_secret = "  xxxxxxxxxxxxxxxxxxx ";
   $my_url = "http://localhost:8088/fb/testing.php";

   session_start();
     $code = $_REQUEST["code"];

   if(empty($code)) 
{
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state']. "&scope=publish_stream,read_stream";

     echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }

      if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) 
      {

     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     echo $response;
     $_SESSION['access_token'] = $params['access_token'];

     $graph_url = "https://graph.facebook.com/me/feed/?access_token=" 
       . $params['access_token'];

     $response = json_decode(file_get_contents($graph_url));
     if($response)
     echo $response;

     echo("Hello  " .$user );
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }


?>

这里当我打印$ user参数时,它什么也没显示。我无法找出错误。

1 个答案:

答案 0 :(得分:0)

以下是通过PHP API获取Facebook用户提要的代码,我使用Facebook PHP SDK获取提要:

    <?php 
require_once('src/facebook.php');

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

$uid = $facebook->getUser();

$me = null;
if ($uid) {
  try {

    $me = $facebook->api('/me');
    $feed = $facebook->api('/me/feed/');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}


//4. login or logout
if ($uid) {
    $logoutUrl = $facebook->getLogoutUrl();
} else {
    $loginUrl = $facebook->getLoginUrl();
}

?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title>php-sdk</title>
  </head>
  <body>
    <?php if($uid)

    {
    ?>
    <a href="<?php echo $logoutUrl; ?>">Logout</a>
    <?php
    }
else
{
?>
<a href="<?php echo $loginUrl; ?>">Login</a>
<?php
}   
     ?>

    <?php if ($me): ?>
    <?php
    echo "<pre>";
    print_r($feed);
    echo "</pre>";
    ?>
    <?php endif ?>


  </body>
</html>