Can anyone help me with this code and tell me what is wrong?
My code is not working anymore with the new Facebook API and I am getting the below errors!
Uncaught Error: OAuth2 specification states that 'perms' should now be called
'scope'. Please update.
Error is in http://connect.facebook.net/en_US/all.js line 23
And even if I changed it, it still does not work at all!
//THIS FUNCTION WILL INITIALIZE THE FACEBOOK API AND WILL ADD NEW FACEBOOK ACCOUNTS.
var apikey = $("#apikey").val();
//var tuittingID = $("#tuittingID").val();
FB.init({ apiKey: apikey, status : true, cookie : true, oauth: true });
FB.getLoginStatus(handleSessionResponse);
$('#FBlogin').live('click', function() {
FB.login(handleSessionResponse, {
scope:'manage_pages, publish_stream, offline_access, user_status,
read_insights'
});
return false;
});
function handleSessionResponse(response) {
if (!response.session || String(response.scope) == '') {
return;
}
else
var tuittingID = $.cookie("tuittingID");
$('#AccessToken').val(response.session.access_token);
$("#loader").show();
$.post("tuitting/facebook_lib/fbadd.php",
{ tuittingID: tuittingID, uid: FB.getSession().uid, usid:
FB.getSession().session_key, accesstoken: response.session.access_token },
function(data){
reloadAccounts();
$("#loader").hide();
FB.logout(function(response) {
}); //END LOGOUT FROM FACEBOOK AFTER SUCCESSFULL ACTION
}
); //END AJAX POST FUNCTION DATA
}
Did you make the changes needed to support Oauth 2? it's been mandatory since Oct 1st but the SDKs were only forced onto Oauth 2 yesterday (December 13 2012)
See https://developers.facebook.com/docs/oauth2-https-migration/ - there's a summary of what changed and links to the announcing blog posts - the authentication and javascript docs are the docs you're most likely to need to check if you're making changes as this is where the changes were
We were also affected by this change and we made the following changes to make it work.
FB.init() was required as coded below with oauth set as true.
FB.init({
appId: 1234567890123,
oauth: true
})
And now there is no more session, response.session becomes response.authResponse and response.session.uid becomes response.authResponse.userID
FB.login(function(response) {
if (response.authResponse) {
var postData = {
FBID: response.authResponse.userID,
Access_Token: response.authResponse.accessToken
};
Link with additional information on js changes required
https://developers.facebook.com/blog/post/525/
Also make sure you're using FB.getAuthResponse() instead of FB.getSession().
http://developers.facebook.com/docs/reference/javascript/FB.getAuthResponse/
http://developers.facebook.com/blog/post/525/
This is the Oauth 1.0 code:
html
<div id="fb-root"></div>
<div class="fb-login-button" scope="email,user_birthday"
onlogin="afterFacebookConnect();" autologoutlink="false">Login con Facebook</div>
javascript
window.fbAsyncInit = function () {
FB.init({
appId: 'id_of_app',
status: true,
cookie: true,
xfbml: true });
};
if (document.getElementById('fb-root') != undefined) {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/es_ES/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}
function afterFacebookConnect() {
FB.getLoginStatus(function (response) {
if (response.session) {
window.location = "/facebook/login?token=" + response.session.accessToken;
} else {
// user clicked Cancel
}
});
}
Changes I made to adapt to Oauth 2.0:
window.fbAsyncInit = function () {
FB.init({
appId: 'id_of_app',
status: true,
cookie: true,
xfbml: true,
oauth:true // additional parameter
});
};
function afterFacebookConnect() {
FB.getLoginStatus(function (response) {
if (response.authResponse) {
window.location = "/facebook/login?token="
+ response.authResponse.accessToken;
} else {
// user clicked Cancel
}
});
}
Additional: Here is the code that handles the response (ASP.NET MVC, C#):
using Newtonsoft.Json.Linq;
[RequireHttps]
public ActionResult login(string token)
{
WebClient client = new WebClient();
string JsonResult = client.DownloadString(string.Concat(
"https://graph.facebook.com/me?access_token=", token));
JObject jsonUserInfo = JObject.Parse(JsonResult);
string nombre = jsonUserInfo.Value<string>("first_name");
string segundo_apellido = jsonUserInfo.Value<string>("last_name");
string nombre_completo = jsonUserInfo.Value<string>("name");
string genero = jsonUserInfo.Value<string>("gender");
string email = jsonUserInfo.Value<string>("email");
string birthday = jsonUserInfo.Value<string>("birthday");
// here you do your logic to login the user
// otherwise you can send user to the registration
// form and fill in some data you received from facebook
}
Related
This question already has answers here:
Facebook JS SDK's FB.api('/me') method doesn't return the fields I expect in Graph API v2.4+
(4 answers)
Closed 7 years ago.
I am using this simple FB connect
Connect
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
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
console.log(response);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
(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);
}());
When I connect, it only returns me
Object {name: "my name here", id: "102xxxxxxxx230"}
How can I retrieve email address ?
FB.api('/me', {fields: 'name,email'}, function(response) {
user_email = response.email; //get user email
console.log(response);
});
It´s called "Declarative Fields", see changelog: https://developers.facebook.com/docs/apps/changelog#v2_4
I want to integrate the facebook login button into my website. A user can log in using his/her facebook account only. I'm not interested in any other information about the user.
But I'm a little confused... I read the official facebook documentation, and I did not understand what i need. I'm undecided if I need to use the Graph API or the Login-Button of the Social Plugin
Can you please help me solve my doubts?
Many thanks!
To use this in flash, you have to use the javascript sdk through some ExternalInterface calls. This is how I always do it.
AS3
public function FBconnect():void {
ExternalInterface.addCallback("onLogin", onLogin);
ExternalInterface.addCallback("onError", onError);
ExternalInterface.call("requestLogin");
}
private function onError():void {
dispatchEvent(new DataEvent(DataEvent.ERROR));
}
public function logout():void {
ExternalInterface.call("FB.logout", null);
}
private function onLogin():void {
debugTools.trace("FB LOGIN");
connectUser();
}
private function connectUser():void {
ExternalInterface.addCallback("loadUser", userCallback);
ExternalInterface.call("connectUser");
}
private function userCallback(data:Array):void {
debugTools.trace("FB USER LOADED");
var userData:Object = data[0];
_FBuser = new FBUser(userData.id);
_FBuser.firstName = userData.first_name;
_FBuser.lastName = userData.last_name;
_FBuser.email = userData.email;
dispatchEvent(new DataEvent(DataEvent.SUCCESS));
}
JS
window.fbAsyncInit = function() {
FB.init({
appId: YOUR_APP_ID,
status: false,
cookie: true,
xfbml: false
});
};
(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);
}());
function connectUser() {
FB.api('/me', function(response) {
if(response) {
var usrs = new Array();
usrs.push(response);
document.getElementById('flashObj').loadUser(usrs);
} else {
document.getElementById('flashObj').onError();
}
});
};
function requestLogin() {
FB.login(function(response) {
if (response.authResponse) {
document.getElementById('flashObj').onLogin();
} else {
document.getElementById('flashObj').onError();
}
}, {scope:'email'});
}
So to break it down.
We load in the javascript sdk in our webpage, check the docs on facebook on how to do itn if you don't know.
Next, through the ExternalInterface, we call FB.login in the JS and on response we call an AS3 function through document.getElementById (to access your swf).
Then we do the same thing to use the Graph API to get the info on our user.
In my experience, this is the best workflow to facebook connect your user to your flash Application.
I am using JavaScript API to create my app for Facebook. The problem is, it's returning
email = undefined.
I don't know why? And if I use Facebook login/logout button on my app then the alert shows correct email id of the user but I don't want to do that.
What am I missing?
Here is my code:
<p><fb:login-button autologoutlink="true" perms="user_about_me,email"></fb:login-button></p>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '250180631699888', 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>
// https://developers.facebook.com/docs/javascript/reference/FB.api/
// v2.4
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
console.log(response.email);
}
);
here is example how i retrieve user name and e-mail:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
$(function() {
FB.init({
appId : 'APP_ID',
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') {
getCurrentUserInfo(response)
} else {
FB.login(function(response) {
if (response.authResponse){
getCurrentUserInfo(response)
} else {
console.log('Auth cancelled.')
}
}, { scope: 'email' });
}
});
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
});
</script>
According to the latest info on the facebook page you should use 'scope' instead of perms.
https://developers.facebook.com/docs/reference/javascript/FB.login/
If you visit
https://developers.facebook.com/tools/console/
and use the fb-api -> user-info example as a starting point, then logout and back in again, it should ask you for email perms and you can see your email being printed. It is done using response.email as you mention in your post.
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
</script>
Use this to for extra permission
for more details visit :
https://www.fbrell.com/examples/
In this code i have get user data form facebook and store into my database using ajax
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me?fields=email,name,first_name,last_name', function(response)
{
FB.api(
"/"+response.id+"/picture?height=100",
function (responses) {
//console.log(responses.data.url)
response['profile_pic']=responses.data.url;
$.ajax({
type:"POST",
url:'<?php echo base_url(); ?>'+'home/facebook_get_signup',
data:response,
success:function(res)
{
if(res=='success')
{
window.location='<?php echo base_url(); ?>';
}
if(res=='exists')
{
window.location='<?php echo base_url(); ?>';
}
}
});
}
)
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
// handle the response
}, {scope: 'email,user_likes'});
There are a couple of things wrong with your solution. First of all you are using the old authentication scheme. You should use the new one described here :
https://developers.facebook.com/docs/reference/javascript/
You need to add the oauth:true to your init function, and make sure that your getLoginStatus looks for the new type of response.
When that is said you need to make sure you have the right permissions to see the users e-mail. You can see the required permissions here:
http://developers.facebook.com/docs/reference/api/user/
You get those by using the FB.login function as described by TommyBs in another answer.
Once you have those options you can use the FB.api function to get the e-mail.
I'm trying to see if a user is logged into FB on my website. I have the following code below but regardless if I'm logged into my FB account or not the FB.getLoginStatus response is always returning null.
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: 'XXXXXXXXXXXXXXX', status: true, cookie: true,
xfbml: true});
FB.getLoginStatus(function(response) {
if (response.session) {
alert('Logged In');
} else {
alert('Not 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>
So it turns out this was a misinterpretation of the FB docs. The session will only return if the user is connected to the app. To see if the user is logged in but not connected you need to use response.status
maybe response.session is deprecated, official working example from Facebook:
To determine if a user is connected to your app:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
My FB.ui stream.share and stream.publish work perfectly but when I call the Callback funcion, it always returns as error, even though the story is published on my Facebook profile.
[script] <div id="fb-root<?php the_ID();?>"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '151136734905815', status: true, cookie: true, xfbml: true});
};
(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<?php the_ID();?>').appendChild(e);
}());
function fb_share (url, title){
var share = {
method: 'stream.share',
display: 'dialog',
u: url,
t: title
};
FB.ui(share, function(response) {
if (response && response.post_id) {
alert(response.post_id);
} else {
alert('Error: Post was not published due to some error. Please try again later.');
}
});
}
</script>[/script]
It always returns Error: Post was not published due to some error. Please try again later. even though the story is in facebook successfully. Any help on this?
$('#share').bind('click', function(e){
var share = {
method: 'stream.share',
u: 'http://your/share/url/with/id/123'
};
FB.ui(share, function(){
$.post("/log_shares.php", {"id": 123});
});
e.preventDefault();
});