2015-03-02 138 views
1

我有檢索基本用戶信息的問題。這是我的代碼:facebook php sdk:檢索用戶信息

require_once 'facebook-php-sdk/autoload.php'; 
FacebookSession::setDefaultApplication('appid', 'appsecret'); 

try { 
    $token = 'mytoken'; 
    $session = new FacebookSession($token); 
    $request = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); 
    $username = $request->getName(); 

    echo $username . '<br>'; 
} catch (FacebookRequestException $e) { 
    echo'Error'; 
    echo $e; 
} 

但沒有例外,並且什麼都不打印。怎麼了?

回答

0

我不知道什麼可能是錯的代碼,但我這樣做的方式是,我下載了fb_api(3.2版)和寫這個劇本:

<?php 
require 'fb_api/facebook.php'; 

$facebook = new Facebook(array(
    'appId' => 'APPIDHERE', 
    'secret' => 'APPSECRETHERE', 
)); 

$user = $facebook->getUser(); 
if ($user) { 
    try { 
    $user_profile = $facebook->api('/me'); 
    } catch (FacebookApiException $e) { 
    error_log($e); 
    $user = null; 
    } 
} 

if ($user) { 
    $logoutUrl = $facebook->getLogoutUrl(); 
} else { 
    $loginUrl = $facebook->getLoginUrl(); 
} 

?> 
<!doctype html> 
<html xmlns:fb="http://www.facebook.com/2008/fbml"> 
    <head> 
    <title>php-sdk</title> 
    <style> 
     body { 
     font-family: 'Lucida Grande', Verdana, Arial, sans-serif; 
     } 
     h1 a { 
     text-decoration: none; 
     color: #3b5998; 
     } 
     h1 a:hover { 
     text-decoration: underline; 
     } 
    </style> 
    </head> 
    <body> 
    <?php if ($user): ?> 
     <a href="<?php echo $logoutUrl; ?>">Logout</a> 
    <?php else: ?> 
     <div> 
     <meta http-equiv="refresh" content="0; url=<?php echo $loginUrl; ?>"> 
     </div> 
    <?php endif ?> 
    <?php if ($user): ?> 
    <p> 
     <img src="https://graph.facebook.com/<?php echo $user; ?>/picture"> 
     <?php echo $user_profile['name']; ?> 
</p> 
     <h3>Your User Object (/me)</h3> 
     <pre><?php print_r($user_profile); ?></pre> 
    <?php else: ?> 
     <strong><em>You are not Connected.</em></strong> 
    <?php endif ?> 
    </body> 
</html> 

這段代碼的作用是,它會記錄你在,當你沒有登錄到Facebook和會抓住你的基本信息,當您登錄。

+0

我不t需要登錄到ph p頁面,因爲我調用我的腳本從一個Android應用程序,所以我已經有一個有效的令牌 – giozh 2015-03-02 10:30:33

0

你可以試試這個,讓我們知道你會得到什麼

$my_profile_info = (new FacebookRequest($session, 'GET', '/me/?fields=friends,id,name,birthday,email,picture,gender,location,address,email,hometown'))->execute()->getGraphObject()->asArray(); 
+0

沒有任何反應。 – giozh 2015-03-02 11:00:02

+0

您可以檢查/調試您獲得的訪問令牌嗎?使用https://developers.facebook.com/tools-and-support/點擊工具和支持 - >圖形Api資源管理器,以及您是否擁有public_profile,basic_info範圍 – jones 2015-03-02 11:08:39