Need help getting my web site to publish info to Facebook wall - facebook-graph-api

SO I am trying to have my web site publish info to a user's facebook page. Where I am now is that I placed the following code (as instructed by another stackoverflow contributor), which is getting executed however the alert with "error occurred" comes up. Do I need to request the publish_stream permission as well? If so, I cannot figure out how to add that to my code. Sorry, I'm not much of a scripter and I have very limited knowledge on doing any integration into facebook. My ultimate goal is to be able to post information to a users facebook page on their behalf (this won't be done without their permission). Any help would be much appreciated:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXXXXXXXXX', // App ID
channelUrl : '//www.XXXXXXXXXXXXXX.com/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
oauth : true
});
});
// Additional initialization code here
};
// 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));
</script>
<SCRIPT language="JavaScript">
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
</SCRIPT>
<SCRIPT language="JavaScript">
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
})
</SCRIPT>

Why don't you expand the error handling a little bit?
alert("Error occured: " + response.error.message);
And did you check the console log for errors? Maybe authentication didn't work.

Related

'statusChangeCallback' is not defined Facebook Javascript SDK Login Error

For New Developers who are trying to integrate facebook login and authentication in their websites, they might receive the error if they'll simply try to copy the tutorial from Facebook Help for Developers.
Error is : Uncaught ReferenceError: statusChangeCallback is not defined
Code:
<script>
function checkLoginState() {
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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function () {
FB.init({
appId: '<Your App ID>',
cookie: true,
xfbml: true,
version: 'v2.12'
});
FB.AppEvents.logPageView();
};
</script>
<fb:login-button scope="public_profile,email"
onlogin="checkLoginState();">
</fb:login-button>
<div id="status"></div>
The solution is that new developers are forgetting to write success callback function in their code. The problem occurs when they try to copy the code from Facebook's Guide that comes immediately after Facebook App Registration.
In your HTML define a div with id status <div id="status"></div> just before the <script> tag.
Please include the javascript method below for the API to work. I have written some console.log verbose text. You can delete this text and replace with yours.
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.
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 + '!';
});
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}

Facebook api undefined issue

THis is my first time trying to use the Facebook javascript SDK so please bear with but I am having issues trying to retrieve an email address from the Facebook API. I have the code below in my site:
<script>
window.fbAsyncInit = function() {
FB.init({`enter code here`
appId : 'my id',
xfbml : true,
version : 'v2.5'
});
};
(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 think I have connected successfully to the api as when I add a like button for testing:
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
it seems to load in all buttons from the api.
WHen I try to retrieve a users name however I get an error message saying "undefined". Here is my code for attempting to retrieve username
jQuery(".test123").click(function(){
FB.api(
'/me',
'GET',
{"fields":"id,name,email"},
function(response) {
alert('Your name is ' + response.name);
}
);
I've doublechecked on the Graph API and it seems im using the correct method so not sure what the problem could be and all other articles i've seen seem to make the same call or something similar and more simple like:
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
});
But nothing has worked for me yet.
You need to authorize the user with FB.login first:
FB.login(function(response) {
if (response.authResponse) {
//user just authorized your app
}
}, {scope: 'email,public_profile'});
Here´s a tutorial: http://www.devils-heaven.com/facebook-javascript-sdk-login/
...and here´s the official page for FB.login: https://developers.facebook.com/docs/reference/javascript/FB.login/
Without authorization, you can´t get any user data.

Client-side access token doesn't function after a server-side call (FB Graph API v2.0)

First, a facebook user is logged client-side with using Facebook JS SDK.
FB.init() is called with the following parameters:
{
version : 'v2.0',
appId: '...',
status : true,
cookie : true,
xfbml : false
}
Then, in PHP, a session is created:
$session = (new FacebookJavaScriptLoginHelper())->getSession();
Once FB API calls have been made from PHP, I still can continue calling FB API from withing js.
But as soon as my page sends a new command to the server instructing it to make an FB API call, it doesn't work the second time, and the FB API says:
An access token is required to request this resource.
Obviously, this is called one more time and after that it stops working:
$session = (new FacebookJavaScriptLoginHelper())->getSession();
If the user updates the page in his browser, the next call from the server will work again. What I want instead is to keep querying FB API from both the server and the browser simultaneously without reloading the page.
It is out of date, but maybe will help someone
<?php
//some code here - requires and uses
FacebookSession::setDefaultApplication($SETTINGS['fbappid'], $SETTINGS['fbsecret']);
$helper = new FacebookJavaScriptLoginHelper();
$session;
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
//
} catch(\Exception $ex) {
//
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $SETTINGS['fbappid'] ?>',
xfbml : true,
version : 'v2.0',
status : true,
cookie : true
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.login(function () {
FB.api('/me', {
fields: 'id'
}, function (response) {
console.log(response);
});
}, {
scope: 'publish_actions'
});
} else if (response.status === 'not_authorized') {
} else {
}
});
};
(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>
<div id="fb-root"></div>
<?php
//here url to go to my app
echo "<a href='...'>Sign in to Facebook application</a>";
if ($session) {
echo "<br/>logged in";
}
?>
</body>
</html>
Note that login comes after second access to page if cookies were not set. So ajax request is needed to check properly.

Access token doesn't contain any scopes

I want to get a list of my friends with their name, current location and profile picture. I executed the query and the access token (with the required scope parameters) in the GRAPH API explorer tool and it works fine --> https://developers.facebook.com/tools/explorer?method=GET&path=me%2Ffriends%3Ffields%3Dname%2Clocation%2Cpicture
But everytime I execute the application, I get an access token without the required scope (it has none). How can I send my scopes to the access token?
Scope I want to give to the access token: Scopes: friends_location user_location user_relationships
I work in a localhost environment.
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script js.src = "//connect.facebook.net/en_US/all/debug.js"></script>
<script>
var accessToken
var uid
window.fbAsyncInit = function() {
FB.init({
appId : '493774134048550', // App ID
channelUrl : '//localhost/Facebook', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
testAPI(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
//FB.login();
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
// FB.login();
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;µ
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
}
}, {scope: 'friends_location, user_location, user_relationships'});
};
// 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));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
//FB.api('/me', function(response) {
// console.log('Good to see you, ' + response.name + '.');
// console.log(response);
//});
///me/friends?fields=name,location,picture&accesstoken=CAACEdEose0cBAFhNXAYgMjfAPWNxGZAdNdEJ6s2GAyIQp4zicpV0ZBZCeVINbiLvIxaFl33N0I1gZAZArREsHmOGiqQX2HPaNZCiU4W4Nq3VA12TrreKfeOtFSMvmZC8c1qYqu85NZAzzWDXWH5foXIWfPFk1ZBScNbAZD
FB.api('/'+uid+'/friends?fields=name,location,picture&accesstoken='+accessToken, function(response) {
//FB.api('/'+uid+'/friends?fields=name,location,picture&accesstoken=CAACEdEose0cBAJayThSg77Ydil76EM0W4zuJ9l29yKoIxlu6g37ZAX1CWQhpTStBL48xoX5g0Bbe8Va4wr6qqT2ft5tZBoNDZCWFYF7TtwmBnTDOSGWruOp0pSS9Ws1phfl5wiFbHeZAyUbdZBDdx3GLBHeysn6EZD', function(response) {
var teller1 = 0;
console.log('Good to see you, ' + response.name + '.');
console.log(response.data);
for (var i=0;i<response.data.length;i++)
{
if(response.data[i].name && response.data[i].location && response.data[i].picture){
console.log(response.data[i].name);
console.log(response.data[i].location.name);
console.log(response.data[i].picture.data.url);
teller1++;
}
//<img border="0" src="console.log(response.data[0].picture.data.url)">
}
console.log(teller1); //aantal gebruikers met naam, locatie en picture
console.log(response.data.length); //aantal gebruikers in totaal
});
}
//Logout
function fbLogout() {
FB.init();
FB.logout(function (response) {
//Do what ever you want here when logged out like reloading the page
window.location.reload();
});
}
</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.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
<span id="fbLogout" onclick="fbLogout()"><a class="fb_button fb_button_medium"><span class="fb_button_text">Logout</span></a></span>
</body>
</html>
Replace the code under response.status === 'connected' with this. Remove all other parts in the original code where the scope was added. (you only have to add it here)
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
if(accessToken)
{
// alert("Connected WITH accesToken");
testAPI();
}
else{
// alert("Connected WITHOUT accesToken");
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log(uid);
console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
}

Automated facebook post to wall with Javascript

I have a facebook application in which the user is authenticated with PHP and grants permissions to the app, including publish_stream.
During the application, the user is going through several screens.
On the last screen, the is user chooses if they want to share a post on their wall.
If they do, an automated and formatted post should be posted on their wall.
I've tried to do it with Javascript but it didn't work. Can you see what's wrong?
Thanks!
Here's my code:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY APP ID',
status : true,
cookie : true,
xfbml : true
});
};
(function() {
var e = document.createElement('script');
e.src = 'http://connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<script>
function postToFacebook() {
var body = '';
var params = {};
params['message'] = 'MESSAGE';
params['name'] = 'NAME';
params['description'] = '';
params['link'] = '';
params['picture'] = 'https://www.URL.com/pic.jpg';
params['caption'] = 'CAPTION';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
// alert('Error occured');
} else {
// alert('Post ID: ' + response);
}
});
}
</script>
From reading your question and the various comments it seems to me that the users session information is not persisting into the JavaScript SDK - this assumes that there is a valid user session being maintained serverside.
First of all you should check that you are using the most up to date PHP SDK. To double check download and install the latest version from GitHub.
I think this should solve your problem as the cookies containing the authorised users session data should be passed between the PHP and JavaScript SDKs.
If that doesn't work I have a suspicion that the user is not being authenticated correctly serverside. In which case you could try the following.
Before you postToFacebook() you should check the users the users logged in status and log them in if necessary. For example:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
postToFacebook();
} else {
// no user session available, someone you dont know
FB.login(function(response) {
if (response.authResponse) {
// logged in and connected user
postToFacebook();
} else {
// User cancelled login or did not fully authorize
}
}, {scope: 'YOUR,REQUIRED,PERMISSIONS'});
}
});
You are not calling the function postToFacebook()!
window.fbAsyncInit = function() {
FB.init({
appId : 'MY APP ID',
status : true,
cookie : true,
xfbml : true
});
postToFacebook();
};
When you attempt to do this:
FB.api('/me/feed', 'post', params, function(response) { .. });
You need to pass the access token along with the call. I assume you have it on the php/server side, so then:
FB.api('/me/feed/access_token='[INSERT_ACCESS_TOKEN], 'post', params, function(response) { .. });