无法使用PHP SDK从Facebook个人资料中检索电子邮件

时间:2017-05-20 17:03:55

标签: php facebook

我最近开始使用面向PHP的Facebook SDK。当我点击登录Facebook时,它会询问我的权限,包括我在第一步中授予的电子邮件地址。

我能够成功显示用户ID和名称。但是,对于电子邮件,我收到以下错误:

  

未定义的索引:第201行的C:\ wamp64 \ www \ php-graph-sdk-5.5 \ src \ Facebook \ GraphNodes \ Collection.php中的电子邮件

非常感谢你的帮助。

facebooklogin.php:

$fb = new Facebook\Facebook([
     'app_id' => '1234', 
     'app_secret' => '987654321',
     'default_graph_version' => 'v2.2',
  ]);

$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
    $helper->getPersistentDataHandler()->set('state', $_GET['state']);
}

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://localhost/callback.php', 
$permissions);

echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';

callback.php:

$fb = new Facebook\Facebook([
     'app_id' => '1234',
     'app_secret' => '987654321',
     'default_graph_version' => 'v2.2',
]);

$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
    $helper->getPersistentDataHandler()->set('state', $_GET['state']);
}

try {
    $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);

// Get user’s Facebook ID
$userId = $tokenMetadata->getField('user_id');

 try {
     // Returns a `Facebook\FacebookResponse` object
     $response = $fb->get('/me?fields=id,name,email', $accessToken);
 } 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();

 $userId = $user['id'];
 $name = $user['name'];
 $email = $user['email'];

 echo "$userId, $email";

0 个答案:

没有答案