2012-02-05 22 views

回答

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代碼顯示如何處理這些錯誤並檢索新的訪問令牌。

當您將用戶重定向到身份驗證對話框時,如果用戶已經授權您的應用程序,則不會提示用戶輸入權限。 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
感謝

+0

非常感謝。此代碼非常適合基於用戶的閱讀。如果可能的話,我需要一個僅在服務器上工作而無需用戶交互的系統。可能嗎? – Andrea 2012-02-06 20:31:05

+0

@Andrea,但這對Facebook的條款 – 2012-02-07 05:28:42

+0

對不起,我不明白爲什麼。你能指出我在這種情況下適用的規則嗎?非常感謝 – Andrea 2012-02-07 22:56:11