I need help on facebook login wth app. I have a website http://отдых-сицилия.рф. I did configured this in facebook app, and I am trying to login from my application.
I have the code below:
window.fbAsyncInit = function() {
FB.init({
appId : 'code', // App ID
channelUrl : '//отдых-сицилия.рф/channel.php', // 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.
// FB.login({scope:'email,hometown'});
FB.api('/me', function(response) {
document.getElementById('nome').value = response.name;
if(response.email){
document.getElementById('email').value = response.email;
}
document.getElementById('fbusername').value = response.username;
document.getElementById('fbname').value = response.first_name;
document.getElementById('fbsurname').value = response.last_name;
document.getElementById('nazionalita').value = response.locale;
if(response.hometown){
document.getElementById('citta').value = response.hometown.name;
}
});
} 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({scope:'email,hometown'});
} 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({scope:'email,hometown'});
}
});
};
// 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/it_IT/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
this code works very good on other 2 websites.
What I noticed is that when I open the login popup, the url is:
redirect_uri=http%3A%2F%2Fwww.facebook.com%2Fdialog%2Freturn%2Farbiter%3Frelation%3Dopener%26close%3Dtrue%23origin%3Dhttp%253A%252F%252F%25D0%25BE%25D1%2582%25D0%25B4%25D1%258B%25D1%2585-%25D1%2581%25D0%25B8%25D1%2586%25D0%25B8%25D0%25BB%25D0%25B8%25D1%258F.%25D1%2580%25D1%2584%252Ff32358e929d241c&app_id={APP_ID}&display=popup
so, the website url is not correct. How can I pass this url correctly?Or what cand I do?
Thank you!
Related
The first time my users accesses the app, everything works fine. The user gets a popup with the question to authorize my app. But then, the next session(ex. refresh), he gets an empty popup that closes itself in an instant.
I believe it's Facebook asking for a new access token, but the problem is that I don't find it user friendly. When a popup opens and closes itself that fast, the user thinks there's something wrong or that he missed something.
Here's the code:
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelUrl : '', // 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.
if(accessToken)
{
//console.log("Connected WITH accesToken");
testAPI();
}
else{
// console.log("Connected WITHOUTaccesToken");
FB.login(function(response) {
// handle the response
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
//console.log(uid);
//console.log(accessToken);
}, {scope: 'friends_location, user_location, user_relationships'});
}
} 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.
//alert("You're logged in on FB but not on the APP");
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();
//alert("You're offline on FB");
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() {
FB.api('/'+uid+'/friends?fields=name,location,picture&accesstoken='+accessToken, function(response) {
}
//<img border="0" src="console.log(response.data[0].picture.data.url)">
}
});
}
//Logout
function fbLogout() {
//FB.init();
FB.logout(function (response) {
//Do what ever you want here when logged out like reloading the page
//window.location.reload();
});
}
How can I prevent this empty popup?
You are explicitly calling FB.login, vs FB.getLoginStatus, which is a wrapper around the login dialog. This is why you always get the popup.
Instead, first call getLoginStatus, and only if this fails, you present a button which triggers login.
In my code I have
FB.api('/me/friends', function(response) {
if(response.data) {
//TODO : what to do if no. of friends is more than 5000 (pagination by fb)
friends_data=response.data;
dijit.registry.byId("mainWidget_div").set_friends_data(friends_data);
} else {
alert("Error!");
}
});
And this gives an error. But, if I call this function manually(on the console), there's no error
FB.api('/me/friends', function(response){r=response;});
//wait a while
r
and now r.data is an array of my friends.
I checked the network panel and I gather that when I call this manually, an access token automatically gets inserted in the request url and when it is getting called via the code, the access token doesn't get inserted.
The full fb sdk loading code in my application is this:
<script type="text/javascript">
// You probably don't want to use globals, but this is just example code
var fbAppId = "{{facebook_app_id}}";
// This is boilerplate code that is used to initialize the Facebook
// JS SDK. You would normally set your App ID in this code.
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : fbAppId, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse page for xfbml or html5 social plugins like login button below
});
// Put additional init code here
dojo.ready(function(){
FB.api('/me/friends', function(response) {
if(response.data) {
//TODO : what to do if no. of friends is more than 5000 (pagination by fb)
friends_data=response.data;
dijit.registry.byId("mainWidget_div").set_friends_data(friends_data);
} else {
alert("Error!");
}
});
});
};
// 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/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
The answer from Brent Baisley and another answer to a different question, helped me figure out what was wrong.
You can't call FB.init() dependent methods right after FB.init() because it loads asynchronously. Even loading the data asynchronously like in dojo.ready() doesn't help. You have to wrap the code in FB.getLoginStatus().
My guess would be that you are trying to get the list of friends before the Facebook API is fully initialized. What is the error you are seeing?
You are registering the FB.api call to be run on DOM ready (dojo.ready). That might be causing it to load out of sync, even though it's all wrapped in fbAsyncInit. The friends API call itself has no dependency on the DOM, so I wouldn't wrap it in a dojo call. You're not doing that in the console and it's working.
I'm no javascript expert. If I made a possibly incorrect guess, the reason this happens could have to do with javascript hoisting.
I am using the js sdk and getting the basic information such as name, location, id. Great but I need just one more thing and that is email. So I read here that email requires extended permissions. I also read here using fb.login how to ask for extended perms.
In my code from this tutorial here I don't call fb.login yet the visitor gets prompted to login and grant app permissions if they aren't. How is that done? The register button (modified slightly from tutorial) is a div with a class that styles it.
<div class="fb-login-button" data-show-faces="false" data-width="400" data-max-rows="1">Register</div>
Well I inspected the "register" button and found it rendered quite transformed but I never found an onclick or some clue as to how a user clicking on the button event is handled. My GUESS is that the iframe that comes from the styling has a src and the event must be on fb side.
So going back to my script I thought perhaps fb.login was with fb.init and I could add my perm request there but there is no fb.login?? I thought maybe to put it in the else branch below but nothing is there now and it works...minus extended perms for email?
window.fbAsyncInit = function ()
{
FB.init({...removed for concise....});
//If user authorizes using fb account info:
FB.Event.subscribe('auth.authResponseChange', function (response)
{
if (response.status === 'connected')
{
...removed for concise code...
}
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.
//**HERE IS WHERE I WOULD HAVE THOUGHT TO PUT FB.Login**
}
});
};
So what is eluding me is how the pieces fit together in the puzzle. I KNOW I need to ask for extended permissions to get the json to include email but not sure where to make the perm. request at???
This code here is the actual code in the page so you can see my entire sdk implementation.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function ()
{
FB.init({
appId: 12324, // App ID
status: true, // check login status
cookie: true, // enable cookies
xfbml: true // parse XFBML
});
//If user authorizes using fb account info:
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;
// send access token to server so we can fill in fields
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/mypage');
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>
Since you are not using the SDK itself to login, but the login button, you have to request the permission via the scope parameter, set as data-scope="…" on the button itself, see https://developers.facebook.com/docs/reference/plugins/login/
The other alternative would be to remove the button, and call FB.login onclick on a button/link of your own making.
how do you logout the user from your site in facebook api, while still keeping the user logged into facebook with cakephp? (I found the answer so wanted to share with everyone).
I figured this one out just now, after reading CakePHP facebook integration logout issue with CakePHP-Facebook-Plugin.
Basically, although in the demos with webtechnick's examples, he puts the "Facebook.Connect" component in the AppController, if you want the selective logout piece, the Best place to put it is in reality within the actual controllers that you want to use it in. That or leave it in AppController and pass noAuth=> true into the Facebook.Connect component.
Either way, whichever way you choose, you set up one controller (facebook_controller.php?) to handle the facebook logins, and set its component with the noauth set to false (which is default, meaning DO authenticate [read connect.php to understand this]). That way, you have total control over when the users are logged into the site, and you can ACTUALLY log them out (with the regular redirect($this->Auth->logout()) without having the connect component immediately log them back in on redirect. Here is an implementation below:
Let me give you an idea:
app_controller.php
class AppController extends Controller {
var $components = array('Auth', 'Acl', 'Session');
//or if you want access to "$this->Connect" universally:
// array('Auth', 'Facebook.Connect' =>
// array('noauth'=>'true'), 'Acl', 'Session');
}
users_controller.php:
class UsersController extends AppController{
var $helpers = array('Facebook.Facebook');
//an example of the users controller, enabling connect, but
// not authorizing the user (because logout() used by Auth is here)
var $components = array('Email', 'Session', 'Facebook.Connect' => array('createUser'=>false, 'noauth'=>true));
//login() doesnt need to be shown and can be left alone for your traditional users
function logout(){
//if there is no fb user, do the logout normal
if ($this->Connect->FB->getUser() == 0){
$this->redirect($this->Auth->logout());
}else{
//ditch FB data for safety
$this->Connect->FB->destroysession();
//hope its all gone with this
session_destroy();
//logout and redirect to the screen that you usually do.
$this->redirect($this->Auth->logout());
}
}
}
your "facebook_controller.php":
class FacebookaController extends AppController {
...
// i dont personally like to have his piece create my user so:
var $components = array('Facebook.Connect' => array('createUser'=>false));
...
function login(){
//just need this stub function for later
$this->autoRender = false;
}
//you also need this for deauths or they will still be able to get into the site after deauth (against policy or whatever)
function deauthorize(){
//get user id from facebook API
$uid = $this->Connect->FB->getUser();
$record = $this->User->findByFacebookId($uid);
$this->User->delete($record['id'], FALSE);
}
}
now your users/login.ctp file:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id', // App ID
channelUrl : '//'+window.location.hostname+'/facebook/channel', // 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
FB.Event.subscribe('auth.statusChange', function(response){
if (response.status == "connected"){
alert('redirecting you to auto facebook login');
//here is out default place for login
window.location.href = "http://"+window.location.hostname + "/facebook/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));
</script>
<?php e($this->Facebook->login(array('registration-url'=>'http://www.yoursite.com/facebook/signup'))); ?>
And that should be pretty much it. I hope this helps someone reading this who still needs the help.
I am getting FB undefined , when i write following code , i have successfully added the necessary files for facebook using window.fbAsyncInit , the thing is if i write following code under "click" event then it works well but not at the time of pageshow in jquery mobile. this is happening might be because the facebook js files are loading bit late. but i want to check the user status on every page to restrict unnecessary or anonymous access.
$("#details").live( "pageshow", function() {
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;
console.log("INSIDE ME");
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
console.log("OUTSIDE ME");
} else {
// the user isn't even logged in to Facebook.
}
});
});
Put the jQuery live() assignment inside the window.fbAsyncInit as well. So that way it is only applied to the DOM element after FB has a chance to initialize.