JavaScript code for posting to Facebook - facebook-javascript-sdk

I am writing a simple JS program to post on FB.
The login script looks something like below:
indow.fbAsyncInit = function() {
FB.init({
appId: '1469527639#######',
version : 'v2.0',
xfbml : true,
status : true,
cookie : true
});
// fetch the status on load
FB.getLoginStatus(loginChecker);
};
(function(d, s, id){
var js;
var 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'));
function loginChecker(response){
if(response.status === "connected"){
console.log('This app is already authorized');
} else if(response.status === "not_authorized") {
console.log('This app is not authorized');
} else {
console.log('user is not logged into fb');
FB.login(function(){}, { scope: 'publish_actions', return_scopes: true});
}
}
The above script doesn't exactly perform as per expectation. It does display the Facebook login box, however after I enter my credentials, it does not ask for permission to post on wall.
I have another function that is suppose to post a message on the user's wall once the user is logged in. But since the above script does not ask for these permissions, i am unable to post.
As per Facebook documentation, i should be asking for permissions using
{ scope: 'publish_actions', return_scopes: true}
I am already doing this.
The button that posts on the user's wall is simple :
$('#postit').bind('click', function(){
var messageToPost = document.getElementById("messageArea").value;
FB.api('/me/feed','post',{message: messageToPost},function(response){
if(!response || response.error){
console.log('There was a issue in posting your emssage');
} else {
console.log(response.id);
}
});
});

Most permissions need to get approved by Facebook before they can be used by Users. Without approval, they only work for App Admins and other Users will only get basic permissions in the login process. See the change log and review guidelines for more information:
https://developers.facebook.com/docs/apps/changelog
https://developers.facebook.com/docs/apps/review
Btw, make sure the message parameter is always 100% user generated, or you will definitely not get through the review process with publish_actions.

Related

facebook login/logout issue in website

I’ve taken below code from Facebook developer, while login to FB it's showing only logout button not showing user name and profile with logout button. Is it possible to add our own button instead of Facebook login button?
<html>
<head><title>facelogin<title></head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '478566162309261',
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.
testAPI();
} 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();
} 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();
}
});
};
// 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 + '.');
});
}
FB.logout(function(response) {
// Person is now logged out
});
</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. -->
<div class="fb-login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="true">
</div>
</body>
</html>
You can use your own button and call FB.login on click:
document.getElementById('loginBtn').addEventListener('click', function() {
//do the login
FB.login(function(response) {
if (response.authResponse) {
//user just authorized your app
document.getElementById('loginBtn').style.display = 'none';
getUserData();
}
}, {scope: 'email,public_profile', return_scopes: true});
}, false);
Source: http://www.devils-heaven.com/facebook-javascript-sdk-login/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</script>
<script>
window.fbAsyncInit = function () {
// FB JavaScript SDK configuration and setup
FB.init({
appId: // FB App ID
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse social plugins on this page
version: 'v2.8' // use graph api version 2.8
});
// Check whether the user already logged in
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
//display user data
getFbUserData();
}
});
};
// Load the JavaScript 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_GB/sdk.js#xfbml=1&version=v2.8&appId=FB APP ID";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Facebook login with JavaScript SDK
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
} else {
document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
}
// Fetch the user profile data from facebook
function getFbUserData() {
FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
function (response) {
document.getElementById('fbLink').setAttribute("onclick", "fbLogout()");
document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
document.getElementById('userData').innerHTML = '<p><b>FB ID:</b> ' + response.id + '</p><p><b>Name:</b> ' + response.first_name + ' ' + response.last_name + '</p><p><b>Email:</b> ' + response.email + '</p><p><b>Gender:</b> ' + response.gender + '</p><p><b>Locale:</b> ' + response.locale + '</p><p><b>Picture:</b> <img src="' + response.picture.data.url + '"/></p><p><b>FB Profile:</b> <a target="_blank" href="' + response.link + '">click to view profile</a></p>';
});
}
// Logout from facebook
function fbLogout() {
FB.logout(function () {
document.getElementById('fbLink').setAttribute("onclick", "fbLogin()");
document.getElementById('fbLink').innerHTML = '<i class="fa fa-facebook-official" aria-hidden="true"></i>';
// document.getElementById('fbLink').innerHTML = '<div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="login_with" data-show-faces="false" data-auto-logout-link="false" data-use-continue-as="false"></div>';
document.getElementById('userData').innerHTML = '';
document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
});
}
</script>

FB.login inside FB.getLoginStatus popup window blocked

I'm trying to integrate Facebook login into my website with Facebook Javascript SDK. According to the step by step instructions provided by Facebook Developer document here, here is the test code I wrote:
<script>
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 : 'v2.1', // use version 2.1
status : true, // check FB login status
});
};
function fblogin() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert('Logged in.');
}
else {
FB.login();
}
}, true);
}
</script>
<button onclick="fblogin()">login</button>
<script src="//connect.facebook.net/en_US/sdk.js"></script>
Sorry, because of the restriction of website domain, I can't take this to fiddle. But I tried on my own domain, the Facebook login window popuped in Chrome and Firefox, but blocked by Safari. This is kind of weird, is there anything wrong for the code snippets provided by Facebook Developer Document?
As we already discussed in the comments, FB.login must be called on user interaction, the example in the docs is not correct.
This should be a working example how to do a login correctly, copied together from several articles in the Facebook docs:
<script>
//call this on user interaction (click)
function doLogin() {
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.');
}
}, {scope: 'email,user_friends'});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.1'
});
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
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
} else {
// the user isn't logged in to Facebook.
}
});
};
(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>
<button onclick="doLogin()">login</button>
More explanation: http://www.devils-heaven.com/facebook-javascript-sdk-login/

Facebook Login Javascript SDK

Facebook login is not working. I dont know why.
Following is the FB js code :
<script>
window.fbAsyncInit = function () {
FB.Event.subscribe('auth.statusChange', function (response) {
$(document).trigger('fbStatusChange', response);
});
FB.init({
appId: '419718681491265', // App ID
channelUrl: 'http://127.0.0.1/9377/', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
};
// 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));
Following is the App dashboard:
Please help..Tired of banging my head
The error is :
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
It seems that you can't test Facebook connect locally.
So a URL of 127.0.0.1 will not work.

Facebook App: Javascript SDK getLoginStatus not working in canvas

I have been racking my brain for 2 days now. I am trying to build a simple Facebook app using the Javascript SDK and I just want a simple alert if the user is not authorized using getLoginStatus(). It works fine in my website but not in the canvas. I get no alert. I am using very simple code that Facebook provides.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '354932757968708', // App ID from the app dashboard
channelUrl : '//www.staging.socialdigi.com/channel.html', // Channel file
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("Youre In");
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
alert("Not Authorized");
} else {
// the user isn't logged in to Facebook.
}
});
};
// 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>
I get the following errors in the console but have been told it doesnt have anything to do with my issue
Blocked a frame with origin "http://static.ak.facebook.com" from accessing a frame with origin "http://staging.socialdigi.com". The frame requesting access set "document.domain" to "facebook.com", but the frame being accessed did not. Both must set "document.domain" to the same value to allow access.
I do not have an ssl
Its in sandbox mode
I have the canvas url correct and nothing for secure canvas url
app id is correct
any help is appriciated
thanks

Authentication and OpenGraph

this is my first attempt playing around with facebook apps and OpenGraph. I've followed the example at developers.facebook.com. So far, so good.
What I am trying to do though is:
When clicking a certain image, check so that the user is logged and have authenticated your app. I want the user to be able to use the page without going through authentication. Only one specific action (clicking that image) requires that the user authenticate.
If the user is logged in and have authenticated your app then publish a message on the user's stream.
If the user is not logged in and/or have not authenticated your app show the authentication dialog if the user clicks on the image. Once accepted, post a message on the user's stream.
<a onclick="fb_login();" href="#" class="productlink1"><img id="product1" onclick="postCook()" alt="" src="img/fressko_heart_black.png"/></a> <a class="productlink2"><img id="product2" alt="" src="img/fressko_checked_black.png"/></a>
I know this is not the ultimate piece of code, especially as it has two onclick="" that will trigger at the same time. So, I need a different solution to that.
The JavaScript function to post on the user's feed looks like this:
function postCook()
{
FB.api(
'/me/xxxxxx:cook',
'post',
{ recipe: 'http://www.zzzzzzz.com/test/' },
function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Cook was successful! Action ID: ' + response.id);
}
});
}
The JavaScript to authenticate the user looks like this:
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxx',
oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});};
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_stream'
});
}(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);}());
Does anyone have any good solution to my problem? Or a kick in the right direction. I prefer using PHP usually, but for this mission JavaScript seems to be the weapon of choise.
Regards,