PHP。获取有关Facebook用户的信息

时间:2014-02-19 11:33:03

标签: php oauth-2.0 facebook-login facebook-sdk-3.0

我在php中创建了一个Web服务器,它通过我的webApp接收facebook userAccessToken并检查它是否有效,我想获得有关该用户的基本信息但我找不到这样做的方法。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

    <?php
      require_once('php-sdk/facebook.php');

      $config = array(
        'appId' => 'YOUR_APP_ID',
        'secret' => 'YOUR_APP_SECRET',
        'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
      );

      $facebook = new Facebook($config);
      $user_id = $facebook->getUser();
    ?>

<html>
  <head></head>
  <body>



    <?php
        if($user_id) {

          // We have a user ID, so probably a logged in user.
          // If not, we'll get an exception, which we handle below.
          try {

            $user_profile = $facebook->api('/me','GET');
            echo "Name: " . $user_profile['name'];

          } catch(FacebookApiException $e) {
            // If the user is logged out, you can have a 
            // user ID even though the access token is invalid.
            // In this case, we'll get an exception, so we'll
            // just ask the user to login again here.
            $login_url = $facebook->getLoginUrl(); 
            echo 'Please <a href="' . $login_url . '">login.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
          }   
        } else {

          // No user, print a link for the user to login
          $login_url = $facebook->getLoginUrl();
          echo 'Please <a href="' . $login_url . '">login.</a>';

        }

      ?>

  </body>
</html>

登录后,使用此命令检索用户数据阵列:

$user_profile = $facebook->api('/me','GET');

或者您可以使用它来通过ID(其他用户)获取用户

$user_profile = $facebook->api('userID','GET');

您需要的一切都可以在这里找到:

https://developers.facebook.com/docs/reference/php/