Fetch facebook data using javascript FB.api not working when not logged in - facebook

I have the following code to display the users on my site.
function getFBData()
{
FB.api(
'/*fbID*/',
function (response) {
if (response && !response.error) {
/*CODE*/
}
}
);
}
getFBData();
It was working fine when a user is logged in, via Facebook plugin, into the site. But nothing is fetched when the user is not logged in.
Is a user really needed to be logged in to execute FB.api?

Actually user must be logged in to Facebook to use Facebook Api,
you can use the code below to check the state of the user to either get his data if connected or ask him to login again.
FB.init({
appId: 'xxxxxxxxxxxxxxxxxxx',
channelUrl: '//www.yoursite.com/fbsdk-channel.aspx',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.getLoginStatus(function (response) {
if (response.status === 'not_authorized') {
/* The user has already logged into FB but not authorized the your webpage */
}
else if (response.status === 'connected') {
/* The user has logged into FB and authorized the "App" to get their user information */
}
else { /* The user has not yet logged into FB */ }
}

It depends, you CAN use FB.api without authorization, but only for API calls that need an App Access Token. For API calls with a User Token, you do need authorization. Of course you canĀ“t grab details of a user (by ID) without authborization, so in your case you must authorize the user.
More information about Access Tokens and login:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
http://www.devils-heaven.com/facebook-javascript-sdk-login/

Related

I can't get a user access token with manage_pages permission

So I have a code that logs a user in and then should get a list of the user's Pages in which he is an admin of.
FB.login(function (r) {
if (r.authResponse) {
FB.api("/me/accounts", "GET", { access_token: r.authResponse.accessToken }, function (response) {
..//
});
} else {
// not auth / cancelled the login!
}
}, { scope: "manage_pages, publish_pages, publish_actions" });
The problem I think is the user access token generated does not have manage_pages permission even though I asked for it during log in. I confirmed this by getting the user access token generated after logging in and then using Facebook's Access Token Debugger. How do I get a user access token with manage pages permission?

facebook users who r not my friends but using the app

The new Facebook graph api has divided friends into Friends & Invitable_friends .
me/friends/ returns my friends who are using the app while me/invitable_friends/ returns only the list of my friends who are not using the app.
But in my app,a user may interact with random users too who may not be on his friend list.
So how do i get user data for those who are using the app but are not on my friend list.
Thanks.
I went through the same issue and solved it like that: when a user starts your app by default you ask for permission to access his public profile information, which includes real ID, name and some other. You simply store the user data (id, name, etc.)in a database. This way you keep track of all the people using your app and they can interact with each other.
JavaScript Example:
window.fbAsyncInit = function () {
FB._https = true;
console.log('here');
FB.init({ appId: 'xxxxxxxxxxxxxxxx', cookie: true, xfbml: true, oauth: true, version : 'v2.0'});
Login();
};
function Login() {
FB.login(function(response) {
if (response.authResponse){
checkUser();
}
else{
console.log('User cancelled login or did not fully authorize.');
}
}
);
}
function checkUser() {
FB.api('/me', function(response) {
$.ajax({
type: "get",
url: "cgi-bin/checkUser.cgi",
cache: false,
data: {"user_name" : response.name, "u_id" : response.id, "link" : response.link},
success: function() //onSuccess,
{
console.log("user " + response.name + " checked!");
},
error: function()
{
console.log("Error with server connection on user checking");
}
});
});
}
I don't know in what language you are writing the app but I believe that in every language you should call the "login" function, which asks the user for permissions and basically gets access to info.
To get details of users who are using the app but are not your friends,call the following
graph.facebook.com/v2.0/
?ids={comma-separated-ids}&access_token=app_access_token&fields=name,picture
access_token is a must else graph-api returns following error-
The global ID xyz is not allowed. Please use the application specific ID instead.
This will work for all users who have authenticated the app no matter their authentication date,but for any non-app user graph-api returns above error message.

How do I get publish_actions permission with Facebook

I follow a tutor for connection with Facebook which uses the following code to connect to Facebook successfully.
The code follows -
FB.Event.subscribe('auth.authResponseChange', 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;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", 'loadMainPage.ashx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} 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.
}
});
};
How can I ask for publish_actions permission ?
What platform are you using? See Facebook's official docs.
An excerpt:
Requesting permissions
Each type of login flow has its own method of requesting these permissions:
Web login with the JavaScript SDK uses a scope option with the FB.login function call.
Other types of web login should add the scope parameter to the Login
dialog URL that they redirect to.
Android login uses the setReadPermissions and setPublishPermissions
on the LoginButton class.
iOS login uses the readPermissions and publishPermissions properties
in the FBLoginView class.

what is response in FB.getLoginStatus

To detect the facebook user online/offline status we use the method FB.getLoginStatus method.
But, what does the paramater("response") mean and where does it come from in the below code snippet
the parameter response mean in the line " FB.getLoginStatus(function(response) "
FB.getLoginStatus(function(response) {
console.log(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;
console.log('User logged in and autenticated');
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
console.log('User logged in, but not autorized');
} else {
// the user isn't logged in to Facebook.
console.log('User not logged in');
}
}, true);
You are specifying a function to be called when the Facebook API has completed retrieving a response from the server. It passes the response object to the function which you specify. A typical response would be:
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
See facebook javascript docs for more info

Facebook Authentication - adding permission for accessing email address

It might be a basic question.
And also my English is poor...
I have a web service which needs Facebook login.
With JavaScript SDK, I can get users' basic information such as user ID, name, gender.
And now there are about 10000 users.
This time, I need to access users' email address.
I know I can get email address from new users by adding scope attribute.
However, from existed users, though I can access email address, I don't know how to display authorization dialogue for permission to access email address.
Any idea? Thanks in advance!
Below is a code snippet that I have used. Basically check their permissions using /me/permissions and show a reauthenticate link
<script>
var FB_config = {
API_ID: 123123123123,
PERMISSIONS: "publish_stream,email",
};
jQuery(document).ready(function(){
// initialise FB
window.fbAsyncInit = function() {
FB.init({
appId : FB_config.API_ID,
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.Event.subscribe('auth.statusChange', FBverifyLogin);
};
});
function FBverifyLogin(response) {
if (response.status === 'connected') {
checkPermissions(); // check permissions if the user is logged in
}
}
function checkPermissions(){
jQuery("#FBreauth").hide();
FB.api('/me/permissions', function(response) {
var permissions = FB_config.PERMISSIONS.split(",");
for(var i = 0; i < permissions.length; i++)
{
if(response.data[0][permissions[i]] == undefined || response.data[0][permissions[i]] != 1)
{
// user does not have full permissions, show reauth link
jQuery("#FBreauth").show();
break;
}
}
});
}
function FBreauth(){
FB.ui(
{
method: 'oauth',
display: 'popup',
app_id: FB_config.API_ID,
client_id: FB_config.API_ID,
redirect_uri: "http://www.facebook.com/connect/login_success.html",
scope: FB_config.PERMISSIONS
}
);
}
</script>
App permissions have changes. Please reauthorize this app