How can I create a page post using Facebook Javascript SDK? - javascript

I need to be able to post to a user's business page using the Facebook Javascript SDK.
I have successfully logged my user's into facebook but when I try to use a function to post to the user's page, nothing happens. I have even tried to manually enter my own page id into the function to make it work but still nothing happens.
I log my user in using the following javascript which I got from the Facebook documentation and it works.
<script>
// 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 {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'my app id',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v3.3' // The Graph API version to use for the call
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
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 + '!';
});
}
</script>
I then altered the code to add a function called postapi() to test a post to the logged in user's page as shown below:
<script>
function postapi() {
FB.api(
'/{your-page-id}/feed',
'POST',
{ "message": "Awesome!" },
function (response) {
// Insert your code here
});
}
// 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 {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'my app id',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v3.3' // The Graph API version to use for the call
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
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 + '!';
});
}
</script>
I then use a button to open the login dialog and request the proper permissions as follows:
<fb:login-button scope="manage_pages,publish_pages,pages_show_list" onlogin="checkLoginState();">
</fb:login-button>
I successfully tested to see if this actually stored the user's access token by displaying the user access token in a textbox as follows:
function placetoken() {
var user_access_token = FB.getAuthResponse()['accessToken'];
document.getElementById("<%=TextBox1.ClientID%>").value=user_access_token;
}
I now need to be able to use the user access token to get a list of the pages (including page id and page access token) that the user manages so they can choose one to post to.
I have tried:
var user_pages=FB.api('/me/accounts', 'GET');
But I cannot figure out how to capture what the api returns.
I would like to be able to use the Facebook Javascript SDK to log user's in and post to their business pages.

In order to publish to a Page (as a Page, which is the only option), you need to to the following:
Authorize with the manage_pages and publish_pages permissions.
Get a Page Token of the Page in question with /page-id?fields=access_token
Use the Page Token to post with /me/feed
Example Request with Page Token:
FB.api(
'/me/feed',
'POST',
{message: 'Awesome!', access_token: 'the-page-token'},
function (response) {
// Insert your code here
}
);
Be aware that only users with a role in the App would see the new post, unless you put your App live and get the required permissions reviewed by Facebook.

Publishing on a page feed requires a page token valid for that specific page incl all required permissions granted by a page admin. Therefore you first need to retrieve a manage_pages permission with login, request a page token (via /me/accounts for example) for that specific page and then make the actual publish feed call.

Related

Redirect after Successful Facebook Login with API

I'm using JSF / Primefaces to build a web app in Netbeans. I chose the FB API / JS SDK to allow users to log into the app.
I'd like to redirect the user to another page upon a successful login.
I've an XHTML file that kinda works. However, within the testAPI() function, I added a window.location.href = 'http://www.google.com'; to test the redirection. It won't work unless I manually refresh (F5) the page after logging in.
Here's the full XHTML, testAPI around line 91:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:fb="http://www.facebook.com/2008/fbml">
<f:view contentType="text/html">
<h:head>
<f:facet name="first">
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
<title>PrimeFaces</title>
</f:facet>
</h:head>
<h:body>
<script>
// 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.
//window.location.href = 'http://www.google.com'; //Will take you to Google.
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function () {
FB.init({
appId: '1943608085935991',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v3.2' // use graph api version 2.8
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
};
// 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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
//If I uncomment the line below to redirect, the console logs and
//the getElementById lines won't work
//window.location.href = 'http://www.google.com';
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
//If I uncomment the line below, the test api will execute correctly
//except for the windo.location below:
//window.location.href = 'http://www.google.com';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<!-- I'm trying out these two buttons! -->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<fb:login-button autologoutlink="true"></fb:login-button>
<div id="status">
</div>
</h:body>
</f:view>
</html>
As you can see, the testAPI function has two lines commented, corresponding to the redirection I'm attempting (Google, as test).
I'm open to alternatives and I would totally understand if you suggest a better practice than what I'm doing.
Please let me know if you would like me to add more info, or another file.
Thank you a lot!

Facebook login web

I want to login into my website using facebook.
There is following example at https://developers.facebook.com/docs/facebook-login/web. But if I enter it into a html-file (with changing the app-ID of course) it just does nothing and I don't know why. Also in the web console I cannot see anything.
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// 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.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1234567890',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.3' // use version 2.3
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
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 + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
Could someone help me out and get this first example work?
Thanks in advance.
Best regards
Try:
Go to facebook developper page.
On settings tab, add your app domains into field "app domain" (it is your app url) after that, you have to wait some minutes and go to "status and review" and toggle your app on public mode. The effect appear after some minutes (20 - 30 minutes) and try again.
Your appid is 1234567890. Is it a coincidence or you just made it up? If it is the latter, go to developers.facebook.com to set up your app. Otherwise, the FB.getLoginStatus will get exception and will not execute statusChangeCallback.

Error in the response from facebook graph API

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/

automatic Facebook Login like Hootsuite with Facebook JavaScript SDK

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/

JS Facebook login iOS8

The login button on my facebook app has completely stopped working in iOS 8. I thought it was something I have done but when I take facebooks sample html from their site and apply it to my page it still doesnt work (my app id has been replaced with xxxxx). Basically the pop up window opens for facebook auth but never closes and returns to my app. Im just left with a blank which tab open:
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// 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.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function () {
FB.init({
appId: 'xxxxxxxxxxxxx',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.1' // use version 2.1
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
};
// 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/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
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 + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
The only solution I came up with is to degrade back to the server-side authentication flow when on iOS using full on redirects. Basically your app should hit a URL like this:
https://www.facebook.com/dialog/oauth?
client_id={app-id}
&redirect_uri={redirect-uri}
Which is a jarring experience on desktop, but is arguably a nicer experience on mobile, given that the user isn’t taken through the weird tab switching (which is the root of the new problem in the first place). To degrade to this flow ONLY on iOS, make sure your sign-in link is actually an href to the facebook authentication dialog (like the link above, or for you omniauth users on rails, is “/auth/facebook”). Then wrap the javascript where you invoke the client side flow in code that prevents it from being run on iOS (or all of mobile, if you want).
if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
[Facebook client side flow code here]
}
(please let me know in comments if anyone has a more elegant way of doing this)

Categories