facebook php sdk:检索用户信息

时间:2015-03-02 10:01:04

标签: php facebook 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;
}

但不会抛出异常,也不会打印任何内容。怎么了?

2 个答案:

答案 0 :(得分: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时它会将您登录,并在您登录时获取基本信息。

答案 1 :(得分:0)

你可以尝试一下,让我们知道你得到了什么

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