In Facebook FB.ui (method: permissions.request) user is not redirect to proper location - facebook

Hi i m trying to show permission dialog using following code:
$permission = $facebook->api(array('method' =>'users.hasAppPermission','ext_perm'=>'publish_stream','uid'=> $uid));
if($permission != '1')
{
echo "<script type='text/javascript'>
var dialog = {
method: 'permissions.request',
perms: 'publish_stream',
redirect_uri: 'http://apps.facebook.com/abcd/'
};
FB.ui(dialog,null);
</script>";
}
This code works fine but problem is that when user allow to permissions he is not redirected to redirect_uri location(that is my canvas page) instead it goes to canvas url (that is my server's url). how to solve this problem Help me.

You can add the following javascript code in your page:
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
window.location.href = '/whatever/here';
} else {
// The user has logged out, and the cookie has been cleared
}
});

Related

Facebook login on cordova app shows blank white screen

This problem has been bugging me for a long time and I can't seem to find the solution, all the settings in my Facebook Developer panel are configured correctly, Site URL, App Domain and OAuth URLs.
When I run my app on my iPhone (I have it installed through iTunes) and click the authentication button I am successfully prompted with this screen:
However, after logging in, I am faced with a blank white screen instead of being redirected to my main.html page.
I am using the OpenFB plugin along with Parse and the Facebook Graph API to authenticate and store my users data, here is my login code:
login.html:
$('.facebookLogin').click(function(){
Parse.User.logOut(); // log current user out before logging in
login();
});
function login() {
openFB.login(function(response) {
if(response.status === 'connected') {
console.log('Facebook login succeeded');
Parse.FacebookUtils.logIn("email", { // permission request to use email
success: function(user) {
if (!user.existed()) {
FB.api('/me', function(response) {
var firstName = response.first_name;
var lastName = response.last_name;
var email = response.email;
var user_id = response.id;
user.set("firstName",firstName);
user.set("lastName",lastName);
user.set("email",email);
user.save();
});
window.location.href= "main.html";
}
else {
window.location.href= "main.html";
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
}
else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
}
oauthcallback.html:
<html>
<body>
<script>
// redirects to main page
window.location.href= "main.html";
</script>
</body>
</html>
Note: I have added main.html, login.html and oauthcallback.html to the Valid OAuth redirect URIs list on my panel.
Check that your site is using SSL with a valid certificate.
There might be an error trying to redirect from a non-secure site to an encrypted site.

FB.getLoginStatus() needs page refreshed

I am using FB.getLoginStatus() and FB.Login() to log the user into my website using facebook. I first check for the status on page load using FB.getLoginStatus() and save the state in a hidden variable. When the user clicks on my facebook login button, I first check the value in the hidden variable and call FB.Login() only if FB.getLoginStatus() is not connected. If FB.getLoginStatus() returns 'Connected', then I just log the user into my website without FB.Login().
My scenario with issue
*user logs into my accont using facebook
*user logs out of my website
*my website is open in the logged out state
*in another tab, the current facebook user logs out of facebook and a new user logs into facebook
*user comes back to my website and clicks on facebook login button without refreshing the page
*the old facebook user (not the one currently logged into facebook) is logged into my account
How can I identify the most current user in facebook when user clicks the facebook login button?
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root">
</div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with your Facebook API key
var AppID = '<%=AppID%>';
window.fbAsyncInit = function() {
FB.init({
appId: AppID,
status: true,
cookie: true,
xfbml: true,
channelUrl: 'http://<%=Request.ServerVariables("HTTP_HOST")%>/channel.html'
});
FB.Event.subscribe('auth.login', function(response) {
//alert('logged in');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('logged out');
});
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
var uid = response.authResponse.userID;
document.getElementById('hdnFBConnected').value = uid;
}
else if (response.status === "not_authorized") {
//alert("Not authorized");
document.getElementById('hdnFBConnected').value = '';
}
else {
//alert("user not logged in to facebook");
document.getElementById('hdnFBConnected').value = '';
}
});
};
</script>
<img src="<%=global_language & "/images/FacebookSmall.gif"%>" />
<script type="text/javascript" language="javascript">
function WindowOpen() {
if (document.getElementById('hdnFBConnected').value != '') //user is connected
{
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = document.getElementById('hdnFBConnected').value;
//log the user into my site
})
}
else { //user is not connected, so calling FB.Login()
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = response.authResponse.userID;
var globalLang = '<%=global_language%>';
//log the user into my site })
}
else {
//alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' }
);
}
}
</script>
</body>
What you're describing is normal behavior. The JS SDK is sending the old user's signed_request object which allows the new user to access her account. Since this concerns you, include a logout button on your app's page and let the user know that it's important she clicks that button when she's done using your app. The logout button should call FB.logout like so:
FB.logout(function(response) {
// user is now logged out
});
For extra security, you can create an activity timer that prompts the user to click a button after X minutes of inactivity. If the user doesn't click within, say 1 minute, she is logged out automatically. This is how most banking sites deal with session security.

Facebook login not responding to FB.login response

I am working on a android phonegap application with facebook integration.
FB.login(function(response) function has a response handler it is being called when
user click on fb button, but its not getting into the function response
or alert('test') every time. it gets into this script only when i hit
around 5 or 6 times. wat i need is to fetch the access token the very first time i logged into facebook. i have gone through a lot of links regarding this but
cant find an exact solution for this...
FB login callback function not responding if user is already logged in facebook
Even this question seems to be same but i cant figure it out my solution.
this is the code am working :
<div id="data">Hello Facebooktesters, loading ...</div>
<button onclick="login()">Login</button>
<button onclick="me()">Me</button>
<button onclick="logout()">Logout</button>
<button onclick="Post()">facebookWallPost</button>
<script type="text/javascript">
document.addEventListener('deviceready', function() {
try {
alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({
appId : "xxxxxxxxxxxxxxx",
nativeInterface : CDV.FB,
useCachedDialogs : false
});
document.getElementById('data').innerHTML = "FB init executed";
} catch (e) {
alert(e);
}
}, false);
function me() {
FB.api('/me/friends', {
fields : 'id, name, picture'
}, function(response) {
if (response.error) {
alert(JSON.stringify(response.error));
} else {
var data = document.getElementById('data');
fdata = response.data;
console.log("fdata: " + fdata);
response.data.forEach(function(item) {
var d = document.createElement('div');
d.innerHTML = "<img src="+item.picture+"/>" + item.name;
data.appendChild(d);
});
}
var friends = response.data;
console.log(friends.length);
for ( var k = 0; k < friends.length && k < 200; k++) {
var friend = friends[k];
var index = 1;
friendIDs[k] = friend.id;
//friendsInfo[k] = friend;
}
console.log("friendId's: " + friendIDs);
});
}
function login() {
FB.login(function(response) {
alert('test');
if (response.authResponse) {
alert('logged in');
var access_token = FB.getAuthResponse()['accessToken'];
alert(access_token);
window.location = "test.html"
} else {
alert('not logged in');
}
}, {
scope : "email"
});
}
function logout() {
alert('test');
FB.logout(function(response) {
alert('logged out');
//window.location.reload();
});
}
function Post(ele) {
var domain = 'http://192.168.0.46:8082/';
console.log('Debug 1');
var params = {
method: 'feed',
name: 'test - test',
link: domain+'test/test/showproddetails.action?product.productId=1',
picture: 'http://www.careersolutions.com/test.png',
caption: 'test',
description: 'test'
};
console.log(params);
FB.ui(params, function(obj) { console.log(obj);});
}
</script>
Thank you,
raj
You are missing semicolon in this line :
window.location = "test.html"
This question was posted a while ago but I would like to point out something. FB.login function opens a popup dialog asking if the user would like to log in to your app using Facebook. It is generally recommended that it be run after clicking a button as most browsers would block popup dialogs when a page loads. If the user had previously authorized your app then the popup dialog redirects back to your app and closes the dialog box (assuming your app is a website).
If what you intended to do was to check whether a user is logged in to your app upon page load, then it's recommended that you instead use FB.getLoginStatus method like so
function checkLoginState() {
FB.getLoginStatus(function(response) {
// Check response.status to see if user is logged in
alert(response.status);
});
}
Refer to this extensive documentation on facebook

Cakephp Facebook Plugin - Sharing through an action

I am using Nick Baker's (webtechnick) CakePHP / Facebook plugin which is awesome and works great, however I have a question that I can't seem to even come close to answer for.
How would I bypass the use of a share button and share directly through an action?
For instance, I make a post through my site and the post adds to the DB as it should, it also shoots a post to the logged in users Twitter account through the action. How can I also have this action handle sharing it to my FB account (connection has already been made).? I tried the first thing I think anyone would obviously try $this->Facebook->share() directly in the action, too no avail...
Any thoughts or solutions would be of great help...
UPDATE AFTER ANSWER
Thx for the help spooney. I voted your answer up because you are 100% spot on from what I can tell. I am loading the JS SDK.
function init($options = null, $reload = true) {
if (empty($options)) {
$options = array();
}
if ($appId = FacebookInfo::getConfig('appId')) {
$session = json_encode($this->Session->read('FB.Session'));
if ($reload) {
$callback = "FB.Event.subscribe('auth.login',function(){window.location.reload()});";
} else {
$callback = "if(typeof(facebookReady)=='function'){facebookReady()}";
}
$callback .= "FB.Event.subscribe('auth.logout',function() {window.location = '/bastards/users/logout'});";
$init = '<div id="fb-root"></div>';
$init .= $this->Html->scriptBlock(
<<<JS
window.fbAsyncInit = function() {
FB.init({
appId : '{$appId}',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // use Oauth
});
{$callback}
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/{$this->locale}/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
JS
, $options);
return $init;
} else {
return "<span class='error'>No Facebook configuration detected. Please add the facebook configuration file to your config folder.</span>";
}
}
I have no problem pulling in the user information and working with all that. I have accomplished posting to FB from my site, but it was only through a link, using FB.ui...
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'message name',
caption: 'message caption ',
description: 'description goes here',
link: 'the url current page',
picture: 'if you want to add an image'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>
I have tried replacing the code above with...
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
</script>
But it errors everytime.
I should also throw in there that the post on the users FB wall isn't really coming from the site persay, it's a post from the user on their own wall basically stating, "I made a post on ladala.com, you should go check it out at ."
So now I'm at the point that I need to figure out how to run FB.ui through the action that submits the post.
Based on our conversation, I figured I would just put a more complete description in an answer.
You can fire a share call using the JavaScript SDK.
First, you would need to load the JavaScript SDK as described in the Loading section of https://developers.facebook.com/docs/reference/javascript/.
Once loaded into your page, the two calls you want to look at are FB.getLoginStatus, and FB.api. FB.getLoginStatus will give you back a response telling you if the user is logged in to facebook, and if they have approved your application. This link will describe the functionality of getLoginStatus, but in short, you need to check for response.connected(and then possibly do another call to confirm a user's permissions, if required).
If the user is logged in and has approved your app, you can then attempt to make an API call using FB.api. Keep in mind to do this, you will likely need the user to have allowed the publish_stream permission.
Your code would look something like this:
//Do FB initialization
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
//Post was successful
}
});
}
});
This can be triggered any way you want. On page load, on click, on completion of some other event, etc.
Keep in mind this is just one way to implement this. Also, if you are trying to share something with your FB application, and it is not working, you should confirm that you have all the permissions required to do so.

Extracting user id from Facebook Javascript SDK session object

I am using Facebook's Javascript SDK "FB.ui" to pull up an OAuth dialog. Once you click allow, I need to capture the session object, extract the user id and use it further in my script. For some reason I cannot get this working properly, I keep getting undefined, even though the session does exist.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script type="text/javascript">
FB.init({
appId : '***************',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.session) {
//do something
} else {
FB.ui({
method: 'oauth',
display: 'page',
scope: 'email',
perms: 'email'
},
function(response) {
alert(response.session.uid); //returns underfined
});
}
});
</script>
To get the userID:
FB.getLoginStatus(function(response) {
alert(response.authResponse.userID);
});
When you login from login button of facebook then it stores cookies in your system that contains your access token that is also unique. That cookies contains your facebook id also.
Check your response. I bet it says something like "display" must be one of "popup", "iframe" or "hidden". Apparently the oauth dialog cannot be called with the default "page" display. And display: 'iframe' requires that you include an access_token, which is why you're calling the oauth dialog in the first place >:l .
I don't think FB.ui can currently be used to get the oauth dialog, unless you want to use a popup, which most everyone has blocked nowadays.
So I got this to work as I would like. This may not be the best way, but after much digging around and frustration I hope this could help somebody with the same question get on the right track.
JS source:
FB.getLoginStatus(function(response) {
if (!response.session) {
//initiate FB OAuth js popup dialog
FB.ui({
method: 'oauth',
display: 'page',
scope: 'email',
perms: 'email'
},
function(response) {
if (response.session) { //if permission Allowed
var thesession = response.session;
var thesession = eval('(' + thesession + ')'); //decode json
//POSTing to local file get.user_graph.php, to fetch user info
$.ajax({
type: "POST",
url: "get.user_graph.php",
data: "client_id=<?php echo $appId; ?>&client_secret=<?php echo $secret; ?>&sessions="+thesession.session_key+"&type=client_cred&uid="+thesession.uid,
dataType: "text",
success: function(user_graph){
var user_graph1 = eval('('+user_graph+')');
alert(user_graph1.name); //users name
alert(user_graph1.id); //users id
alert(user_graph1.email); //users email
alert(user_graph1.link); //users profile link
}
});
} else {
//if permission Not Allowed
}
});
}
});
get.user_graph.php source:
//exchange our session for an access_token
define('POSTURL', 'https://graph.facebook.com/oauth/exchange_sessions');
define('POSTVARS', 'client_id='.$_POST['client_id'].'&client_secret='.$_POST['client_secret'].'&sessions='.$_POST['sessions'].'&type=client_cred');
$curl_token = curl_init(POSTURL);
curl_setopt($curl_token, CURLOPT_POST,1);
curl_setopt($curl_token, CURLOPT_POSTFIELDS,POSTVARS);
curl_setopt($curl_token, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($curl_token, CURLOPT_HEADER,0);
curl_setopt($curl_token, CURLOPT_RETURNTRANSFER,1);
$token = curl_exec($curl_token);
$token_decoded = json_decode($token,true);
//get the user graph (personal info)
$user_graph = file_get_contents("https://graph.facebook.com/".$_POST['uid']."?access_token=".$token_decoded[0]['access_token']);
echo $user_graph;