简体   繁体   English

Facebook Graph API,如何获取用户电子邮件?

[英]Facebook Graph API, how to get users email?

I'm using the Graph API, but I can't figure out how to get a logged-in users email address.我正在使用 Graph API,但我不知道如何获取登录用户的电子邮件地址。

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday" Graph 的介绍指出“Graph API 可以提供对您通常在网站注册表单中请求的所有基本帐户注册数据的访问权限,包括姓名、电子邮件地址、个人资料图片和生日”

All well and good, but how do I access that info?一切都很好,但我如何访问这些信息?

This is what I have so far:这是我到目前为止:

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

$first = $json['first_name']; // gets first name
$last = $json['last_name'];

The only way to get the users e-mail address is to request extended permissions on the email field.获取用户电子邮件地址的唯一方法是请求对电子邮件字段的扩展权限。 The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.用户必须允许您看到这一点,并且您无法获得用户朋友的电子邮件地址。

http://developers.facebook.com/docs/authentication/permissions http://developers.facebook.com/docs/authentication/permissions

You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.如果您使用 Facebook 连接,您可以通过在调用的获取字符串中传递 scope=email 到身份验证对话框来执行此操作。

I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.我建议使用SDK而不是 file_get_contents,因为它可以更轻松地执行Oauth身份验证。

// Facebook SDK v5 for PHP
// https://developers.facebook.com/docs/php/gettingstarted/5.0.0

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

$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
$response = $fb->get('/me?locale=en_US&fields=name,email');
$userNode = $response->getGraphUser();
var_dump(
    $userNode->getField('email'), $userNode['email']
);

Open base_facebook.php Add Access_token at function getLoginUrl()打开 base_facebook.php 在函数getLoginUrl()添加 Access_token

array_merge(array(
                  'access_token' => $this->getAccessToken(),
                  'client_id' => $this->getAppId(),
                  'redirect_uri' => $currentUrl, // possibly overwritten
                  'state' => $this->state),
             $params);

and Use scope for Email Permission和电子邮件权限的使用范围

if ($user) {
   echo $logoutUrl = $facebook->getLogoutUrl();
} else {
   echo $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,read_stream'));
}

Just add these code block on status return, and start passing a query string object {}.只需在状态返回时添加这些代码块,并开始传递查询字符串对象 {}。 For JavaScript devs对于 JavaScript 开发者

After initializing your sdk.初始化sdk后。

step 1: // get login status step 1: // 获取登录状态

$(document).ready(function($) {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
        console.log(response);
    });
  });

This will check on document load and get your login status check if users has been logged in.这将检查文档加载并获取您的登录状态检查用户是否已登录。

Then the function checkLoginState is called, and response is pass to statusChangeCallback然后调用函数checkLoginState ,并将响应传递给statusChangeCallback

function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

Step 2: Let you get the response data from the status第二步:让你从状态中获取响应数据

function statusChangeCallback(response) {
    // body...
    if(response.status === 'connected'){
      // setElements(true);
      let userId = response.authResponse.userID;
      // console.log(userId);
      console.log('login');
      getUserInfo(userId);

    }else{
      // setElements(false);
      console.log('not logged in !');
    }
  }

This also has the userid which is being set to variable, then a getUserInfo func is called to fetch user information using the Graph-api.这也有被设置为变量的用户 ID ,然后调用getUserInfo函数以使用 Graph-api 获取用户信息。

function getUserInfo(userId) {
    // body...
    FB.api(
      '/'+userId+'/?fields=id,name,email',
      'GET',
      {},
      function(response) {
        // Insert your code here
        // console.log(response);
        let email = response.email;
        loginViaEmail(email);
      }
    );
  }

After passing the userid as an argument, the function then fetch all information relating to that userid .在将userid作为参数传递后,该函数然后获取与该userid相关的所有信息。 Note: in my case i was looking for the email, as to allowed me run a function that can logged user via email only.注意:就我而言,我正在寻找电子邮件,以允许我运行一个只能通过电子邮件登录用户的功能。

// login via email // 通过电子邮件登录

function loginViaEmail(email) {
    // body...
    let token = '{{ csrf_token() }}';

    let data = {
      _token:token,
      email:email
    }

    $.ajax({
      url: '/login/via/email',    
      type: 'POST',
      dataType: 'json',
      data: data,
      success: function(data){
        console.log(data);
        if(data.status == 'success'){
          window.location.href = '/dashboard';
        }

        if(data.status == 'info'){
          window.location.href = '/create-account'; 
        }
      },
      error: function(data){
        console.log('Error logging in via email !');
        // alert('Fail to send login request !');
      }
    });
  }

To get the user email, you have to log in the user with his Facebook account using the email permission.要获取用户电子邮件,您必须使用email权限使用他的 Facebook 帐户登录用户。 Use for that the Facebook PHP SDK ( see on github ) as following.为此使用 Facebook PHP SDK(参见 github ),如下所示。

First check if the user is already logged in :首先检查用户是否已经登录:

require "facebook.php";
$facebook = new Facebook(array(
    'appId'  => YOUR_APP_ID,
    'secret' => YOUR_APP_SECRET,
));

$user = $facebook->getUser();
if ($user) {
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

If he his not, you can display the login link asking for the email permission :如果他不是,您可以显示登录链接,要求获得email权限:

if (!$user) {
    $args = array('scope' => 'email');
    echo '<a href="' . $facebook->getLoginUrl() . '">Login with Facebook</a>';
} else {
    echo '<a href="' . $facebook->getLogoutUrl() . '">Logout</a>';
}

When he is logged in the email can be found in the $user_profile array.当他登录时,可以在$user_profile数组中找到电子邮件。

Hope that helps !希望有帮助!

Assuming you've requested email permissions when the user logged in from your app and you have a valid token,假设您在用户从您的应用登录时请求了电子邮件权限,并且您拥有有效的令牌,

With the fetch api you can just使用fetch api你可以

const token = "some_valid_token";
const response = await fetch(
        `https://graph.facebook.com/me?fields=email&access_token=${token}`
      );
const result = await response.json();

result will be:结果将是:

{
    "id": "some_id",
    "email": "name@example.org"
}

id will be returned anyway.无论如何都会返回id。

You can add to the fields query param more stuff, but you need permissions for them if they are not on the public profile (name is public).您可以向字段查询参数添加更多内容,但如果它们不在公共配置文件中(名称为 public),则您需要它们的权限。

?fields=name,email,user_birthday&token=

https://developers.facebook.com/docs/facebook-login/permissions https://developers.facebook.com/docs/facebook-login/permissions

You can retrieve the email address from the logged in user's profile.您可以从登录用户的个人资料中检索电子邮件地址。 Here is the code snippet这是代码片段

<?php

    $facebook = new Facebook(array(
      'appId'  => $initMe["appId"],
      'secret' => $initMe["appSecret"],
    ));

    $facebook->setAccessToken($initMe["accessToken"]);
    $user = $facebook->getUser();

    if ($user) {
        $user_profile = $facebook->api('/me');
        print_r($user_profile["email"]);
    }
?>

First, activate your application at the Facebook Developer center .首先,在Facebook 开发人员中心激活您的应用程序。 Applications in development mode are not allowed to retrieve the e-mail field.开发模式下的应用程序不允许检索电子邮件字段。

If the user is not logged in, you need to login and specify that your application/site will need the e-mail field.如果用户未登录,您需要登录并指定您的应用程序/站点将需要电子邮件字段。

FB.login(
    function(response) {
         console.log('Welcome!');
    },
    {scope: 'email'}
);

Then, after the login, or if the user is already logged, retrieve the e-mail using the Facebook API, specifying the field email:然后,在登录后,或者如果用户已经登录,使用 Facebook API 检索电子邮件,指定字段电子邮件:

FB.api('/me', {fields: 'name,email'}, (response) => {
    console.log(response.name + ', ' + response.email);
    console.log('full response: ', response);
});

The email in the profile can be obtained using extended permission but I Guess it's not possible to get the email used to login fb.可以使用扩展权限获得个人资料中的电子邮件,但我猜不可能获得用于登录 fb 的电子邮件。 In my app i wanted to display mulitple fb accounts of a user in a list, i wanted to show the login emails of fb accounts as a unique identifier of the respective accounts but i couldn't get it off from fb, all i got was the primary email in the user profile but in my case my login email and my primary email are different.在我的应用程序中,我想在列表中显示用户的多个 fb 帐户,我想将 fb 帐户的登录电子邮件显示为相应帐户的唯一标识符,但我无法从 fb 中删除它,我得到的只是用户个人资料中的主要电子邮件,但在我的情况下,我的登录电子邮件和我的主要电子邮件不同。

https://graph.facebook.com/me https://graph.facebook.com/me

will give you info about the currently logged-in user, but you'll need to supply an oauth token.将为您提供有关当前登录用户的信息,但您需要提供 oauth 令牌。 See:见:

http://developers.facebook.com/docs/reference/api/user http://developers.facebook.com/docs/reference/api/user

Make sure your Facebook application is published.确保您的 Facebook 应用程序已发布。 In order to receive data for email, public_profile and user_friends your app must be made available to public.为了接收电子邮件、public_profile 和 user_friends 数据,您的应用必须公开。

You can disable it later for development purposes and still get email field.您可以稍后出于开发目的禁用它,但仍然可以获取电子邮件字段。

The following tools can be useful during development:以下工具在开发过程中很有用:

Access Token Debugger: Paste in an access token for details访问令牌调试器:粘贴访问令牌以获取详细信息

https://developers.facebook.com/tools/debug/accesstoken/ https://developers.facebook.com/tools/debug/accesstoken/

Graph API Explorer: Test requests to the graph api after pasting in your access token Graph API Explorer:在粘贴访问令牌后测试对图形 API 的请求

https://developers.facebook.com/tools/explorer https://developers.facebook.com/tools/explorer

Make sure to fully specify the version number of the API as something like "v2.11" and not "2.11"确保将 API 的版本号完全指定为"v2.11"而不是"2.11"

I'm not sure what it defaults to if this is incorrect, but I got some odd errors trying to just retrieve the email when I missed the v .如果这是不正确的,我不确定它的默认值是什么,但是当我错过了v时,我在尝试检索电子邮件时遇到了一些奇怪的错误。

For me the problem with collecting user's email addres on PHP side (getGraphUser() method) was, that the default behavior of facebook-rendered button (on WEBSIDE side, created with xfbml=1) is to implicity calling FB.login() with the scope NOT including "email".对我来说,在 PHP 端(getGraphUser() 方法)收集用户电子邮件地址的问题是,facebook 渲染按钮(在 WEBSIDE 端,使用 xfbml=1 创建)的默认行为是隐式调用 FB.login()范围不包括“电子邮件”。

That means you MUST:这意味着您必须:

1) call 1) 打电话

FB.login(....,{scope: email})

manifestly, creating your own button to start login process显然,创建自己的按钮来开始登录过程

OR

2) add scope="email" attribute to the xfbml button 2) 将 scope="email" 属性添加到 xfbml 按钮

<div class="fb-login-button" data-size="large" data-button-type="continue_with" data-
layout="rounded" data-auto-logout-link="false" data-use-continue-as="true" data-
width="1000px" scope="email"></div>

to be able to collect email address on PHP side.能够在 PHP 端收集电子邮件地址。

Hope it helps.希望它有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM