facebook javascript permission dialog for email - facebook-graph-api

i have a question.... i am actually developing a facebook application with FB javascript SDK. In my application I need email permission for further processing. i am using
FB.Connect.showPermissionDialog("email");
but some how the dialog doesn't appears... here is my code
<script>
appid = '*************';
name = 'Palmchip Test App';
href = 'https://apps.facebook.com/*********/';
FB.init({
appId:appid, cookie:true,
status:true, xfbml:true
});
FB.getLoginStatus(function(response) {
if (response.session) {
alert("You are logged in...");
FB.Connect.showPermissionDialog("email", function(perms) {
if (!perms) {
alert("no access");
} else {
alert("accessed...");
}
});
}
else {
top.location.href='https://graph.facebook.com/oauth/authorize?client_id='+appid+'&redirect_uri='+href+'&display=page';
}
});
</script>
the alert which says you are logged in... works fine but then nothing happens .....

You need to upgrade to OAuth 2.0 ouath: true
You should use the new OAuth Dialog
You should be aware when upgrading that FB.getLoginStatus() will return different objects: response.authResponse

Try this code block
FB.init({appId: <?= APP_ID ?>, status: true, cookie: true, xfbml: true, oauth:true});
function getin(){
FB.login(function(response) {
if (response.authResponse) {
var regurl = "/login";
location.href=regurl;
} else {
var regurl = "/logout";
window.location.href=regurl;
}
}, {scope:'email'});
}
So when you call the getin() function , if the current user already gave you the email address it'll do nothing for him just will redirect him to /login url , but if the user is a new user then he/she will see a pop-up box asking for the email address once he/she allows that you can pull the email address using graph or fql. BTW response inside FB.login has the user id , access_toke and some more useful data so save that for further use.

Related

Can't Get Email from Facebook Login

I am working on putting Facebook login on my site. I'm not a very strong javascript coder, but usually find the code I need and, after some work and trial and error, get the results I need.
I got the login script working and the only thing I need (I think--remember javascript isnt my strong point so maybe you see some flaws here that I don't) is to obtain the email address from the login call. I have added 'email' to the scope and tried to access email from the response object as well as the user object. I know that email is valid because I am testing with my FB account and it was validated with email, not phone. But it comes up as undefined.
You'll see the spot where I am trying to get it in the myfacebooklogin function.
Anyone know how/why I cant access the email?
Also, does this code look solid?
Lastly, how would you best handle the session/state? In ASP (what the site is coded in--classic, not .NET) I use the session object if the person logged in traditionally. If they log out, I just set the session variable to "".But with this, would you just authenticate every page and use that as the session, or would you use the FB login to create an ASP session and use that?
Below is all of the code. The only other pieces are in the HTML body--a button to the myfacebooklogin function and a div that gets written to (which was part of the code I found so I left it in).
Thanks!
<script>
// 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'));
window.fbAsyncInit = function() {
FB.init({
appId : 'myAppId',
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
});
// 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.
//second parameter of FB.getLoginStatus is "true" to force a roundtrip to FB.
//if "true" not set, result will come from cache
//set "true" only when needed to save performance (for example, on login page)
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
},true);
};
// 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();
alert('1');
} 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.';
alert('2');
} 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.';
alert('3');
}
}
function myFacebookLogin() {
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 + '.');
alert(response.name);
alert(response.id);
//alert(response.mail);
});
// FB.api('/me', function(user) {
// console.log(user.name + ': ' + user.email);
// alert(user.email);
// });
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'public_profile, email', return_scopes: true}); //scope: 'publish_actions'
}
</script>
You need pass the fields in the url "/me" like:
FB.api('/me?fields=name,id,email', function(response) {

Django - How to setup and test facebook login before going to production?

So I am trying to add Facebook Login to my page but I am having some difficulties. I am trying to figure out how to test these features in development before I go to production but I don't completely understand how to do that.
I have followed the facebook api instructions so I think I have something that should work but I can't test. That code is below:
<script>
function fb_login() {
FB.login( function() {}, { scope: 'email,public_profile' } );
}
// 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 : '************',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// 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>
My App ID is correct in my application.
Here is my login button:
<img src="../../static/textchange/facebookloginbutton.png" border="0" alt="" height="42px;">
</div>
I made my own so I could choose another image.
So now when I try to login I get this error:
"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."
So I believe I have to choose another domain of some sort to test it? But I don't understand what I am supposed to choose? Do I have to start "hosting" so I can use a real domain? Can I do it locally?
I would appreciate any help in pushing me in the right direction.
Thanks.
You can configure your Valid OAuth redirect URIs under Client OAuth Settings in the Facebook Developers dashboard to allow whatever URL you are using locally. Or set the site URL to use your local URL.
your site URL should be http://localhost:8000/. I think the http:// matters
$scope.login = function() {
FB.login(function(resp) {
var args = { signed_request: resp.authResponse.signedRequest };
$http.get('/auth/facebook/callback', args).then(function(resp) {
// handle success
});
}, {scope: 'email,user_friends,user_location'});
};

Call Back Function Not Called In FaceBook Connect

e have written a code to use FaceBook Connect API. On click of facebook button, log in window is opened, i entered my facebook credentials and got logged in to facebook, but my call back function through which i should get the response from facebook is not getting called. Can any one please let me know where i got things wrong.
<script type="text/javascript">
$("document").ready(function () {
// Initialize the SDK upon load
FB.init({
appId: 'My APP ID', // App ID
scope: 'id,name,gender,user_birthday,email',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
//FB.Event.subscribe('auth.login', OnLogin);
FB.Event.subscribe('auth.login', function(response) {
alert('The status of the session is: ' + response.status);
});
});
// This method will be called after the user login into facebook.
function OnLogin(response) {
if (response.authResponse) {
FB.api('/me?fields=id,name,gender,email,birthday', LoadValues);
}
}
//This method will load the values to the labels
function LoadValues (me) {
if (me.name) {
alert(me.name);
}
}
</script>

call FB.login() after FB.init() automatically

i`m developing an app for Facebook.
My Code:
function init() {
window.fbAsyncInit = function() {
var appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
FB.init({ appId: appID,
status: true,
cookie: true,
xfbml: true});
login();
};
(function() {
var e = document.createElement("script");
e.async = true;
e.src = "https://connect.facebook.net/en_US/all.js?xfbml=1";
document.getElementById("fb-root").appendChild(e);
}());
};
function login() {
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'read_stream,publish_stream,offline_access'});
};
I want to call the "init" function and after "init" should call the "login" function (open up the Facebook Login Window) automatically.
But i always get "b is null"
FB.provide('',{ui:function(f,b){if(!f....onent(FB.UIServer._resultToken));}}); Error in Firebug.
Can anybody help me?
Does anybody have the same problem?
Thanks
You needn't have the facebook init stuff in a function, it can go straight on the page, then it will load at the same time, rather than waiting for a button click to load. Then you just need the login logic on the logiin button
<html>
<head>
</head>
<body>
<script type="text/javascript">
window.fbAsyncInit = function() {
var appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
FB.init({
appId: appID,
status: true,
cookie: true,
xfbml: true
});
// This bit adds the login functionality to the login
// button when api load is complete
document.getElementById("login").onclick = function() {
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'read_stream,publish_stream,offline_access'});
}
};
(function() {
var e = document.createElement("script");
e.async = true;
e.src = "https://connect.facebook.net/en_US/all.js?xfbml=1";
document.getElementById("fb-root").appendChild(e);
}());
</script>
<a id="login" href="somewhere.html">My login button</a>
</body>
</html>
You can put the login stuff in a method and automatically call the it after the FB.init, but most browsers will block the pop up window. You are better off waiting for the user to click a login button to make sure they see it properly, and it is generally good practise to only make things happen when the user explicitly requests them to. I think the facebook 'good practice' guide also mentions this somewhere.

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) { .. });