FQL to know if a user like a page [duplicate] - facebook

I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!

I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}

You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}

You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/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.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// 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>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.

Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });

i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

Related

facebook - how to get user id with phpsdk and js sdk

I'm implenting my fb app and it's connected to its own fb fanpage. I need to get a users info like username, id etc but when I click on my "Facebook authenticate" link, I end up going to a blank white page?
You can view my code in here: http://codepad.org/f0Tuh63v
error_reporting(E_ALL);
ini_set('display_errors', true);
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => '1',
'secret' => '2',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
else{
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'user_about_me,user_birthday,email,publish_actions,offline_access,user_hometown,user_location',
'redirect_uri' => "https://domain.net/intro.php"
)
); // end of array
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
Facebook authenticate
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true,
status: true
});
FB.Event.subscribe('auth.login', function(response) {
//window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
//window.location.reload();
});
};
(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>
</body>
</html>
It's also here http://codepad.org/f0Tuh63v
What am I doing wrong?
Also is there a way to get the FB user id without using phpsdk or the js sdk? Or do I have to use these plugins?
I cannot see what's wrong with your code. But, If you are using Javascript, I can tell you an alternative for getting authenticated and then getting the info you require.
I used the following code behind my button, which authenticated my Facebook app and then redirected the user to my website. It worked for me.
<a class="fb-login-button" align="center" target="_blank" href="https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&response_type=token&scope=PERMISSION_1,PERMISSION_2&redirect_uri=YOUR_WEBSITE"> TEXT </a>
Then I extracted the token which was returned in the redirected URL.
var url_t; // Get the redirected URL.
access_token = url_t.split('=')[1].split('&')[0];
Then using the access token I sent the HTTP request for getting the required data. I used GRAPH API provided by facebook. For eg: For getting the first name of the user:
var xhr = new XMLHttpRequest();
var f_url_new = "https://graph.facebook.com/fql?q=SELECT%20name%20FROM%20user%20WHERE%20uid%20=%20me()&access_token=" + access_token;
xhr.open("GET", f_url_new , true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
obj1 = JSON.parse(xhr.responseText);
var str = obj1.data[0].name.toString();
var n=str.split(" ");
document.getElementById("name").innerText = n[0];
}
}
xhr.send();
Hope it gives you some idea with regards to the alternatives. This is not the correct answer to your question, but can help in the thought process.

Login and Logout issue using facebook-php-sdk

I am working on website, in which i want integrate the facebook login with my website login system. I have integrated facebook-php-sdk in code. Login functionality work fine. Below are the points that I have issue...
Once logged out and click on login the facebook login screen not open.
Once logged out and refresh the page, the login deatils is displaying again. And login button disappears.
If the above two points will solved then how to maintain login session through out the website?
For above 2 points I have used the below code.
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => SECRET_KEY,
));
session_start();
if($_REQUEST['msg'] == 'logout'){
setcookie('fbsr_'.$facebook->getAppId(), '', (time() - 3600), '/', 'domain.com');
$sts = $facebook->destroySession();
session_destroy();
header("Location: index.php");
//echo '<meta http-equiv="refresh" content="2;url=index.php">';
}
$userId = $facebook->getUser();
if ($userId && !isset($_SESSION['fbdata'])) {
$_SESSION['fbdata'] = array("userid" => $userId);
}
<?php if ($userId) {
$userInfo = $facebook->api('/' + $userId); ?>
Welcome <?= $userInfo['name'] ?>
<?php } else { ?>
<div id="fb-root"></div>
<fb:login-button></fb:login-button>
<?php } ?>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?= YOUR_APP_ID ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response) {
//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>
<br />
<br />
Logout
I found the answer on my questions below.
1.Once logged out and click on login the facebook login screen not open.
Facebook cookies was not deleted or we can say was not removed from starage. For this I have used this below javascript
function removeCookie( name, path, domain) {
if ( getCookie( name ) )
{
document.cookie = name + '=' + ( ( path ) ? ';path=' + path : '') + ( ( domain ) ? ';domain=' + domain : '' ) + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
}
It works for me.
2.Once logged out and refresh the page, the login deatils is displaying again. And login button disappears.
The same reason as above question.
3.If the above two points will solved then how to maintain login session through out the website?
Maintain the fb id in session and when request coming for logout remove cookie and destroy the session.

An active access token must be used

I'm trying to get the Facebook user (current user) an U´m using the code:
$app_id = "xxx";
$app_secret = "yyy";
//** Get user information
//Create our application instance.
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');....
// The $user_profile = $facebook->api('/me'); line throw an exception:
'message' => string 'An active access token must be used to query
'information about the current user.' (length=80)
'type' => string 'OAuthException' (length=14)
'code' => int 2500
Why?
It seems you did not go through the OAuth 2.0 authentication/authorization process as described at Authentication.
There are some examples there explaining how to do this. I am also using the PHP SDK but I chose to do the authentication through JavaScript on the client side which was easier for me. However, both approaches are explained in the documentation.
Updated: I use this code which is a combination of PHP and JavaScript, which works great for me. The only thing that isn't handled correctly here (AFAIK) is when a user reaches the application when he is not logged in to Facebook, that is, he reaches the application directly through the URL and not through Facebook. In that case a blank page is shown instead of a notification and a login button or something.
Anyway, this is my index.php in which I pass vars from my config.inc.php such as the success (application main page) and failure pages (user didn't grant perms) to JavaScript:
<?php
require 'include/config.inc.php';
//Check whether Facebook OAuth mechanism called back to this script with access_token or error
if (isset($_GET['expires_in']) && $_GET['expires_in']>0)
{
header('Location: '.$appname_canvasPage.$appname_successPage);
exit;
}
else if (isset($_GET['error']))
{
//echo 'querystr: '.$_SERVER['QUERY_STRING'];
header('Location: '.$appname_canvasPage.$appname_failurePage);
exit;
}
else
{
require 'include/header_metadata.inc.html';
?>
</head>
<body>
<div id="fb-root"></div>
<script>
var appname_canvasURI = '<?php echo $appname_canvasURI; ?>';
var appname_canvasPage = '<?php echo $appname_canvasPage; ?>';
var appname_successPage = '<?php echo $appname_successPage; ?>';
var appname_failurePage = '<?php echo $appname_failurePage; ?>';
var appname_fbPerms = '<?php echo $appname_fbPerms; ?>';
var appname_appid= '<?php echo $appname_appid; ?>';
window.fbAsyncInit = function()
{
FB.init({
appId : appname_appid, // App ID
channelUrl : appname_canvasPage+'/channel.html', // Channel File
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
});
// Additional initialization code here
FB.getLoginStatus(function(response)
{
//console.log('getLoginStatus response: ',response);
if (response.authResponse)
{
//user is already logged in and connected
facebookCheckPerms(); // ensure all requires perms are available and if not request them
}
else
{
//app is not authorized or user is logged out
facebookOAuthRedirect();
}
});
};
// Load the SDK Asynchronously
(function()
{
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
//e.src = "http://static.ak.fbcdn.net/connect/en_US/core.debug.js";
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function facebookCheckPerms()
{
var hasReqPerms=true;
FB.api(
{
method: 'fql.query',
query: 'SELECT '+appname_fbPerms+' FROM permissions WHERE uid=me()'
},
function(response)
{
for(var key in response[0])
{
if(response[0][key]==0)
{
hasReqPerms=false;
}
}
if (hasReqPerms==false)
{
// user does not have required permissions, do OAuth 2.0 redirect to get permissions
facebookOAuthRedirect();
}
else
{
// user has required permissions, start the app.
//console.log('checkperms: user has required permissions, start the app');
top.location.href = appname_canvasPage+appname_successPage;
}
});
}
function facebookOAuthRedirect()
{
var redirectURL = 'https://www.facebook.com/dialog/oauth/?client_id='+appname_appid+'&scope='+appname_fbPerms+'&redirect_uri='+encodeURIComponent(appname_canvasURI)+'&response_type=token';
//console.log('redirectURL: '+redirectURL);
top.location.href = redirectURL;
}
</script>
<?php
}
?>
</body>
</html>

Get user basic information using facebook Login button plugin?

Here I am using Facebook Login button plugin and javascript sdk
I am able to successfully login and logout by using above.
When a first time user has gone through authentication process I need to store user basic information i.e. Facebook login name, email in my database.
Please suggest how I can do this.
<p><fb:login-button autologoutlink="true"></fb:login-button></p>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '123456', status: true, cookie: true,
xfbml: true
});
};
(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);
} ());
</script>
Subscribe to the event auth.login. If you do this, Facebook will call your handler after a login as happened.
In that handler, use FB.api to call the Graph API to get any information you desire. For example calling /me as shown in the second example will get you basic information about the logged in user.
Now you have all the data in JavaScript. To send that up to your server, do a plain old XMLHttpRequest/AJAX request. Your JavaScript library probably makes this easy -- in jQuery this is jQuery.ajax() -- but worst case you can use XHR directly.
Now you have the data on your server and you can do whatever you want, like store it in the database. If you only want to store the data once, just check that you haven't already stored info about that user ID yet.
It's also possible to use a combination of PHP SDK and JS SDK, with the latter performing the login and the former storing data on the server. Something like:
<?php
require_once 'config.php';
require_once 'lib/facebook.php';
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId:'<?php echo $facebook->getAppID() ?>',
cookie:true,
xfbml:true,
oauth:true
});
FB.Event.subscribe('auth.login', function (response) {
window.location = "showUser.php"; //redirect to showUser.php on Login
});
FB.Event.subscribe('auth.logout', function (response) {
window.location.reload();
});
};
(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>
<div class="fb-login-button" data-show-faces="true" data-width="200"
data-max-rows="1"></div>
</body>
</html>
And in showUser.php you have something like:
<?php
#showUser.php
require_once 'config.php';
require_once 'lib/facebook.php';
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
$user = $facebook->getUser();
if($user)
{
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
var_dump($user_profile); //You can now save this data
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
}
?>
There's a hole in that solution -- this means the user can make up any information he wants and post an XHR back to my server. The server is going to need to check with Facebook directly.
//very simple just change this line
fb:login-button autologoutlink="true"
//with this one
fb:login-button autologoutlink="true" onlogin='your_ajax_fun_that_store_in_db()'
function your_ajax_fun_that_store_in_db(){
FB.api('/me', function(response) {
$.post( "ajax/store_user_info.php",response, function( data ) {
//write you js code here !
//you can use the (response) from facebook directly in your store_user_info.php as it will be sent in POST array
});
});
}
//last thing when you face such a problem the first thing to do is to go back to facebook reference of fun.

Asking for facebook permissions only when required

I have the following script which works, i.e. it goes to the facebook login page if the user is not already logged in, and asks them if they are ok with the app to post messages on their wall:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'removed for security reasons',
'secret' => 'removed for security reasons',
'cookie' => true,
));
$session = $facebook->getSession();
if ($session) {
if (isset($_GET[id])) {
$post = $facebook->api("/" . $_GET['id'] . "/feed", "POST", array('message' => 'Hello!'));
echo 'A message has been posted on your friends wall';
} else {
$friends = $facebook->api('/me/friends');
foreach ($friends as $key=>$value) {
echo 'You have ' . count($value) . ' friends<br />';
foreach ($value as $fkey=>$fvalue) {
echo 'friend id = ' . $fvalue[id] . ' - friend name = ' . $fvalue[name] . ' - post message<br />';
}
}
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'publish_stream',
'next' => 'http://'.$_SERVER['SERVER_NAME'].'/stage1.php',
'cancel_url' => 'http://'.$_SERVER['SERVER_NAME'].'/cancel.php',
));
header('Location: '.$loginUrl);
}
?>
How can this be improved so it does not ask for extended permissions in the start. It should only ask for basic permissions to display the friends list, and only ask for extended permissions if the user clicks on the friend to post a message.
Here's a rewrite of your code, with what I think are best practices:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'removed for security reasons',
'secret' => 'removed for security reasons',
'cookie' => true,
));
$session = $facebook->getSession();
// Prepare the login url with the right permission
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'publish_stream',
'next' => 'http://'.$_SERVER['SERVER_NAME'].'/stage1.php',
'cancel_url' => 'http://'.$_SERVER['SERVER_NAME'].'/cancel.php',
));
if ($session) {
try {
// Before processing the request
// check if we got the right permission
$perms = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT publish_stream FROM permissions WHERE uid=me()"
));
if($perms[0]['publish_stream']==='1') {
// We have the right permission
if (isset($_GET['id'])) {
// A small security measure
$id = (int) $_GET['id'];
$post = $facebook->api("/$id/feed", "POST", array('message' => 'Hello!'));
echo 'A message has been posted on your friends wall';
} else {
$friends = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me())"
));
foreach($friends as $friend)
echo "friend id = {$friend['uid']} - friend name = {$friend['name']} - post message<br />";
}
} else {
// We don't have the right permission
header('Location: '.$loginUrl);
}
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
header('Location: '.$loginUrl);
}
?>
How to check for a permission is explained here. Also I've added comments to save writing an explanation.
Quickly, there is something I want to point out regarding the following block of code:
foreach ($friends as $key=>$value) {
echo 'You have ' . count($value) . ' friends<br />';
foreach ($value as $fkey=>$fvalue) {
echo 'friend id = ' . $fvalue[id] . ' - friend name = ' . $fvalue[name] . ' - post message<br />';
}
}
Your 1st foreach loop is really misleading and not good practice at all. The Graph API isn't overly consistent in how it presents data, but the reason you are doing the foreach is to deal with the data key in the JSON object that is returned. This is generally a bad idea, because that data key is typically present along with other keys (like paging). Instead, I would check to see that $friends['data'] is not empty, and then re-assign the $friends array like so: $friends = $friends['data'];.
Example:
if (!empty($friends['data']))
{
$friends = $friends['data'];
}
else
{
$friends = array();
}
now, for your question.
You mentioned that you don't want to over-ask for permissions. That's a great thing to want, but the problem with it is that Facebook doesn't make it exceedingly easy to check for which permissions you do have or do not have. There is an FQL table that allows you check if your user has a certain set of permissions, but this table doesn't get updated with any kind of urgency. If you obtain extra permissions from a user (or if a user retracts permissions) and you then check this FQL table for the status of the permission, it can (and probably will) read the incorrect value and you will get a false positive.
You have three options to deal with this, that I can think of right off the top of my head.
Continue on your stage1.php code, as you are - there's nothing wrong with the way you're obtaining the installation and the session for the user there. You change page 2 to redirect your user through the OAuth endpoint requesting the publish-stream permission every time the user loads the page. The OAuth endpoint will not re-prompt the user to install, and will send them on their way.
The cons with this approach is, every request to post to a friends' wall turns into 3 requests.
The initial page load
The OAuth redirect / load
The redirect from OAuth back to your application
This approach also requires that you add a flag to your next key in your loginURL, which you can look for to make sure the user went through the OAuth endpoint, otherwise you're going to get an infinite redirect error.
Utilize the FB Javascript SDK to check for your users' current set of permissions. To do this, you'll utilize the FB.getLoginStatus method.
Example:
<div id="fb-root"></div>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"
type="text/javascript" charset="utf-8">
</script>
<script src="http://connect.facebook.net/en_US/all.js"
type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript">
(function($)
{
FB.init({
appId: '<?= FB_APP_ID; ?>',
cookie: true,
status: true,
xfbml: true
});
$('a').click(function(event)
{
var self = this;
event.preventDefault();
FB.getLoginStatus(function(session)
{
if (session.perms.match(/\"publish_stream\"/))
{
/* This user has publish stream, so we don't need
* to ask again
**/
window.location = $(self).attr('href');
}
else
{
/* This user does not have publish stream, so we need
* to ask.
**/
FB.login(function(response)
{
if (response && response.perms.match(/publish_stream/))
{
/* We now have publish stream access! */
window.location = $(self).attr('href');
}
}, {
perms: 'publish_stream'
});
}
})
return false;
})
})(jQuery);
Don't utilize any extended permissions, use the Javascript SDK (again) and give the user a publish-dialog for each user they would like to publish on the wall of. This is a relatively easy thing to do, also.
Example:
given your links for users:
Friend 1
Friend 2
Friend 3
You can do something like this:
<div id="fb-root"></div>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"
type="text/javascript" charset="utf-8">
</script>
<script src="http://connect.facebook.net/en_US/all.js"
type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript">
(function($)
{
$('a').click(function(event)
{
var user_id = $(this).data('id');
FB.ui({
method: 'feed',
message: 'Hello!',
to: user_id
}, function(response)
{
//this gets called whether it was successful, or not.
})
});
})(jQuery);