php Facebook Graph API,如何获取用户电子邮件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3611682/
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
Facebook Graph API, how to get users email?
提问by kylex
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'];
采纳答案by Gazler
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 SDKinstead of file_get_contents as it makes it far easier to perform the Oauthauthentication.
回答by masakielastic
// 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']
);
回答by Kaletha
Open base_facebook.php
Add Access_token at function getLoginUrl()
打开 base_facebook.php 在函数中添加 Access_token getLoginUrl()
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'));
}
回答by Delino
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 checkLoginStateis 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 useridwhich is being set to variable, then a getUserInfofunc 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 useridas an argument, the function then fetch all information relating to that 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.
在将userid作为参数传递后,该函数然后获取与该userid相关的所有信息。注意:就我而言,我正在寻找电子邮件,以允许我运行一个只能通过电子邮件登录用户的功能。
// 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 !');
}
});
}
回答by Quentin
To get the user email, you have to log in the user with his Facebook account using the email
permission. Use for that the Facebook PHP SDK (see on github) as following.
要获取用户电子邮件,您必须使用该email
权限使用他的 Facebook 帐户登录该用户。为此使用 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 !
希望有帮助!
回答by Yash Kumar
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"]);
}
?>
回答by Gabriel P.
Assuming you've requested email permissions when the user logged in from your app and you have a valid token,
假设您在用户从您的应用登录时请求了电子邮件权限,并且您拥有有效的令牌,
With the fetch apiyou 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": "[email protected]"
}
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
回答by Karthik Sekar
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. 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 帐户的登录电子邮件显示为相应帐户的唯一标识符,但我无法从 fb 中删除它,我得到的只是用户个人资料中的主要电子邮件,但在我的情况下,我的登录电子邮件和我的主要电子邮件不同。
回答by Bobby Hyman
will give you info about the currently logged-in user, but you'll need to supply an oauth token. See:
将为您提供有关当前登录用户的信息,但您需要提供 oauth 令牌。看:
回答by Didzis
Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.
确保您的 Facebook 应用程序已发布。为了接收电子邮件、public_profile 和 user_friends 的数据,您的应用必须向公众开放。
You can disable it later for development purposes and still get email field.
您可以稍后出于开发目的禁用它,但仍然可以获取电子邮件字段。