FB.api does not work when called right after FB.init - javascript

FB.api does not work when called right after FB.init. Here is the code snippet I use:
window.fbAsyncInit = function() {
FB.init({
appId : window.APP_ID,
status : true,
cookie : true,
oauth : true,
channelUrl : window.MASTER_URL + "channel",
frictionlessRequests : true
});
window.COMPANY.init();
};
(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);
}());
And here is my COMPANY.init() and COMPANY.fetchAllFriends():
friends: new Array(),
init : function() {
// TODO
COMPANY.fetchAllFriends();
FB.Canvas.setSize($(document).height());
FB.Canvas.setAutoGrow();
},
fetchAllFriends : function() {
FB.api('/me/friends', function(response) {
if (!response || response.error) {
return;
}
COMPANY.friends = new Array();
$.each(response.data, function(index, value) {
COMPANY.friends.push(value.id);
});
});
},
where at fetchAllFriends response contains error which says "An active access token must be used to query information about the current user.". I made sure (via the browsers debugger) that FB.init is called before that call of FB.api.
Any help will be appreciated!

Ok, I fixed my problem. I changed:
window.fbAsyncInit = function() {
FB.init({
appId : window.APP_ID,
status : true,
cookie : true,
oauth : true,
channelUrl : window.MASTER_URL + "channel",
frictionlessRequests : true
});
window.COMPANY.init();
};
to:
window.fbAsyncInit = function() {
FB.init({
appId : window.APP_ID,
status : true,
cookie : true,
oauth : true,
channelUrl : window.MASTER_URL + "channel",
frictionlessRequests : true
});
FB.Event.subscribe('auth.login', window.COMPANY.init);
};
in case anyone else want to know. What I found is that the FB JS SDK has not formed the user session by the time when FB.init returns, so what you need to do is to subscribe to the 'auth.login' event with your init function. More info here

You don't appear to be checking the status of the user. All you are doing is initializing Facebook, you don't even know if the user is logged into Facebook or has a Facebook account. You need to call FB.getLoginStatus and check if they are "connected". If they aren't connected, there is no possible way to get an access token. If they are connected, then you get an access token.

Related

how to customize the Facebook Login Button with ReactJs

I am trying to customize the Facebook button for my ReactJs website, but it seems to be not working. I want my Facebook button look like the following design:
Google login is working as I expected, but facebook is kept appearing like following:
Any help would be appreciated!
codesandbox link
I found the answer to my own question, I just stupidly did not see the correct way of importing the FacebookLogin
import FacebookLogin from 'react-facebook-login/dist/facebook-login-render-props'
This is how the import should be done. After that I was able to make my own custom style through render prop:
appId="1088597931155576"
autoLoad
callback={responseFacebook}
render={renderProps => (
<button onClick={renderProps.onClick}>This is my custom FB button</button>
)}
/>```
You can achieve this thing very easily. What you have to do is you have to design your custom button and then use the onclick property.
Here how you do it:
Include this thing where you want to show the Facebook login button and don't forget to style this button according to your needs.
<div id="fb-root"></div>
<button onclick="fb_login();">Login using facebook</button>
Now here is the code you have to include in your page that has the fb_login function defined. You have to put your app id to see the results.
window.fbAsyncInit = function () {
FB.init({
appId: 'your_app_id_here',
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
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'public_profile,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);
}()

Facebook connect: can retrieve the id, the username but cannot retrieve the email

I can get the id and username from facebook connect, but I cannot retrieve the email !
Here is the JS script:
function connectionFacebook()
{ console.log('connectionFacebook called');
FB.api('/me?fields=email,name', { fields: 'name, email' }, function(response)
{
console.log(response);
response gives me:
Object {name: "John Doe ", id: "11112222333344445555"}
But no email !
PS. I guess it uses some old FB connect js since I work on an quite old site.
I have no idea what version of FB it uses, but I guess an old one !
ex: of code found in site;
FB.Event.subscribe('auth.login', function(response)
{
connectionFacebook();
;
});
FB.getLoginStatus(function(response)
{
if (response.authResponse)
{
connectionFacebook();
}
else
{
// no user session available, someone you dont know
//alert("getLoginStatus:deconnecté");
}
});
$.fn.connexionFacebook = function( ) {
return this.each(function () {
FB.init({
appId : xxxxxxxxx,
status : true,
cookie : true,
xfbml : true
});
});
}
})( jQuery );
<script src="http://connect.facebook.net/fr_FR/all.js"></script>
<fb:login-button show-faces="false" width="450" perms="email,user_birthday,user_location" size="medium">FaceBook connect</fb:login-button>
I'd guess that you don't have a permission to access the user's email. Facebook requires you to set the scope that determines which information you need to access.
In you case you need to specify the scope as public_profile,email to access the email. you can do that when your user logs in. Either with the API call:
FB.login(callback, { 'scope': 'public_profile,email' });
or with the button:
<fb:login-button scope="public_profile,email"></fb:login-button>
Specifying the email in the scope will ask the user to share her email address with your application when she logs in:

facebook login with javascript - server related issues?

I'm experiencing issues with login into FB account with javascript from our website.
The login is simple, we defined the scope: email, user_birthdate, ... what we need.
On one server I can all the info we need, on another only basic information, ie: birthdate is missing and hometown as well.
Is there any way to prevent this? It might be I missed something out.
Thanks for your suggestions.
   window.fbAsyncInit = function() {
   FB.init({
   appId : fb_app_id, // App ID
   apiKey : fb_app_secret,
channelURL : '', // Channel File, not required so leave empty
   status : false, // 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
frictionlessRequests : true
   });
    function login(){
FB.getLoginStatus(function(response){
if(response.status === 'connected'
|| response.authResponse != null){
FB_response(response);
}
else{
FB.login(function(response) {
if(response.authResponse) {
//alert('connected' );
FB_response(response);
}
else {
// user is not logged in
}
},{scope:'email, user_about_me, user_birthday, user_hometown, user_location'});
}
});
}
I guess you try it with different users... All admin/tester/developer users of an app can give their permissions without the app being reviewed yet. All other users can't, and therefore you only see the basic info.
See
https://developers.facebook.com/docs/apps/review/login#do-you-need-review

Facebook Javascript SDK Cookie

i wrote for my Node.js Applikation a model (backbone), that realizes the authentication with Facebook Javascript SDK.
My modelcode is here:
define(['jquery','underscore','backbone'], function($,_,Backbone) {
var facebookUserModel = Backbone.Model.extend({
initialize: function() {
console.log('FacebbokUserModel initialized');
// bind statusChange to this context
_.bindAll(this, 'statusChange');
// be notified when the session changes
FB.Event.subscribe('auth.authResponseChange', this.statusChange);
}
//saves actual status
,_loginStatus : null
//return true/false if user is logged in
,isLoggedIn : function() {
return this._loginStatus === 'connected';
}
//check whether user is logged in or not
//used for firsttime invoke
,getLoginStatus : function() {
_this = this;
FB.getLoginStatus(function(response) {
_this.statusChange(response);
});
}
//log user in
,login: function() {
FB.login(function() {});
}
//log user out
,logout: function() {
FB.logout();
}
//treat changes on status
,statusChange: function(response) {
console.log('statuschange');
if(this._loginStatus === response.status) return false;
var event;
if(response.status === 'not_authorized') {
event = 'fb:unauthorized';
}else if(response.status === 'connected') {
event = 'fb:connected';
}else {
event = 'fb:disconnected';
}
console.log(event);
// RESPONSE IS SHOWN CORRECTLY EVEN IN FIREFOX
console.log(response);
this._loginStatus = response.status;
this.trigger(event, this, response);
}
,sync: function(method, model, options) {
if(method !== 'read') throw new Error('FacebookUser is a readonly model, cannot perform ' + method);
var callback = function(response) {
if(response.error) {
options.error(response);
} else {
options.success(model, response, options);
}
return true;
};
FB.api('/me', callback);
},
});
return facebookUserModel;
});
Initfunction
FB.init({
appId : 'myappId', // App ID
channelUrl : 'channelurl', // 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
});
When i execute this code it is working fine in Chrome and in IE. On serverside i can validate this cookie really easy but i have a problem with Firefox. Firefox shows the response correctly(clientside) but it does not create an fbsr-cookie. Can somebody give me a hint why? How can i handle this problem?
greets

Reveal hidden download box div after visitor shares a link on facebook

I am searching for some days a possibility to reveal a hidden div after a visitor shares a link but i couldn't find anything. I've tried here something http://jsfiddle.net/trefu/qNDJB/9/ but is not working. Can someone give me a little help please.
Download Box (whatever that means) goes here
window.fbAsyncInit = function() {
FB.init({
appId : '437410746335629', // 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
});
// 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));
FB.init({appId: "437410746335629", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
name: 'Facebook Dialogs',
caption: 'Reference Documentation',
description: 'Using Dialogs to interact with users.'
};
function callback(response) {
if (response && response.post_id) {
document.getElementById('download_box').style.display = 'block';
} else {
alert('You must share your post before you can download.');
}
}
FB.ui(obj, callback);
}
The code you have specified should work in what you are trying to achieve. The problem is with your application settings. Make sure your domain is set in the Facebook App Settings page, specifically update the 'App Domains' and 'Site URL' fields. You will find that the feed dialog error you're getting will then be resolved.

Categories

Resources