2014-01-13 164 views
0

我在構建下面的一些Q &後面的PHP代碼如下所示。下面的代碼爲我的Facebook應用程序生成一個無限期(兩個月)的訪問令牌。PHP Facebook獲取粉絲頁面令牌

基本上,通過Facebook應用程序,用戶可以將多張圖片上傳到他們在我的臉書頁面上的專輯中。爲了這個應用程序的工作,它需要兩個訪問令牌。應用訪問令牌(以下代碼)和頁面訪問令牌。

我使用cron作業來生成文本文件(下面的代碼)的第一個訪問令牌,它工作正常。現在我想使用下面類似的代碼生成頁面訪問令牌到另一個文本文件,但我還沒有成功。

<?php 

require_once 'library/facebook.php'; 
include '../constants.php'; 

define('TOKEN_FILE', 'fb_app_token.txt'); // dont need to change this 


$fb = new Facebook(array(
    'appId' => FB_APP_ID, 
    'secret' => FB_APP_SECRET, 
    'cookie' => true, 
)); 


function ensure_login($fb) { 
    if (!$fb->getUser()) { 
     header('Location: '.$fb->getLoginUrl(array(
      'scope' => 'manage_pages,publish_stream', 
     ))); 
     die(); 
    } 
} 

function fetch_long_living_access_token($fb) { 
    $qs = http_build_query(array(
     'client_id'   => $fb->getAppId(), 
     'client_secret'  => $fb->getApiSecret(), 
     'grant_type'  => 'fb_exchange_token', 
     'fb_exchange_token' => $fb->getAccessToken(), 
    )); 

    $fb_resp = file_get_contents('https://graph.facebook.com/oauth/access_token?'.$qs); 
    if (!$fb_resp) { 
     ensure_login($fb); 
    } 
    parse_str($fb_resp, $fb_resp); 
    if (!isset($fb_resp['access_token'])) { 
     ensure_login($fb); 
    } 
    $fb->setAccessToken($fb_resp['access_token']); 
    return $fb_resp['access_token']; 

} 

function save_page_access_token($token) { 
    file_put_contents(TOKEN_FILE, $token); 
} 

function get_random_message($source) { 
    $lines = preg_split('/[\n\r]+/', trim(file_get_contents($source))); 
    return $lines[array_rand($lines)]; 
} 


ensure_login($fb); 
$page_access_token = fetch_long_living_access_token($fb); 
save_page_access_token($page_access_token); 
print 'saved access token: '.$page_access_token; 


?> 

我試過到目前爲止什麼:

<?php 
require_once 'library/facebook.php'; 
include '../constants.php'; 
define('TOKEN_FILE', 'fb_page_accestoken.txt'); // dont need to change this 
$fb = new Facebook(array(
    'appId' => FB_APP_ID, 
    'secret' => FB_APP_SECRET, 
    'cookie' => true, 
)); 
$access_token = file_get_contents('fb_app_token.txt'); 
$response = "https://graph.facebook.com/me/accounts?access_token=".$access_token; 
echo $response; 
?> 

下面這段代碼。基本上它獲得了上述的用戶令牌,它給了我一個URL來獲取不確定的(2個月)Facebook頁面訪問代碼。

我在瀏覽器中輸入這個URL,它給了我所有頁面的數組。在這種情況下,我選擇我相應頁面的訪問令牌。

我想獲得類似於第一個代碼的頁面訪問令牌 - 而不是使用我的第二個代碼。否則,從第二個代碼的數組中獲取頁面訪問代碼。

我無法找到如何從facebook api給出的數組中獲取特定數據,例如僅訪問頁面訪問代碼。

+0

我真的不明白你想做什麼。請解釋一下你的意思:「我希望獲得類似於第一個代碼的頁面的訪問令牌 - 而不是使用我的第二個代碼,否則,從第二個代碼的數組中獲取頁面訪問代碼。」 您可以使用字段擴展API從所查詢的對象只獲得某些字段: https://graph.facebook.com/me/accounts?fields=access_token 如果你有多個頁面,那麼你需要某種登錄才能選擇適當的訪問令牌。 – Tobi

+0

嗨,我想獲得頁面Toke類似於我如何獲得應用程序令牌,即第一個代碼。# – user3173207

回答