【问题标题】:facebook php sdk: retrieve user informationfacebook php sdk:检索用户信息
【发布时间】:2015-03-02 18:57:05
【问题描述】:

我在检索基本用户信息时遇到问题。这是我的代码:

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;
}

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

【问题讨论】:

    标签: php facebook facebook-php-sdk


    【解决方案1】:

    我不知道你的代码有什么问题,但我这样做的方式是,我下载了 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 时登录,并在您登录时获取您的基本信息。

    【讨论】:

    • 我不需要登录到 php 页面,因为我从一个 android 应用程序调用我的脚本,所以我已经有一个有效的令牌
    【解决方案2】:

    你可以试试这个,让我们知道你得到了什么

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多