FB:PHP简单连接脚本:如何获取电子邮件(PHP SDK OAuth 2.0)?

时间:2015-09-30 16:02:39

标签: php facebook

我使用的是一个简单的php连接脚本:

http://code.runnable.com/UfwdES1fQz9uAAAh/simple-facebook-connect-php-example

我检索名称,ID

如何检索电子邮件

我试过

 $user_profile = $facebook->api('/me?fields=email');

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

没有成功!

<?php

require 'lib/facebook-php-sdk/src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '',
  'secret' => '',
));

// Get User ID
$user = $facebook->getUser();

// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}


?>
<!doctype html>
<html>
  <body>


    <?php if ($user): ?>
      <a href="<?php echo $logoutUrl; ?>">Logout</a>
    <?php else: ?>
      <div>
        Login using OAuth 2.0 handled by the PHP SDK:
        <a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
      </div>
    <?php endif ?>

    <h3>PHP Session</h3>
    <pre><?php print_r($_SESSION); ?></pre>

    <?php if ($user): ?>
      <h3>You</h3>
      <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">

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

1 个答案:

答案 0 :(得分:1)

替换$ loginUrl var
$facebook->getLoginUrl(array("scope" => "email"));

之后你可以使用

/me?fields=email