i am creating login code for facebook connect on our site,
however i cannot find how to check if the user has the required permissions.
with the old javascript, one dialog would be opened for each permission and the return code would say if the permission was accepted or not, how does it work with the javascript code?
here is the code i got so far, with the TODO where i want to check if the user has got permissions
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'MY API KEY', status: true, cookie: true,xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
alert("logged in");
//TODO: check if all perms has been accepted!!!!
//if they have NOT been accepted, I want to logout the user
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, again, check if all perms has been accepted
alert("already logged in");
}
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<fb:login-button perms="email,user_birthday,status_update,publish_stream" >Login with Facebook</fb:login-button>
btw, in the documentation they have this example
http://developers.facebook.com/docs/reference/javascript/FB.login
where they use custom buttons, that's why i suspected that there would be something similar for the fb:loginbutton
FB.Event.subscribe('auth.login',function(response) {
if(response.session) { //checks if session is true
alert('logged in');
if(response.perms) { //checks if perms is true = permissions are granted
alert('perms granted');
}
else { //if perms is false = no permissions granted
alert('no perms');
}
}
else { //if something goes wrong
alert('login failure');
}
});
Original Facebook guide:
http://developers.facebook.com/docs/reference/javascript/FB.login
I made this solution to check for "user_friends" and "publish_actions" permissions, if not allowed the both, force the user to "re-autenticate". The callback function will only be called when all permissions are given.
function login(cb,forceAuth) {
FB.getLoginStatus(function (response) {
if (response.status !== 'connected' || forceAuth==true){
FB.login(function (response) {
checkPermissions(cb,false);
}, {scope: 'publish_actions,user_friends'});
} else {
checkPermissions(cb);
}
});
}
function checkPermissions(cb,forceAuth){
FB.api(
"/me/permissions",
function (response) {
if (response.data[0]['publish_actions']==undefined || response.data[0]['publish_actions']==0 ||
response.data[0]['user_friends']==undefined || response.data[0]['user_friends']==0) {
if (forceAuth!=false)
login(cb,true);
} else {
cb();
}
}
);
}
How to use:
login(function () {
myLogedAndAllowedFunction();
});
Related
i'm using javascript sdk and i have already send to review my publish_action , they are approved. Anyway i can't publish my post , the way i require the scope is this:
FB.login(function(response)
{
...
}, {scope: 'email,publish_actions'});
When i try to publish the return error is:
(#200) The user hasn't authorized the application to perform this action
It's true, because in the facebook modal login, appears only the permission to read information of the profile, no the permission to publish. How i can solve?
EDIT
i add my complete code to better explain:
<script type="text/javascript">
/***FACEBOOK***/
function fb_publish_Photo(immaginelink,idfoto){
var testo_share= $("#share_text").text();
var wallPost = {
message: testo_share,
link:immaginelink,
picture:immaginelink
};
console.log(wallPost);
FB.api('/me/feed', 'post', wallPost , function(response) {
if (!response || response.error) {
console.log(response.error);
alert('Failure! ' + response.error + ' You may logout once and try again');
} else {
// alert('Success! Post ID: ' + response.id);
var PostId=response.id;
if(response.id!=null && response.id!=''){
FB.getLoginStatus(function (response) {
if (response.authResponse) {
} else {
// do something...maybe show a login prompt
}
}, {scope: 'publish_actions'});
}
}
console.log(response);
}, { scope: 'publish_actions'});
}
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.
//fb_login();
} else if (response.status === 'not_authorized') {
} else {
}
}
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?fields=email,first_name,last_name,name', function(response) {
//chiamata ajax per registrare/loggare l'utente
console.log(response);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_actions'
});
}
// 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 : 'xxxxxxxxxxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.4' // use version 2.4
});
// 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'));
/***end FB***/
</script>
EDIT
This is the only ref i can find in facebook documentation:
function myFacebookLogin() {
FB.login(function(){}, {scope: 'publish_actions'});
}
or
FB.login(function(){
// Note: The call will only work if you accept the permission request
FB.api('/me/feed', 'post', {message: 'Hello, world!'});
}, {scope: 'publish_actions'});
It seems simple, in login call i have to require permission, so why the publish permission dialog not appears in an approved app?
EDIT
this is a screen of my app permission
Publish_actions scope now seems to works correctly. I had two times scope request.
So I have been going through the facebook developer documentation and I have managed to get to a point where the user clicks the facebook login button and gives me publish permissions. Then my function will post something to their wall.
My question: Is their a way for my facebook app to post to the walls of all the users who have given my app publish permissions, using either the javascript sdk or the php sdk.
My current code:
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
console.log(response);
},{scope: 'publish_actions'});
} else {
FB.login(function(response) {
console.log(response);
},{scope: 'publish_actions'});
};
});
function postAPI() {
var body = 'We are testing the ability of posting on users behalf.';
FB.api('/me/feed','post',{message:body},function(response){
if (!response || response.error) {
alert('Error occurred');
} else {
console.log('Post ID: ' + response.id);
};
});
};
I have created a simple app which used FB Javascript SDK which posts on FB the things which are given in my webpage's textareas.
I am using fb.api for this and the problem is that it works only with my user id(from which I have created the app). For other ids, it doesn't work.Can someone help please? I want other users also to be able to post on their wall once they are logged in.
<html>
<head></head>
<body>
<div id="fb-root"></div>
<label>Give your message here:</label><br/>
<textarea id = "ta"></textarea><br/>
<label>Any image?</label><br/>
<textarea id = "pic"></textarea><br/>
<label>Any link?</label><br/>
<textarea id = "ta_link"></textarea><br/>
<button onclick = "testAPI()">Click To Post!</button>
<script>
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : 'AppID', // App ID
channelUrl : 'http://127.0.0.1/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
});
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("Connected");
//testAPI();
} else if (response.status === 'not_authorized') {
// not_authorized
login();
} else {
// not_logged_in
login();
}
});
};
function login() {
FB.login(function(response) {
if (response.authResponse) {
//testAPI();
} else {
alert("Can't connect")
}
});
}
function testAPI() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var tbmsg = document.getElementById("ta").value;
var tbimg = document.getElementById("pic").value;
var tblink = document.getElementById("ta_link").value;
var wallPost = {};
wallPost['message'] = tbmsg;
if(tbmsg == "")
{
alert("Message box can't be empty")
}
if(tbimg)
{
wallPost['picture'] = tbimg;
}
if(tblink)
{
wallPost['link'] = tblink;
}
FB.api('/me/feed', 'post', wallPost , function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert("Posted");
}
});
}
else
{
alert("Login first")
}
});
}
// Load the SDK Asynchronously
</script>
</body>
I am trying to build a Facebook app using Js file provided by them.
I am able to get User Registered for my App, But I have to post Feeds on their wall (also I don't want the Pre-Confirmation message for the User's Approval, User should only Login into his/her account).
Following is the Code:
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
FB.init({ appId: '<%: Facebook.FacebookApplication.Current.AppId %>', status: true, cookie: true, xfbml: true });
var userName;
FB.login(function (response) {
//alert('1');
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
//alert('Access Token = ' + access_token);
FB.api('/me', function (response) {
alert('Good to see you, ' + response.name + '.');
userName = response.name;
document.getElementById('btnPostFeed').style.display = 'block';
});
} else {
document.getElementById('btnPostFeed').style.display = 'none';
//console.log('User cancelled login or did not fully authorize.');
}
}, { scope: '' });
function SubmitPost(msg) {
try {
if (userName != null || typeof userName != 'undefined') {
var wallPost = {
message: msg + " By : " + userName,
picture: '',
link: '',
name: 'test app posted in your wall',
caption: '',
description: ('Test description')
};
FB.api('/me/feed', 'post', wallPost, function (response) {
if (!response || response.error) {
/*action*/
alert('Message could not be Posted.');
alert(response.error.message);
} else {
/*action*/
alert('Message Posted successfully.');
}
});
}
else {
alert('Please wait while User Info is Loaded..');
}
}
catch (err) { alert('SubmitPost: ' + err); }
My Main issue is:
I get (#200) The user hasn't authorized the application to perform this action
Following is the Screen shot for the App Registration:
What should I do for this?
Your scope is completely empty in this line
}, { scope: '' });
If your don't request the correct permission you will not be authorized for it.
But I have to post Feeds on their wall (also I don't want the Pre-Confirmation message for the User's Approval, User should only Login into his/her account).
This makes no sense, your user needs to approve you to post to their wall. If they only login they only grant you the most basic permissions exclusive of posting to their wall.
I need to login via facebook using javascript sdk and retrieve email id and general info of user.
Here is the my code. Please tell me where I'm going wrong:
<script>
window.fbAsyncInit = function () {
FB.init({ appId: 'your_app_id', status: true, cookie: true,
xfbml: true
});
FB.getLoginStatus(function (response) {
if (response.session) {
greet();
}
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
function greet() {
FB.api('/me', function (response) {
alert('Welcome, ' + response.name + "!");
alert('Your email id is : '+ response.email);
}
);
}
</script>
I think you're missing the login part of getLoginStatus(). Without login, you cannot prompt the user with email permission. Here's some helper code to get you pointed in the right direction.
FB.getLoginStatus(function (response) {
if (response.status=== 'connected') {
greet();
} else {
FB.login(function(response){/*do something*/},{scope:'email`});
}
});
Also response.session is for the old oauth, not the new oauth2. Please see:
http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
https://developers.facebook.com/docs/reference/api/permissions/
https://developers.facebook.com/docs/authentication/