阅读Facebook页面帖子和令牌过期

时间:2012-02-05 16:48:48

标签: facebook facebook-graph-api facebook-php-sdk

我需要从服务器读取特定粉丝页面的流。 我试着读图api https://graph.facebook.com/ /进料=的access_token&安培;限= 100 它的工作原理。 我需要的是了解令牌是否会过期以及如何以编程方式更新令牌。 现在,我通过http://developers.facebook.com/tools/explorer/应用生成令牌。 你能帮我么? 我正在使用PHP sdk 谢谢, 一个。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码阅读Facebook页面,也可以获取指定的字段

https://graph.facebook.com/$page_id/?fields=link,etc&access_token=page_access_token

$response = $fb->api($page_id .  '/?fields=link,etc&'. $access_token, 'GET')

以下是四种情况的解决方案

1.令牌在到期时间后到期(默认为2小时) 2.用户更改密码,使访问令牌无效 3.用户取消授权您的应用。
4.用户退出Facebook。

为了确保为用户提供最佳体验,您的应用需要做好准备,以捕获上述方案的错误。以下PHP代码向您展示了如何处理这些错误并检索新的访问令牌。

当您将用户重定向到auth对话框时,如果用户已经授权您的应用程序,则不会提示用户输入权限。 Facebook将返回一个有效的访问令牌,而无需任何面向用户的对话框。但是,如果用户取消了您的应用程序的授权,那么用户需要重新授权您的应用程序才能获得access_token。

<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET"; 
$my_url = "YOUR_POST_LOGIN_URL";

// known valid access token stored in a database 
$access_token = "YOUR_STORED_ACCESS_TOKEN";

$code = $_REQUEST["code"];

// If we get a code, it means that we have re-authed the user 
//and can get a valid access_token. 
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
  . $app_id . "&redirect_uri=" . urlencode($my_url) 
  . "&client_secret=" . $app_secret 
  . "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}


// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);

//Check for errors 
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
  // Retrieving a valid access token. 
  $dialog_url= "https://www.facebook.com/dialog/oauth?"
    . "client_id=" . $app_id 
    . "&redirect_uri=" . urlencode($my_url);
  echo("<script> top.location.href='" . $dialog_url 
  . "'</script>");
}
else {
  echo "other error has happened";
}
} 
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}

// note this wrapper function exists in order to circumvent PHP’s 
//strict obeying of HTTP error codes.  In this case, Facebook 
//returns error code 400 which PHP obeys and wipes out 
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>

有关详细信息,请访问此link
感谢