如何使用 Facebook PHP API 获取用户信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16581361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:23:22  来源:igfitidea点击:

How to get user information with Facebook PHP API

phpfacebookfacebook-graph-apifacebook-javascript-sdk

提问by Florent

I use the Facebook API and I wish retrieve Facebook information of the connected user. I can retrieve the information in javascript, but I want to get the information to fill the PHP stored in my database.

我使用 Facebook API 并希望检索连接用户的 Facebook 信息。我可以在 javascript 中检索信息,但我想获取信息来填充存储在我的数据库中的 PHP。

Here is my code in javascript function:

这是我在 javascript 函数中的代码:

    <html>
    <head>
        <title>My Application</title>
        <style type="text/css">
            div { padding: 10px; }
        </style>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
          var fbAppId = 'myAppId';
          var objectToLike = 'http://techcrunch.com/2013/02/06/facebook-launches-developers-live-video-channel-to-keep-its-developer-ecosystem-up-to-date/';

          if (fbAppId === 'replace me') {
            alert('Please set the fbAppId in the sample.');
          }

          window.fbAsyncInit = function() {
            FB.init({
              appId      : fbAppId,        // App ID
              status     : true,           // check login status
              cookie     : true,           // enable cookies to allow the server to access the session
              xfbml      : true            // parse page for xfbml or html5 social plugins like login button below
            });

            FB.login(function(response) {
               if (response.authResponse) {
                 FB.api('/me', function(response) {
                   window.alert(response.last_name + ', ' + response.first_name + ", " + response.email);
                 });
               }
             });
          };

          (function(d, s, id){
             var js, fjs = d.getElementsByTagName(s)[0];
             if (d.getElementById(id)) {return;}
             js = d.createElement(s); js.id = id;
             js.src = "//connect.facebook.net/en_US/all.js";
             fjs.parentNode.insertBefore(js, fjs);
           }(document, 'script', 'facebook-jssdk'));

        </script>
</body>
</html>

Here is my PHP code I can not make it work

这是我的 PHP 代码我无法让它工作

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

$config = array();
$config['appId'] = 'myAppId';
$config['secret'] = 'myCodeSecret';
$config['fileUpload'] = false; // optional

$facebook = new Facebook($config);

$user = $facebook->getUser();

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

If I display the variable $user, I get my user id. But then I can not get other information.

如果我显示变量$user,我会得到我的用户 ID。但后来我无法获得其他信息。

I looked more in detail and this may be a problem in the configuration of the application in Facebook. Could you explain the steps to create an application on Facebook?

我看了更详细,这可能是 Facebook 中应用程序配置的问题。您能解释一下在 Facebook 上创建应用程序的步骤吗?

回答by Liam Allan

try

尝试

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

回答by Dani?l van Rijn

I'm now answering on an old thread but I was experience the same problem. I have solved this to creat a $params array with my acces token.

我现在正在回答一个旧线程,但我遇到了同样的问题。我已经解决了这个问题,用我的访问令牌创建了一个 $params 数组。

So the things to do is something like this.

所以要做的事情是这样的。

    $config = array();
$config['appId'] = $appid;
$config['secret'] = $appSecret;
$config['fileUpload'] = false; // optional
$fb = new Facebook($config);

$params = array("access_token" => "acces_token_given_by_facebook");
$object = $fb->api('/me', 'GET', $params);

print_r($object);

When you add $params to your get request it will work. Facebook won't do anything untill you've sended the acces token. Also this solved my problem.

当您将 $params 添加到您的 get 请求时,它将起作用。在您发送访问令牌之前,Facebook 不会执行任何操作。这也解决了我的问题。

回答by MastaBaba

From here:

这里

$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',
  ]);

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['name'];
// OR
// echo 'Name: ' . $user->getName();

回答by varun

Here is a quick script which gets user data

这是一个获取用户数据的快速脚本

<?php     
try {
    // Get UID of the user
    $uid = $this->fb->getUser();

    // Get basic info about the user
    $me = $this->fb->api('/me');

    // Get the user's facebook stream
    $feed = $this->fb->api('/me/home');

    // Obtain user's and his/her friend's basic information via FQL Multiquery
    $streamQuery = <<<STREAMQUERY
{
"basicinfo": "SELECT uid,name,pic_square FROM user WHERE uid=me()",
"friendsinfo" : "SELECT uid, name, pic_square FROM user WHERE uid = me() OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())"
}
STREAMQUERY;
    $streamParams = array(
                          'method' => 'fql.multiquery',
                          'queries' => $streamQuery
                   );
    $streamResult = $this->fb->api($streamParams);

    //Obtain user likes, interests, movies, music, books
    $likes = $this->fb->api('/me/likes');
    $interests = $this->fb->api('/me/interests');
    $movies = $this->fb->api('/me/movies');
    $music = $this->fb->api('/me/music');
    $books = $this->fb->api('/me/books');
}catch(FacebookApiException $e) {
    error_log($e);
    //Session expired or user de-authenticated the app
    $this->showConnectToFB(true);
}

?>