My code till now is this:
<script>
window.fbAsyncInit = function(){
FB.init({ appId:'my app id', status:true, cookie:true, xfbml:true});
FB.getLoginStatus(function(response){
if (response.status != "unknown") // makes sure the user is already logged in.
{
FB.api('/me', function(response) {
console.log(response);
});
}
});
};
// Load the SDK Asynchronously
(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));
</script>
The error that I'm getting in the console is "An active access token must be used to query information about the current user."
But I have already made sure that the user is logged in as seen from the code, then where am I making a mistake?
Update: From the answers and the comments, it seems like the problem is that my website is not authorized although the user is logged in.
I just want to display the user's real name on the website with a welcome message. Can I use facebook graph API for this?
I do not want to go into authorization step since that would seem unnecessary from the user's point of view.
I'm new to programming, javascript and facebook graph api, so please forgive any mistakes I might have made.
Where did you make sure the user is logged in? You did not authorize the user anywhere, you only checked if he is logged in. For example:
FB.login(function(response) {
if (response.authResponse) {
//user just authorized your app
}
}, {scope: 'email,public_profile'});
You may want to use getLoginStatus correctly too:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//user is authorized
} else {
//user is not authorized
}
});
Source: http://www.devils-heaven.com/facebook-javascript-sdk-login/
Related
I have problems with the captive portal. There is little to finish. My application works as follows:
The user connects to the WiFi network and is redirected to an
external page where he asks to login through facebook using php sdk;
Login occurs as expected in php sdk displaying the login pages and
everything else. Informed login the user is redirected to another
page that receives the code and state fields in the query string;
In this redirect page I call the sdk javascript to know customer
data, and to my surprise, on devices that have an older OS version
(iOS, windowsPhone or Android), when running FB.getLoginStatus (),
the response of the function shows that the user is connected,
however in android 7.0+ or iOS 9.0+ the user always appears as
disconnected.
I have already lost countless nights of sleep trying to solve this without success. If anyone has an idea why this is happening I will be very grateful.
let statusLogin = function () {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//you are loggedin
accessToken = response.authResponse.accessToken;
userID = response.authResponse.userID;
} else if (response.status === 'not_authorized') {
//loggedin but not authorized your app
alert('User is connected on facebook nut not authorized!!');
} else {
// the user isn't logged in to Facebook.
alert('User is not connected on facebook!!');
}
});
};
window.fbAsyncInit = function() {
FB.init({
appId : '00XXX811XXX0000',
status : true,
cookie : true,
xfbml : true,
version : 'v2.12'
});
FB.Event.subscribe('auth.statusChange', statusLogin);
statusLogin();
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.12&autoLogAppEvents=1';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
I'm working on a feature on our website to display my company's Facebook page posts on our Intranet site. I found this code and am having trouble.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<ourappid',
xfbml : true,
version : 'v2.8'
});
FB.AppEvents.logPageView();
FB.login(function (response) {
if (response.authResponse) {
//alert("You are logged in");
FB.api('/ourpageurl/feed', function(response) {
console.log("response",response);
})
} else {
alert("Login attempt failed!");
}
}, { scope: 'public_profile' });
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
I do not control our company's Facebook page. Our social media director provided me with the app id. When I run the code above on a browser where I have not logged into Facebook with my username, I get a pop up window asking for my Facebook credentials. When I run this on a browser where I have an active Facebook session, the code does nothing. Nothing inside the login callback function is executed.
I've also tried skipping the FB.login portion and just running
FB.api('/ourpageurl/feed', function(response) {
console.log("response",response);
})
immediately after FB.AppEvents.logPageView();, but I get an error object back complaining about an access token. As far as I've been able to tell, in order to get an access token, I have to run the login method. What am I doing wrong here?
First of all: You can only call FB.login on user interaction, or browsers will block the popup. If done correctly, FB.login opens a popup where you can authorize the App with your user account.
I assume that is not what you want. For getting the feed of an unrestricted Page, you can use an App Access Token - it is the only Token that does not need user authorization. Access Tokens are meant to be kept secret, so you need to do that API call on your server, NOT on the client with JavaScript. You also need to think about caching the result, if a lot of users hit the Page where you read/show the feed, you may hit an API limit on Facebook.
About Tokens in general:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
How can I perform an automatic Facebook Login with the Facebook JavaScript SDK like Hootsuite do?
With my code I can just access my Facebook app with my Facebook Account, but how can I create a non-facebook login to my website, but also be logged in to Facebook over the app?
Here is my code for normal Facebook Login:
<div id="fb-root"></div>
<script>
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
// 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.
document.getElementById('status').innerHTML = 'Verbunden';
} 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.';
}
}
window.fbAsyncInit = function() {
FB.init({
appId : 'AppID',
xfbml : true,
status : true,
cookie : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/de_DE/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
An App Login (and that is what hootsuite is using) implies that you must login to Facebook first - So there is nothing else to do. If you use the Facebook Login on hootsuite, you will need to sign in to Facebook first.
Don´t worry too much about Access Tokens, the JavaScript SDK usually takes care about that unless you want to do more complicated things like generating Extended Access Tokens and whatnot.
Login is very easy with the JavaScript SDK: https://developers.facebook.com/docs/reference/javascript/FB.login/v2.2
Just make sure you call that function on user interaction (mouse click) - else it may get blocked in the browser.
Edit: I see that you want to auto-login with Facebook if someone logs in on your website WITHOUT Facebook login. Well, that is not possible. Access Tokens are used for API calls, not for login. If a user is not logged in on Facebook, you can´t just log him in automatically. But you CAN store Access Tokens for later usage, those are valid even when the User is not logged in. About how to use Access Tokens and which ones are available, take a look at those articles:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
http://www.devils-heaven.com/extended-page-access-tokens-curl/
is it correct that the Facebook API access token changes on every pageload?
I thought once a token was obtained, it would stay the same until expiry.
I am using the Facebook SDK for Javascript.
Facebook says that with this SDK, there is no need to manually manage access tokens. The SDK just does it.
But is it correct that the token changes on every pageload?
My code is this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxx',
status : true,
xfbml : false,
cookie : true
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function check() {
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
console.log(response);
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
console.log(response);
} else {
// the user isn't logged in to Facebook.
console.log(response);
}
});
}
</script>
<span onClick="check()">test</span>
I just tested this and you are right, the Token changes with every page refresh. I would not worry much about it though, when using one of the SDKs (JavaScript, PHP, ...) you most likely don´t need to think about the Access Tokens at all.
And even if you need them (for managing Pages, for example), you can just use the last one.
The "older" Tokens are still valid btw, they don´t get invalidated. But they will stop working after 2 hours anyway.
There is also a second parameter you can set to "true": https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ (see "Roundtrips to Facebook's servers") - which may have explained the new Token, but you´re not using that either.
Facebook has recently changed its process of refreshing access token.
Try to use this if it works in you case:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
EDIT:
This will might help you as well. Link
I Used the instructions here: https://parse.com/docs/js_guide#fbusers (Facebook login using Javascript) to write a login page that uses Facebook authentication.
When I first login, all works perfect (Except a 'FB.init has already been called' warning in the console.)
When I Refresh the page, I see a "FB.login() Called when user is already connected" Error in the console. But I still get a "User logged in through Facebook" message as expected.
If I hit refresh Again, I now get a message box saying "User cancelled the facebook login or did not fully authorize" (Msgbox is defined in the code),
and in the console I now see that the POST to https://api.parse.com/1/users returned a 400 Error, as opposed to before in which i got a 200 OK.
This is my HTML Code:
<html><head></head><body> <div id="fb-root"></div>
<script src="http://www.parsecdn.com/js/parse-1.2.9.min.js"></script>
<script>Parse.initialize("<key>", "<key>"); // Additional JS functions here
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : '<id>', // App ID
channelUrl : '<path>/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
});
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
alert("User signed up and logged in through Facebook!");
} else {
alert("User logged in through Facebook!");
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body> </html>
I would appreciate it if anyone could spot the problem.
Thanks!
"User cancelled the facebook login or did not fully authorize" means that you are already logged in. Use chrome's developer tools console to check if your current user using this commmand:
Parse.User.current()
If you get an object, you are already logged in.
You can use Parse.User.logOut() to logout, then Parse.User.current() should return a null!
Also you can use Parse.User.current().get('authData')['facebook'], as mentioned here
Notes:
If logging out from parse logs you out of facebook, update your parse reference