2014-01-13 116 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

回答