Facebook JS api: Not receiving user email despite asking for permissions - javascript

For my facebook canvas app I've been trying to access the users email. Even though I ask for it, it still doesn't show up (birthday, which is also an additional permission, does show up). (in the addscope function)
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '--------------', // App ID
channelUrl : 'http://www.---------.com/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.statusChange', function(response) {
if(response.status === 'connected')
{
console.log('Hello there!');
addScope();
}
else if(response.status === 'not_authorized')
{
console.log('not authorized');
addScope();
}
else
{
console.log('not logged in');
addScope();
}
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// ...
} else if (response.status === 'not_authorized') {
// ...
} else {
//...
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function addScope()
{
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('In addscope function, ' + response.email + response.birthday);
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email,user_birthday'});
}
</script>
</body>
</html>

An effective way to see if the right permissions are being set through the code is to use the following code (change the fields that you want to check for in the query part):
FB.api({ method: 'fql.query', query: 'SELECT user_status,friends_status,user_photos,friends_photos,user_location,friends_location FROM permissions WHERE uid=me()' }, function(resp) {
for(var key in resp[0]) {
if(resp[0][key] === "1")
console.log(key+' is granted');
else
console.log(key+' is not granted');
}
});
It is possible the user might not have given the permissions to access email id.

As far as I can see, and providing there are no errors being thrown elsewhere and that the "addScope" method is being called, your code is correct. Just make sure that there actually is a value to return (that the user has a birthday and email, otherwise you will not get it back. as stated here: https://developers.facebook.com/docs/reference/api/user/ )
I am using the FB api and have had no problem getting email and other fields while using the User access token.

remove this :
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// ...
} else if (response.status === 'not_authorized') {
// ...
} else {
//...
}
});
};
and try again

Related

Retrieve user info (i.e. location, email) w/ Facebook Javascript API

I'm using the Facebook Javascript SDK to implement Facebook Login. I'm trying to grab the name, email, location, likes, friends, etc. and redirect the user to on-boarding.
I'm able to get accessToken and userID values;however, I'm trying to grab other user information I specifically put in my scope. I've tried to look at Facebook returns undefined for email and birthday
and other questions but no luck 😞
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
console.log(response); // dump complete info
var accessToken = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ accessToken);
var userID = FB.getAuthResponse()['userID']; //get FB UID
console.log("userID: "+ userID);
//refer to getData() function below
getData();
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'public_profile,email,user_friends,user_likes,user_location'});
}
function getData() {
FB.api('/me', function(response) {
console.log("email: "+response.email);
// you can store this data into your database
console.log('Good to see you, ' + response.name + '.');
//check if the loginStatus works
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
//redirect to start/location.ejs
//window.location = "start/location";
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
});
}
Why is this?
I was able to figure it out. Had to define some fields...now I have to figure out how to get a bigger profile pic from the user
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
console.log(response); // dump complete info
var accessToken = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ accessToken);
var userID = FB.getAuthResponse()['userID']; //get FB UID
console.log("userID: "+ userID);
//refer to getData() function below
getData(accessToken);
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {'scope': 'public_profile,email,user_friends,user_likes,user_location'});
}
function getData(accessToken) {
FB.api('/me', 'get', { access_token: accessToken, fields: 'id,name,gender,email,location,friends,likes,picture' }, function(response) {
console.log(response);
});
//check if the loginStatus works
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
//redirect to start/location.ejs
//window.location = "start/location";
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
}

Getting email from Facebook JS API, issue or feature?

I'm using the following as a reference:
https://developers.facebook.com/docs/facebook-login/web
However, I cannot seem to extract an email. I'm not sure whether this is because the user settings don't allow the email, or that this is an issue with the calls I'm making.
Here is the code that I'm using:
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
var result = JSON.stringify(response);
alert(response.email)
}, {scope: 'public_profile,email,first_name,last_name'});
<fb:login-button data-scope="email" scope="public_profile, email" onlogin="checkLoginState();">
</fb:login-button>
I can login fine, but I get nothing for the email. I don't know if this is a user settings issue or code issue.
There is no scope parameter for FB.api, and you are already defining the scope in the login button. There is also no scope called "first_name" or "last_name", those are just fields in the user table.
Anyway, since v2.4 you have to specifiy the fields in the API endpoint: https://developers.facebook.com/docs/apps/changelog#v2_4
For example:
FB.api('/me', {fields: 'email,first_name,last_name'}, function(response) {
...
});
You can read more about FB.api in the docs: https://developers.facebook.com/docs/javascript/reference/FB.api
Btw, there´s an article about login with the JS SDK, if you need more information: http://www.devils-heaven.com/facebook-javascript-sdk-login/

FB.Event.subscribe auth.statusChange not firing in Angular JS

In my service:
window.fbAsyncInit = function() {
FB.init({
appId : "",
xfbml : false
version : 'v2.0',
status : true
});
};
In My controller:
FB.Event.subscribe('auth.statusChange', function (response) {
console.log(response);
if (response.status === 'connected') {
//Continue
}else{
console.log("FB not connected")
}
});
FB.getLoginStatus(function (response) {
console.log(response);
if (response.status === 'connected') {
//Continue
} else {
// the user isn't logged in to Facebook.
console.log("not logged in");
}
})
I do not see any of console logs messages. infact the auth.statuschange is not getting fired. Please guide me in the correct direction.
TIA
I'd rather put this as a comment, but I can't because of reputation.
Quick question: Are you already logged in on facebook? Because then you would log nothing.

fb.login response always returns true

in order to check if the suer has given all the needed permissions, i do it so:
FB.login(function(response){
console.log(response.status);
if (response.status == 'connected') {
/* user gave permssions */
}else{
/* user didnt, unmark the checkbox */
$('input:checkbox').removeAttr('checked');
}
}, { scope: 'publish_stream' });
The problem is that this is allways returning true, it doesnt matter if user: logins, ommits or closes the popup.
any idea why?
Also tried: if (response.authResponse) { with no success..
The issue here is that publish_stream is an extended permission, which means the user can opt out of that permission. Generally speaking, when a user hits the block of code in your callback they have authenticated your app, but not necessarily with all of the permissions you asked for since some of them can be extended permissions. response.status is only used to communicate the status of whether the user has authenticated the application, not whether or not they have accepted all of the dialog prompts/permissions you have requested. In your case, publish_stream is an extended permission so you are not guaranteed to have that permission for the user in your callback. If you are asking for publish_stream as an incremental permission after a user has already authenticated, then your conditional check on response.status will always return true (since by definition the user has already authenticated your application).
If you want to verify you have the publish_stream permission in your callback, check for the permission using /me/permissions endpoint on the graph api.
What you want is something like this:
FB.login(function(response){
if (response.status == 'connected') {
FB.api('/me/permissions', function(response) {
var permsArray = response.data[0];
// Permissions that are needed for the app
var permsNeeded = ['publish_stream'];
var permsToPrompt = [];
for (var i in permsNeeded) {
if (permsArray[permsNeeded[i]] == null) {
permsToPrompt.push(permsNeeded[i]);
}
}
if (permsToPrompt.length > 0) {
$('input:checkbox').removeAttr('checked');
}
}
} else {
/* user didnt, unmark the checkbox */
$('input:checkbox').removeAttr('checked');
}
}, { scope: 'publish_stream' });
I don't know why, but the following code works fine for me at least~
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo FACEBOOK_APP_ID ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response){
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
var signed_request = response.authResponse.signedRequest;
// avoid using cookie
self.location= "<?php echo site_url()?>/signup/fb_login/"+uid;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
FB.login(function(response) {
if (response.authResponse) {
self.location="<?php echo site_url()?>/signup/fb_register";
/* FB.api('/me', function(response) { */
/* }); */
} }, {scope: 'email,user_hometown'});
} else { // unknown
// the user isn't logged in to Facebook.
}
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
`

Facebook app with error

I'm not a Facebook App expert. I grabbed this code from the FB website and I modified it to make it work with my app id (it is the only thing I changed. I added a couple of alerts too). Then I tried to use this code from a local webpage (that is: the page is on my desktop but my laptop is connected to the Internet).
Anytime I run this code I get a browser popup showing this error:
"An error occurred with MyAppName. Please try again later."
Can someone tell me what's going on here? It seems the FB.getLoginStatus never gets called too.
Any help is appreciated.
// initialize the library with the API key
FB.init({ appId: 'myAppID',frictionlessRequests:true });
// fetch the status on load
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
alert("1. not");
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
alert("2. alert");
// the user isn't logged in to Facebook.
}
});
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
$('#logout').bind('click', function() {
FB.logout(handleSessionResponse);
});
$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
alert("entered handleSessionResponse");
if (response.authResponse) {
alert('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
alert('Good to see you, ' + response.name + '.');
});
} else {
alert('User cancelled login or did not fully authorize.');
}
if (!response.session) {
clearDisplay();
return;
}
}
Have you changed the property myAppID to the ID of the Facebook app you are using?
FB.init({ appId: 'myAppID',frictionlessRequests:true });
The myAppID should contain a unique Facebook App ID which you can fetch on the Facebook App page. Maybe you just copied the code without changing this.

Categories

Resources