Reading a Facebook personal page posts - javascript

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/

Related

Login with facebook using php and javascript sdk on captive portal

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'));

Meteor: Facebook basic API call error: access token

I am currently trying to make a simple API call to show some user data (including a friends list).
I have a working Facebook login with the following request permission (
'click .facebook': function() {
Meteor.loginWithFacebook({ requestPermissions: ['email', 'read_friendlists', 'accesToken']},
function (error) {
if (error) {
return console.log(error);
}
});
},
Than I initialize facebok through
Template.friendsList.rendered = function(){
window.fbAsyncInit = function() {
FB.init({
appId : '278237565717322',
xfbml : true,
version : 'v2.0'
});
};
(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'));
And I want to make a simple API call with
"click .facebookfriends": function(){
FB.api('/me', function(response) {
console.log(response)
});
}
This gives me the following error:
code: 2500
message: "An active access token must be used to query information about the current user."
type: "OAuthException"
I have tried several examples but cannot seem to find a way to do loginWithFacebook and get the proper accesstoken. Could anyone help me with getting a proper access token set up? Much appreciated!
It looks like you are mixing the Meteor package Facebook OAuth login flow with Facebook's own JS SDK. Whenever I did stuff with FB on Meteor I avoided the JS SDK and opted purely for the Meteor package. Regardless it seems your problem is that you are getting the access token via the meteor package but the the FB JS SDK has no access to it when you call FB.api({ ... })
Try something like:
server:
Meteor.methods({
fb_me: function() {
var user = Meteor.users.findOne(this.userId);
//note: I don't have access to a meteor project hooked up to the FB API
//so where the access token is stored in a user object may differ,
//I got this from an old project. Try logging user here to find it
//if this doesn't work
var accessToken = user.services.facebook.accessToken;
if (!user || !accessToken)
throw new Meteor.Error(500, "Not a valid Facebook user logged in");
return HTTP.get("https://graph.facebook.com/me", {
params: {access_token: accessToken}}).data;
}
});
client:
"click .facebookfriends": function(){
Meteor.call('fb_me', function(err, res) {
if (!err)
console.log(res);
}
}
That works without having to use the FB JS SDK at all.
Since it's likely you would be letting your client make a lot of API calls I would suggest you make a single Meteor.method that takes a API endpoint (e.g. /me) as an argument and returns data to the client similar to the FB.api method Facebook provide.

Facebook access token changes on every pageload

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

Facebook button login issue (after successful login)

I am trying FB login for a site for first time. I am able to see the FB button and the popup window shows with what appears to be correct FB login with my app name, so i think that part is good. my issue is after clicking login I enter the user/pass, then window closes and nothing else happens. I know I am logged in because when i click the FB again it pops up and closes, so i guess it knows I am logged in to FB. but i cant see any of my calls to write to console, and I am not sure how to make it do something else after the loging... Maybe I am not understanding what happens after the login to FB is successful, am i missing something? . here is what I have tried so far.
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
}
function doLogin() {
FB.login(function(response) {
if (response.authResponse) {
console.log('Hello! Getting account information.... ');
FB.api('/me', function(response) {
console.log('Hello, ' + response.name + '.');
});
} else {
console.log('User not fully authorize.');
}
});
}
// 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 testFbLogin() {
console.info("Testing you are Logged in...");
}
In your FB app configuration there are settings for the domains and subdomains this app can use.
I guess you are trying to use the login from some development machine which name do not match the configured parameters for domains and subdomains for your FB app.
If you inspect the network communication (Crome developer tools are excellent and easy to use for this) you will see the error that FB returns and this will give you better idea what is going on.
If this is the case, then:
Open /etc/hosts (unix) or C:\WINDOWS\system32\drivers\etc\hosts.
If your configured domain is example.com, then add this line:
127.0.0.1 dev.example.com
When you are testing, open dev.example.com in your browser and it should work.
As alternative you can edit your app at FB and set the "Site URL" to
http://localhost/myapppath or only http://localhost

Using Parse for Facebook login but i get --https://api.parse.com/1/users 404-- After Refreshing 3 Times

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

Categories