I am trying to return user email address using facebook api. Few days ago it was working fine, but today stopped working, and don't know why.
So first I get access token:
FB.login(response => {
if (response.authResponse) {
resolve(response.authResponse.accessToken);
} else {
reject({
error: 'User cancelled login or did not fully authorize.'
});
}
}, {
scope: 'public_profile,email'
});
then I try to get user data
FB.api('/me', {fields: 'first_name,last_name,email'}, function(response) {
console.log(response);
});
but I only get data for first_name and last_name. There is no email.
Also when I ask for permissions, it gives me email as granted, but as I said, email is not returned.
FB.api('/me/permissions', function(response) {
console.log(response);
});
Does anyone knows what can be the problem?
BTW: I am using API v2.4.
FB.api('/me?fields=email,name', function(response) { /* stuff here */ });
Try adding your return fields to your request.
I know this is old question however if someone still seraching for answers then following workaround worked for me.
You need to add email in scope scope="public_profile,email".
<fb:login-button scope="public_profile,email" autologoutlink="false" onlogin="OnRequestPermission();"></fb:login-button>
A possible cause is that the user did not validate the email. Try with another user with validated email to make sure this is not the problem.
See also this answer
If you set all code correctly and still don't get an email from API. The user probably doesn't have an email bound to the account or the email not confirmed by the user.
I made it work using a promise and adding {scope:'email'} to the initial request then including 'email' in the fb.api fields.
fb.login({scope:'email'}).then(function (resp) {
if (resp.status === 'connected') {
fb.api('/me', 'get', {fields:'id,email,first_name,gender,...'}).then(function (FbUserData) {
console.log(FbUserData);
});
}
});
I spent a lot of time trying to figure out why the email is not returned on the FacebookLoginASPnetWebForms Asp.Net application (https://github.com/nickpinheiro/FacebookLoginASPnetWebForms).
I got it working, thanks to N Nem's post above (thanks!).
Open Default.aspx.cs
In HyperLink1.NaviagteUrl, add the query string parameter: &scope=public_profile,email
HyperLink1.NavigateUrl = "https://www.facebook.com/v2.4/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + "/account/user.aspx&response_type=code&state=1&scope=public_profile,email";
I also had to fix some bugs to parse the access token correctly.
This time, the email address is available! I hope this helps?
N Nem above fixed for me. Had the code correct, but missing the scope on the login button. Code I use is below.
function statusChangeCallback(response){
if(response.status === 'connected'){
registerUser(response);
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function registerUser(statusResponse){
let userId = statusResponse.authResponse.userID;
FB.api('/'+userId+'/?fields=id,email,first_name,last_name',function(response){
if(response && !response.error){
console.log(response);
}
});
}
This is kinda old post but I am sharing the solution that worked for me.
FB Login SDK version: v6.0
First, make sure that the user (which is you for testing purposes) has a valid/verified email. Refer to the code below.
FB.login(response => {
// your code
}, {
scope: 'public_profile,email',
return_scopes: true,
auth_type: 'rerequest'
});
And in getting the user details
const response = await axios({
method: 'get',
url: 'https://graph.facebook.com/v6.0/me?fields=id,name,email&access_token=ACCESS_TOKEN&pretty=0&sdk=joey&suppress_http_code=1'
});
I've added the parameter fields=id,name,email
I have a web application that allows users to post custom stories to their Facebook timeline with the list of fitness exercises they have performed.
The first version is looping through the exercises and calling FP.api for each exercise and it works fine.
Now I would like to make a single call to FB.api with a batch request to speed up the posting and that's where I'm having trouble.
Here is the code with the loop that works fine (exids is an array of numbers):
function postToFB(exids)
{
fbi = 0;
fblength = exids.length;
for (var i = 0; i < fblength; i++)
{
FB.api(
'me/' + vitNamespace + ':perform',
'post',
{
exercise: "http://www.vitalclub.net/scripts/getExforFB.php?exid=" + exids[i],
'fb:explicitly_shared': true
},
function(response) {
...
});
}
}
and here is the code with the batch request that returns an error:
function postToFB(exids)
{
var batcharr = [];
for (var i = 0; i < exids.length; i++)
batcharr.push({ method: 'post', relative_url: 'me/' + vitNamespace + ':perform', body: "exercice=http://www.vitalclub.net/scripts/getExforFB.php%3Fexid%3D" + exids[i] + "&fb:explicitly_shared=true" });
FB.api(
'/',
'post',
{ batch: batcharr, include_headers: false },
function(response) {
...
});
}
The error I get (for each exercise) is the following: The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: exercise.
I presume this has to do with the way the body in the batch request is formatted but I cannot find the right way to format it. I have tried using encodeURIComponent on the URL representing the exercise but the error is the same.
Anybody has an idea of what the problem is?
Thanks,
Jean
OK, my bad. It was really a stupid error. I had written the parameter "exercise" in French instead of English (so "exercice" instead of "exercise") and that's where the problem was.
I'm also now using $.param to format the parameters so I now have:
var batcharr = [];
var opts;
for (var i = 0; i < exids.length; i++)
{
opts = { exercise: "http://www.vitalclub.net/scripts/getExforFB.php?exid=" + exids[i], 'fb:explicitly_shared': true };
batcharr.push({ method: 'post', relative_url: 'me/' + vitNamespace + ':perform', body: $.param(opts) });
}
before calling FB.api and it works like a charm!
I am creating my first facebook app using javascript sdk. In that i can able to post to the user's wall using(FB.api('me/feed', 'post', )).
Now what I need is, when the user accessing my app, it has to show (or list) the post of that user. The code is
FB.api('/me/posts', function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
alert('The value of post is:'+post);
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
But it is not working. If I remove l=response.length and change the condition as i<5 it is going inside the loop but it gives the value of post is undefined.
I didn't get why it is returning as undefined. It returns same for post.message also.
I am getting the access_token of the user also.
If I want to get the post of my user what code i have to use. Can anyone help me in this.
Thanks in advance
You can use the Facebook Graph API Explorer to better understand what data you will be receiving. https://developers.facebook.com/tools/explorer/
You should have l=response.data.length and var post = response.data[i];. Also, some posts will not have a "message", but will have a "story" instead (mainly posts like "Joe Smith and Tom Someone are now friends."). Make sure you also have the appropriate permissions (e.g. user_status) for the information you're trying to receive.
Here is some testing code:
<script>
var movieList = new Array();
var friendList=" ";
var friendCount = 0;
function get_friend_likes() {
FB.api('/me/friends', function(response) {
friendCount = response.data.length;
for( i=0; i<response.data.length; i++) {
friendId = response.data[i].id;
friendList=friendList+(response.data[i].name)+'<br/>';//store names
FB.api('/'+friendId+'/movies', function(result) {
movieList = movieList.concat(result.data); //fetch data to the pool
friendCount--;
document.getElementById('test').innerHTML = friendCount
+ " friends to go ... ";
});//end_FB.api
} //end_for
});//end_FB.api
}
</script>
The problem is: I can get the friends' names and ids successfully with the outer FB.api call, but I can't get '/movies' information in the inner FB.api call. The returned data is empty.
Any insights on this? Thanks a lot!!
According to the User object api documentation you need the "user_likes" permission to get /me/movies and "friends_likes" permission to get friendId/movies.
Have you asked for these permissions?
Not sure how you authenticate your users, but you can do it with the javascript sdk as well:
FB.login(callbackFunction, { scope: "user_likes,friends_likes" });
I have a FB App and I can successfully post actions and objects with the Open Graph API to the timeline, ticker, and chronicle.
My question is, is there a way to get the action id returned written into the mysql database or from the action id get the actual object title returned and written this to the database?
Thanks for your help.
You could do this with AJAX.
For example:
function postNewAction()
{
passString = '&object=http://site.com/APP_NAMESPACE/object.php';
FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post',
function(response) {
if (!response || response.error) {
alert(response.error.message);
}
else {
storeInTable(response.id);
}
}
);
}
function storeInTable(id){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//Success!
}
}
xmlhttp.open("GET","storeInTable.php?id=" + id,true);
xmlhttp.send();
}
And then you would store the id to your table in storeInTable.php of course.
This may not be the best way - maybe it is, I don't know - but will do what youre requesting.