EDIT:
Finally after a long search, I found a solution to this:
heres my code:
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<fb:like href="http://developers.facebook.com" send="true" width="450" show_faces="true"></fb:like>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script>
FB.Event.subscribe('edge.create', function(href, widget) {
//alert('like '+href);
document.getElementById('download').style.visibility = 'visible';
});
FB.Event.subscribe('edge.remove', function(href, widget) {
//alert('dislike '+href);
document.getElementById('download').style.visibility = 'hidden';
});
</script>
<div id="download">Download</div>
</body>
</html>
This works as I wanted, but on page load by default the Download is shown, how do I detect on page load whether the user liked my page or not?
OLD QUESTION
I am having a website where I have some files for users for download, and have a like button next to it. I just want that download button to be visible only if the current user liked my page.
I am new to FB open graph and JS SDK, I tried following code(pasted in my website) :
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
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;
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
// the user is logged in to Facebook,
// but has not authenticated your app or
// the user isn't logged in to Facebook.
FB.login(function(response) {
if (response.authResponse) {
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
});
};
(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));
Even though I am logged in FB and using same browser, it always returns me with following error(firebug debug log)
code:2500
message : "An active access token must be used to query information about the current user."
I dont know much about FB API, am I doing something wrong?
Here's an edit of your code that should work:
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
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;
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
// the user is logged in to Facebook,
// but has not authenticated your app or
// the user isn't logged in to Facebook.
FB.login(function(response) {
if (response.authResponse) {
FB.api('me', function(user) {
if (user) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
});
};
(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));
To explain a bit, what I added was a function which checks whether a user has authorized your app yet (FB.getLoginStatus) and within the success handler of that function, I've added your API call. Within the else of this function, I've added a call to FB.login which will prompt un-authorized users to auth your app. If they successfully do this, your API call is made, if they chose not to, I've just left in the example console.log call, but you could replace that with anything you wanted.
Now, in order to track whether a user has liked your page or not, you need to make use of the FB.Event.subscribe function by tracking the 'edge.create' event.
Related
I already use this code,i get user name but i can't get email address please some example how to get email address in face api .but many user give some example it does n't work so give valuable code
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '64530546436364535', // App ID
channelUrl : '//WWW.loginhire.com', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login();
} else {
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));
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
testAPI();
} else {
// cancelled
}
}, { scope: 'email' });
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + ' Email: ' + response.email + ' Facebook ID: ' + response.id);
//console.log('Good to see you, ' + response.name + '.');
console.log(' Email: ' + response.email+'.' );
});
}
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '645304363653fghdfg', // App ID
channelUrl : '//WWW.channelUrl .com', // 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.
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 login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
testAPI();
} else {
// cancelled
}
}, { scope: 'email'/'phone' });
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.' + ' Email: ' + response.email + ' Facebook ID: ' + response.id);
//console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<fb:login-button show-faces="false" width="200" max-rows="1" scope="email" onclick="testAPI();" onlogin="Log.info('onlogin callback')">
Login with Facebook
</fb:login-button>
</span>
I am new to using the FB JS SDK so please bear with me..
I am currently trying to setup facebook login for a website. The problem I have is that when I click the login button and enter my login details facebook ONLY returns user info when I use the account I made the app on. When I use a different account response.authResponse returns a status of "unknown" which I find unusual.
The main function I'm reffering to here is this.loginUser.
I've also noticed that when I enter my details on the account I made the app on facebook will notify me that the app wants access to ... details however when I use a different account the login panel will disapear on login submit and not ask for permission.
Here is my code:
var FBUser = function(options) {
this.userInfo = null;
var that = this;
/* **********************************************
* Default parameter options
* **********************************************/
this.options = $.extend({
signInBtn: null,
messageContainer: null,
accountContainer: null
}, options);
/* **********************************************
* Initialise functions
* **********************************************/
this.init = function (){
//Load FB JS SDK
this.checkIfLoggedIn();
//Bind event handlers
this.bindEventHandlers();
};
//Check if user is already logged in, if so return data
this.checkIfLoggedIn = function(){
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log("You logged in before so were retrieving your info...");
// the user is logged in and has authenticated your app
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
that.userInfo = response;
that.showUserInfo();
// connected
} else if (response.status === 'not_authorized') {
alert("not connected");
// not_authorized
} else {
// not_logged_in
}
});
};
//Run event handlers to window
this.bindEventHandlers = function() {
if(that.options.signInBtn !== null){
//Trigger fb Login
$(document).on("click", that.options.signInBtn, function(){
console.log("triggered get login");
that.loginUser();
});
}else{
console.log("Btn ID's are null");
}
};
//Trigger FB login
this.loginUser = function(){
FB.login(function(response) {
console.log("RESPONSE IS: ");
console.log(response);
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
console.log('Welcome! You just logged in. Fetching your information.... ');
that.userInfo = response;
that.showUserInfo();
} else {
// sign out
console.log('User does not grant extended permissions');
}
}, {scope: 'email, read_friendlists, user_birthday, user_location'});
};
//Show user info
this.showUserInfo = function (){
var info = this.userInfo;
if(this.userInfo){
FB.api('/me', function(info) {
console.log('Good to see you, ' + info.name);
console.log("USER DATA IS: ");
console.log(info);
//Append user info
if(that.options.messageContainer){
$(that.options.accountContainer).show();
$(that.options.messageContainer).html(info.name)
.prepend('<img src="https://graph.facebook.com/'+info.id+'/picture" alt="'+info.name+'">');
}else{
console.log("facebook container is null");
}
if(that.options.signInBtn){
$(that.options.signInBtn).hide();
}else{
console.log("Login button is null");
}
});
}
};
//Log user out
this.FBLogout = function(){
FB.logout(function(response) {
console.log("user is now logged out");
$(that.options.signInBtn).show();
$(that.options.accountContainer).hide();
});
};
return this.init();
};
/* **********************************************
* Initialise FB app
* **********************************************/
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelUrl : ''
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.statusChange', function(response) {
alert('The status of the session is: ' + response.status);
});
/* **********************************************
* Initialise FB user object
* **********************************************/
//Make sure document is ready before creating object due to jquery references
$(document).ready(function (){
//FB initialise options
var FBUserOptions = {
signInBtn: '#fb_login',
messageContainer: '#welcome',
accountContainer: '#account_area'
};
//create FB user object
var fb_user = new FBUser(FBUserOptions);
});
};
/* **********************************************
* Load FB JS 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));
The HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Facebook Login</title>
<script type="text/javascript" src="static/js/plugins/jquery-1.9.1.min.js"></script>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="static/js/fb_login.js?=v33"></script>
<style type="text/css">
body{font-family: Arial, Helvetica, sans-serif;}
#account_area{display: none;}
</style>
</head>
<body>
<div id="fb-root"></div>
Login to facebook
<div id="account_area">
<div id="welcome"></div>
Sign out
</div>
</body>
</html>
<div id="fb-root">
</div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'myappid', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('auth.authResponseChange', 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;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", 'facebooklogin.aspx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} 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.
}
});
};
// 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>
<div class="fb-login-button" data-show-faces="false"
data-width="400" data-max-rows="1">
</div>
.cs code
var accessToken = HttpContext.Current.Request["AccessToken"];
var client = new FacebookClient(accessToken);
var me = client.Get("me") as IDictionary<string, object>;
string firstName = (string)me["first_name"];
string lastName = me["last_name"].ToString();
string id = me["id"].ToString();
string email=me["email"].ToString();
Other values can be obtained , except for email.
You have not added the permission to access the email.
Change your login code to this:
<div class="fb-login-button" data-show-faces="false"
data-width="400" data-max-rows="1" scope="email">
I had setup
<div id="fb-root"></div><div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1" scope="email, publish_stream"></div><script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({
appId: 'xxx', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML,
oauth : true
});
FB.Event.subscribe('auth.authResponseChange', 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;
// TODO: Handle the access token
$.post('/facebook/login', { accessToken: accessToken }, function (response) { if(response) {alert('Logged in')} });
} 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.
}
});
};
// 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));
The problem is when user click on Login button and Accept my app, the login dialog is closed and no event is fired so my post $.post('/facebook/login') also never fired unless I press F5.
How can I fire event right after login dialog box closed?
Just sharing.
Run in to a possible solution while reading Facebook documentation for answers.
http://facebook.stackoverflow.com/questions/3548493/how-to-detect-when-facebooks-fb-init-is-complete
You could run your $.post('/facebook/login') inside fbEnsureInit(); <-- referring to serg's answer.
Using an interval callback to check for login status might be a way to do it.
You can reload the page with: window.location.reload(); so you don't need to press F5,
An FB.login example:
FB.login(function(response) {
if (response.authResponse) {
console.log('Application authorized.');
window.location.reload();
} else {
console.log('You cancelled login or you did not fully authorize the app.');
}
}, { scope: 'email' });
or you can use a subscribe event:
FB.Event.subscribe('auth.authResponseChange', function(response) {
console.log('The status of the session changed to: '+response.status);
window.location.reload();
});
I need to get the access token from FB.login method in Javascript SDK. My login code is
FB.login(function(response) {
if (response.session) {
if (response.perms) {
} else {
// user is logged in, but did not grant any permissions
alert("No Permission..");
}
} else {
// user is not logged in
alert("Please login to facebook");
}
}, {perms:'read_stream,publish_stream,offline_access'});
Is there any way to get access token? I am able to get the access token using PHP.
You can get access token using FB.getAuthResponse()['accessToken']:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
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: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
response.session.access_token doesn't work in my code. But this works:
response.authResponse.accessToken
FB.login(function(response) { alert(response.authResponse.accessToken);
}, {perms:'read_stream,publish_stream,offline_access'});
If you are already connected, simply type this in the javascript console:
FB.getAuthResponse()['accessToken']
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
FB.login(function(response) {
if (response.authResponse) {
// The person logged into your app
} else {
// The person cancelled the login dialog
}
});
response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.Check this for details:
SDKs & Tools › JavaScript SDK › FB.login
window.fbAsyncInit = function () {
FB.init({
appId: 'Your-appId',
cookie: false, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.0' // use version 2.0
});
};
// 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'));
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) {
var email = response.email;
var name = response.name;
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
<!-- custom image -->
<img src="/Public/assets/images/facebook/facebook_connect_button.png" />
<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
</fb:login-button>
window.fbAsyncInit = function () {
FB.init({
appId: 'Your-appId',
cookie: false, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.0' // use version 2.0
});
};
// 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'));
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) {
var email = response.email;
var name = response.name;
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
<!-- custom image -->
<img src="/Public/assets/images/facebook/facebook_connect_button.png" />
<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
</fb:login-button>