Im sucessfully run FB.Event.subscribe and can output the uid and accesstoken from within that function - however im wondering how i'd go about accessing uid and accesstoken from basically anywhere?
My initial thought was that I needed to declare a global uid and accesstoken var outside of the function - however i've had no luck with that so far - when trying to output the global var I just get undefined
My code just after the starting <body> tag:
<body>
<div id="fb-root"></div>
<script>
//Declaring global var for uid and token
var uid;
var accessToken;
$(document).ready(function(){
function facebookReady(){
FB.init({
appId : '357646666347166', // App ID
channelUrl : '//localhost/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
});
$(document).trigger("facebook:ready");
}
if(window.FB) {
facebookReady();
} else {
window.fbAsyncInit = facebookReady;
}
});
// 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>
My code placed just before the closing </body> tag' - this is also where I try to access the global uid and token:
<script>
$(document).on("facebook:ready", null, function(){
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// Setting the uid + token
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
//
}
});
// Trying to access the UID OR TOKEN HERE:
console.log(uid);
console.log(accessToken);
// Trying to access the UID OR TOKEN HERE:
});
</script>
<!-- some included js file where I also want to access the UID -->
<script src="js/animation.js"></script>
I use to just store my accessToken in a global variable and it worked w/o problems. The problem here is that both uid and accessToken only have scope within their respective script tags so the uid and accessToken declared within FB.Event.subscribe are their own values; separate from your "global variables" and who's scope is limited to FB.Event.subscribe.
That being said all you need is to use is FB.getAccessToken()
Example with using jQuery to retrieve data through an ajax request:
$.ajax({
url: "myQuery.php",
data: { accessToken: FB.getAccessToken() }
}).done(function(data) {
doStuff(data);
});
You can also retrieve the uid through FB.getUserID()
Related
I create a app that use login on Facebook, but I can not capture the user's email address, I know I need to use scope, but do not know how. How can I do this?
This is my code:
window.fbAsyncInit = function() {
FB.init({
appId : '<?= $this->getAppId(); ?>', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.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
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
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));
// 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.email);
});
}
You pass in any additional permissions you want as an argument (comma-separated for multiple permissions) to FB.login(). IN your case, you want email:
FB.login(function(response) {
// handle the response
}, {scope: 'email'});
The FB JS SDK Documentation very clearly explains this. Please take the time to read it.
I resolved the problem, when use FB.Event.subscribe, we need put the permissions in html and not in FB.login() function, using this way:
fb:login-button show-faces="true" perms="email,user_birthday" width="200" max-rows="1
Thanks
My problem is to display a login button and(once the user is logged in) show his profile image, name and a "logout" link.
In the facebook api documentation (here http://developers.facebook.com/docs/guides/web/#login) i found this example:
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.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
});
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
}
});
};
// 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 align="center">
<img id="image"/>
<div id="name"></div>
</div>
</body>
</html>
That should do what i was looking for. I replaced 'MY_APP_ID' and MY_DOMAIN.COM with my app_id and my domain site (http://localhost/index.html). I also added a login button as i found on the documentation (that works and allow me to log in) but then no image nor name is shown. I wrote the "user" object in a console and it conatins this:
error: Object
code: 2500
message: "An active access token must be used to query information about the current user."
type: "OAuthException"
How should I use this "active access token"?
In order to accomplish any user data retrieval, every Facebook application must first authenticate the user session to ensure that the app has the permission of the end user to retrieve their data.
Reference: https://developers.facebook.com/docs/authentication
Retrieve their access token with the Javascript SDK and you should be able to begin retrieving their user display name and image as a result.
Facebook JS SDK: https://github.com/facebook/facebook-js-sdk/
I'm using this code, but it returns empty data array. My access_token has all permissions. I know PAGE_ID, now i need to get events from this page.Thanks
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : APP_ID, // 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
};
// 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));
var interval = setInterval(function() {
if (typeof FB != 'undefined') {
clearInterval(interval);
FB.api('/' + PAGE_ID +'/events?access_token=' + ACCESS_TOKEN, function(response) {
//do something with response
});
}
}, 20);
</script>
It's not clear from your code how you are obtaining the access_token - are you using the access token for the page\account for which you need to retrieve the events? The way I have been doing it (not sure where I picked up this technique) for page events is to loop through the user accounts to get the access token for the page in question. Something like this (php)
$accounts = $facebook->api('/me/accounts');
foreach($accounts['data'] as $account){
if($account['id'] == $page_id){
$page_access_token = $account['access_token'];
}
}
My first access_token for my APP which i get from http://developers.facebook.com/tools/explorer/ was wrong. (Maybe it's only for test mode) Because i couldn't get events by this access_token.
On http://developers.facebook.com/docs/authentication/applications/ was written:
App Access Tokens generally do not expire. Once generated, they are valid indefinitely.
To obtain an App Access Token, perform an HTTP GET on:
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
I got access_token using HTTP GET, by this access_token i get events from facebook page: https://graph.facebook.com/PAGE_ID/events
I was using Facebook login without a problem.. But mysteriously the next error started to appear in the firebug console, and now I am unable to login.
(new Date).addMonths is not a function
FB.provide('',{getLoginStatus:function...signed_request,code'});return a;}}});
I'm using the Javascript SDK.
<div id='fb-root'></div>
<script>
//<![CDATA[
window.fbAsyncInit = function() {
FB.init({
appId : '205160466168923', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
//channelUrl : '//www.clasesd.com/channel.html', // Channel File
// Additional initialization code here
};
// Load the SDK Asynchronously
(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#**oauth=1**&appId=205160466168923&xfbml=1";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
//]]>
</script>
And this is what I use to trigger the login
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
window.location = redirect_url;
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email, offline_access, publish_stream, user_events'});
});
Known issue, see http://developers.facebook.com/bugs/149848578458727
As stated in the comments on that issues, this is a work around:
Place the following code before you call FB.init()
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth()+n);
return this;
}
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_APP_ID',
status : true,
cookie : true,
xfbml : true
});
FB.Event.subscribe('auth.login', function(response) {
$.ajax({
url: "http://example.com/fbconnect",
success: function(){
window.location.reload();
}
});
});
};
(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));
</script>
<div class="fb-login-button" data-perms="email,user_birthday,user_hometown,user_location">Login with Facebook</div>
It's working with only two cases.
1- when a user is NOT logged in and log in to facebook it triggers.
2- when a user is logged in but didn't authorize the app yet it triggers.
the third scenario which is not working is when a user is logged in and He is already authorized the app the FB.Event.subscribe('auth.login) won't trigger !!!
I encountered the same thing as you and I found a function, "getLoginStatus", that might be of interest for you.
When the user is already logged in and has granted your app all the permissions, then there is no need to log in again and therefore the event won't be triggered.
However, if the response of the "getLoginStatus" is "connected" you can do the stuff you want to do when the user is already logged in and has granted your app all the permissions.
The complete script might look something like this:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APPID', // App ID
channelUrl : 'CHANNEL_URL', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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(response) {
if (response.name != undefined ) {
console.log("Welcome, " + response.name);
}
});
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(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));
</script>
Got the exact same issue here and it's driving me nuts. Not liking the Facebook Javascript SDK atm.
It's really complex with the status check in FB.init() and makes it even harder when you put facebook comments on the page...
A workaround I just tested is to have your own login button and use the FB.login() method, there you can hook in to the callback (this replaces your code for the auth.login event).
window.fbAsyncInit = function () {
FB.init({
...
});
$('#fb-login-button-custom').show().click(function () {
var scopeList = $(this).data('scope');
FB.login(function (response) {
alert('FB.login callback');
console.log(response);
document.location.href = document.location.pathname + '?fblogin=1';
}, { scope: scopeList });
});
});
That default login event is actually only triggered when the user authorizes your application. So when loging out the user, you could revoke the authorization. But then every time they log in they have to 'allow' the app.
Using FB.Event.subscribe('auth.statusChange', handleStatusChange); will notify you status changes..
hope it helps