如何使用 PHP 在 Facebook 应用程序中获取用户电子邮件 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3362885/
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 09:28:28  来源:igfitidea点击:

How to get Users Email Id in Facebook application using PHP?

phpfacebook

提问by Harish Kurup

I have created a simple Facebook application in PHP, that greets user by there user name, I also want there Email id, to be displayed. But i am not able to do that. the code that i am using is,

我用 PHP 创建了一个简单的 Facebook 应用程序,它通过用户名向用户打招呼,我还希望显示电子邮件 ID。但我无法做到这一点。我正在使用的代码是,

require_once('facebook.php');
require_once('config.php');
$facebook = new Facebook(APIKEY, SECRETKEY);
$user=$facebook->require_login();

echo $user; // displaying the ID
<div style="padding: 10px;" id="greeting">
   <fb:if-is-app-user uid="loggedinuser">
      <h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
  <fb:else>
       <h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
   </fb:else>
   </fb:if-user-has-added-app>
</div>

the Output that i am getting is,

我得到的输出是,

1000002020202020
Hi User! welcome to facebook

I want the Email address to be displayed along with the user name, i searched many code but did not get any solution. and if you any good facebook tutorial site please post the links too..

我希望电子邮件地址与用户名一起显示,我搜索了很多代码但没有得到任何解决方案。如果你有任何好的 facebook 教程网站,也请发布链接。

回答by Harish Kurup

You can get the Email Address, directly without using the FQL.

您可以直接获取电子邮件地址,而无需使用 FQL。

// initialize facebook
 $facebook = new Facebook(array(
        'appId' => APP_ID,
        'secret' => APP_SECRET));

 $session = $facebook->getSession();
 if ($session) {
 try {
    $fbme = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}
else
{
  echo "You are NOT Logged in";
}

//getting the login page if not signned in
if (!$fbme) {
  $loginUrl = $facebook->getLoginUrl(array('canvas' => 1,
                                      'fbconnect' => 0,
                                      'req_perms' =>                   'email,user_birthday,publish_stream',
                                      'next' => CANVAS_PAGE,
                                      'cancel_url' => CANVAS_PAGE ));
 echo '<fb:redirect url="' . $loginUrl . '" />';
 } else {

      // $fbme is valid i.e. user can access our app
     echo "You can use this App";
 }

 // getting the profile data
 $user_id = $fbme[id];
 $name=$fbme['name'];
 $first_name=$fbme['first_name'];
 $last_name=$fbme['last_name'];
 $facebook_url=$fbme['link'];
 $location=$fbme['location']['name'];
 $bio_info=$fbme['bio'];
 $work_array=$fbme['work'];
 $education_array=$fbme["education"];
 $email=$fbme['email'];
 $date_of_birth=$fbme['birthday'];

This code worked for me..and i go all the information needed with the Email ID.

这段代码对我有用……我用电子邮件 ID 获取了所有需要的信息。

NOTE: User has to allow us to get their Information during the Approval of Application.

回答by agbb

You need to ask for extended permissions when the user authorizes your application, so you can have access to the user email.

当用户授权您的应用程序时,您需要请求扩展权限,以便您可以访问用户电子邮件。

Here's an example using the new PHP SDK and the Graph API:

以下是使用新 PHP SDK 和 Graph API 的示例:

<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');

// initialize facebook
$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET));

$user = $facebook->getUser();
$session = $facebook->getSession();

// in case we don't have a valid session, we redirect asking for email extended permissions
if ($user == null || $session == null) {
  $params = array();
  $params["canvas"] = "1";
  $params["fbconnect"] = "0";
  $params["next"] = CANVAS_URL;
  $params["req_perms"] = "email";

  $loginUrl = $facebook->getLoginUrl($params);

  echo '<fb:redirect url="' . $loginUrl . '"/>';
  exit();
}

// get user email via the new graph api, using the fql.query method
$url = "https://api.facebook.com/method/fql.query";
$url .= "?access_token=" . $session['access_token'];
$url .= "&query=SELECT email FROM user WHERE uid={$user}";
$userData = simplexml_load_file($url);
$userEmail = $userData->user->email;

echo 'The user ID is: ' . $user;
echo 'The user name is: <fb:name uid="' . $user . '" />';
echo 'The user email is: ' . $userEmail;

回答by murvinlai

Thanks for all the help. I finally figure out how to do that.

感谢所有的帮助。我终于弄清楚如何做到这一点。

first, I need to get the access token, NOT the user session one, but the one for admin.

首先,我需要获取访问令牌,而不是用户会话令牌,而是管理员令牌。

So, here is the code:

所以,这里是代码:

$url = 'https://graph.facebook.com/oauth/access_token';
$ch = curl_init();
$params = array(
                'grant_type'=>'client_credentials',
                'client_id'=>$appId,
                'client_secret'=>$secret,
                );

$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
// set URL and other appropriate options
curl_setopt_array($ch, $opts);
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$adminAccessToken = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);

And then, I can use the facebook API to get any user who accept the application and the extended permission like that:

然后,我可以使用 facebook API 来获取任何接受应用程序和扩展权限的用户,如下所示:

$fql    =   "select name, hometown_location, sex, pic_square, email from user where uid=1000000001";
    $param  =   array(
       'method'     => 'fql.query',
        'query'     => $fql,
        'access_token' =>$adminAccessToken ,
      'callback'    => ''
    );

    $fqlResult2   =   $facebook->api($param);

with the access token, i can also post things onto user's wall. :)

使用访问令牌,我还可以将内容发布到用户的墙上。:)