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.
}
});
}
Related
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/
The code below is from developers.facebook.com.
// This is called with the results from from FB.getLoginStatus().
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.';
}
}
User clicks on "Facebook Login" button and logs in through Facebook OAuth.
Once the user logs in, the response object which gives user's email, name, etc is on the browser, fine. Now, how can I check if the response.email (user's email) is on my database table Users? What's the right way to use response.email in the SQL query?
First thing, make sure the login is with the scope "email address"
FB.login(function(response) {
// handle the response
}, {scope: 'email'});
Testapi function will first get the email address of the current user. And response will contain the email address. You should have a service which 'retrieves' email address from the front end, check in the db whether the email address is already existing and 'return' response (may be as simple as 'yes' or 'no')
function testApi(){
FB.api('/me', function(response) {
$.ajax({
type: 'GET',
url: "service/isEmailExisting?email="+response.email,
success:function(data){
alert(data);
}
});
});
}
If I have a user who is already logged onto facebook but remove my app from his/her account, how can I just prompt for the publish_stream only upon entering my app again since the user has already logged in?
Thanks.
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
uid = response.authResponse.userID;
accesstoken = response.authResponse.accessToken;
SrReferral = '#ViewBag.Referral';
window.fbuserid = uid;
var postData = { facebookUID: uid, facebookAccessTok: accesstoken, facebookSrReferral: SrReferral };
$.ajax({
url: '#Url.Action("DisplayGolfers")',
type: 'POST',
data: postData,
dataType: 'html',
success: function (responseText) {
$("#container").html(responseText);
}
});
} 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.
window.FB.login(function (response) {
if (response.authResponse) {
uid = response.authResponse.userID;
accesstoken = response.authResponse.accessToken;
SrReferral = '#ViewBag.Referral';
window.fbuserid = uid;
var postData = { facebookUID: uid, facebookAccessTok: accesstoken, facebookSrReferral: SrReferral };
$.ajax({
url: '#Url.Action("DisplayGolfers")',
type: 'POST',
data: postData,
dataType: 'html',
success: function (responseText) {
$("#container").html(responseText);
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
alert('User cancelled login');
}
}, { scope: 'publish_stream' });
};
});
}
Seems that I misinterpreted your question and you want user to stay logged in even if he removed application from his account on Facebook. This is really bad and easily may became security issue.
Once user removed your application he shouldn't be logged-in!
In case you don't want to prompt the user for permissions before he visits your app for the next time you should define what is "next time" in your case (hour/day/browser-session/etc) and set some cookie/session to check every visit if that is the correct time to prompt.
You can use second parameter for FB.getLoginStatus to always get fresh status of user (which will not return connected for user who removed your app).
FB.getLoginStatus(function(response) {
// this will be called when the roundtrip to Facebook has completed
}, true);
See "Roundtrips to Facebook's servers" section of FB.getLoginStatus documentation
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.
how can i this code to get user id in another functions and use as global variable??
function get_id() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
}
fb_user_id = get_id();
Your best bet would be to set this variable inside the function instead of assignment through calling:
(function(w) {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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
w.fb_user_id = response.authResponse.userID;
w.accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
})(window);
Then later on in your page (provided the call is not dependent on this one immediately), you can access your variable anywhere on the page as the global variable fb_user_id (also known as window.fb_user_id.
If you need to run code as soon as the user ID is ready, you will need to use a callback. If you are using jQuery 1.5 you can also use jQuery Deferreds to help with the synchronicity issues:
var getUserId = function () {
return $.Deferred(function(d) {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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 auth = response.authResponse;
d.resolve(auth.userID, auth.accessToken);
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
d.reject();
} else {
// the user isn't even logged in to Facebook.
d.reject();
}
});
}).promise();
};
getUserId()
.done(function(userId, token) {
// userId and token are available in here
})
.fail(function() {
// run some code in here if not authorized
// or something else failed;
});
JavaScript is asynchronous in nature. You will have to call back to another function within the response function.