Redirect back to page tab after user authenticates? - facebook

How should I go about redirecting the user back to my page's tab after they authenticate my app? I cannot put one specific url in for the redirect since my app will live on multiple pages. So somehow I need to grab the page's id and put it into the url. I've tried to use session variables but it doesn't seem to be working for me. :( Here's a portion of my code...
$signed_request = $facebook->getSignedRequest();
$_SESSION['TrueID'] = $signed_request['page']['id'];
$fbconfig['appBaseUrl'] = "http://www.facebook.com/pages/".$_SESSION['TrueID']."/".$_SESSION['TrueID']."?sk=app_241321439259320";
/*
* If user first time authenticated the application facebook
* redirects user to baseUrl, so I checked if any code passed
* then redirect him to the application url
* -mahmud
*/
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
//~~
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
As you can see I'm trying to set a session variable to grab the page's id.. but that's not working for me :( The variable echo's out just fine when I visit my page.. but I'm guessing its getting lost somewhere during the authentication.

So when a Page add/install your app, you should store the page's link along with the page's id.
Now when your page tab is loaded, Facebook will send the page parameter which will contain the page id (along with other info, refer to the documentation). You retrieve that id, get the page's link from your db and construct your page tab link, which would be something like (where $page is the page's db record):
$redirect_uri = $page['page_link'] . '?sk=app_' . $APP_ID
Since you are using the PHP-SDK, this is how you construct your login:
$user = $facebook->getUser();
if(!$user) {
$url = $facebook->getLoginUrl(array('redirect_uri' => $redirect_uri, 'scope' => 'read_stream'));
echo "<script>top.location.href = '$url';</script>";
exit;
}
Of course you may not want to redirect to the login directly but instead have a call to action link:
Connect

Best way I found is to set the Site URL in the app settings to http://www.facebook.com/pages/
Then do something like this(tested):
$uid = '';
$facebook = new Facebook(array(
'appId' =>'xxxxxxxxxxxxxxx',
'secret' =>'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
'oauth' => true,
));
$uid = $facebook->getUser();
$signedrequest = $facebook->getSignedRequest();
$page_id = $signedrequest["page"]["id"];
$fb_access_token = $signedrequest["oauth_token"];
if($uid==''){
echo '<div id="authenticate">Authorize App</div>';
This might be a little bit of a hack, but it works well for my situation:) Hope it helps someone!

Related

facebook app oauth error (can not be displayed in frame)

I just wanted to create a FB app. I went to developers.facebook.com/apps, set up a new app, created a new folder on my server, copied an old (working) app into the folder, changed the app id, secret, canvas page and canvas url in my configuration file... and it did not work.
It displayed an error: "this content can not be displayed in frame".
I would be grateful if you could help me. Thanks.
I copy here my config file: (I intentionally removed the app id and secret here.)
// Facebook App ID/API Key
$appId = '';
// Facebook App Secret
$secret = '';
// Facebook Canvas Page
$redirect_uri = 'https://apps.facebook.com/appname/';
// Facebook Canvas URL
$canvas_url = 'https://myhost.com/appname/';
// Facebook App Permissions
$scope = 'email, publish_actions';
// Configure Facebook connection
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(array(
'redirect_uri' => $redirect_uri,
'scope' => $scope,
));
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
header("Location: $loginUrl");
}
You should use JavaScript to redirect the user to the login URL using top.location = '{url}', and then use the login redirect url to send them back to your application. Facebook doesn't allow you to use facebook within an iframe, that why you are seeing that error message - pretty self explanatory.
It displays a "this content can not be displayed in frame" errormessage.
And what about this message gives you trouble understanding?
You can't call the auth dialog in an iframe, because it would enable phishing if the user can’t check the sites address.

facebook : load the wall content of a facebook page in a website

I have a website and a facebook page for the website. For most of the news update, I post them on the facebook page's wall.
Now I want to show the wall's content of that facebook page on my website, just like the facebook's Like Box with "stream" enabled: http://developers.facebook.com/docs/reference/plugins/like-box/
However, I only want to show the stream, and perfectly can show it in my own presentation. So is it possible to get only the content of a facebook page by facebook's API?
I think if you use the SDK you can get it by using
fb->api("/{id}/feed");
There's a php and a javascript sdk.
But you also need an access token now to get the feed of a page.
EDIT: Here's a copy of example.php (from the php-sdk) modified for your purpose.
include_once("facebook-sdk/facebook.php");
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID GOES HERE',
'secret' => 'SECRET GOES HERE',
));
// 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.
// This is where we grab the posts
$wall_posts = $facebook->api('/courseyou/posts');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>Login with Facebook</div>
<?php endif ?>
<h3>Wall Posts</h3>
<?php
foreach ($wall_posts["data"] as $post) {
echo "<p>".$post["from"]["name"].": ".$post["message"]."</p>";
}
?>
As far as I know you need an access token to view a page's posts/feed with the api, which makes me think that you need the user to login with facebook.... I'm fairly new to this, but you should look into how to get an access token, because you need one for this.

Facebook how to keep facebook session

I hope that someone can help me. I am developing a Iframe application. I am using a mixture of PHP and Javascipt.
Everything works perfectly if you click on the facebook tab created in the facebook profile. However I have a second page which edit the some functionality in my page, If I navigate to this page, it seems to loose it's authentication, or login session.
The like button, goes to not-liked - (so it seems to me the session breaks).
How can I keep the facebook session, to the next page?
I have included the complete page of my nav.php (This is the page that facebook first access)
<?php require 'facebook.php';
$app_id = "MY-APP-ID";
$app_secret = "MY-APP-SECRET";
$apiKey = "1573bcaff76885d24c5ca93d93266a9e";
$app_url = "http://domain.com";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
if ($_SERVER['HTTP_REFERER'] != 'http://domain.com/facebook/edit_page.php');
{
$signed_request = $facebook->getSignedRequest();
$page_id = $signed_request["page"]["id"];
$page_admin = $signed_request["page"]["admin"];
$like_status = $signed_request["page"]["liked"];
$country = $signed_request["user"]["country"];
$locale = $signed_request["user"]["locale"];
if ($page_admin == 1) {
$oauth_token = $signed_request["oauth_token"];
}
}
if ($like_status) {
// If you like the page this will show - START
}
else {}
if ($page_id == '12345') {
echo "content for 12344";
}
elseif ($page_id == '56789') {
echo "content for 56789";
} ?>
In this page I can see who is the owner of the page, and the LIKE button shows liked! how do I pass the authentication to a next page? so that the Like button stay Liked?
Any help would be appreciated!
Thanks
I have figured out the problem - In my case I needed to pass the getSignedRequest(); to all pages, for the session to stay in place.

How do I get the facebook user access_token for my feed

I am using jQuery to work with a json-data from my Facebook wall. The call for my json-file is like that:
var url = 'http://graph.facebook.com/myname/feed';
$.getJSON(url+'&callback=?',function(json){...});
Since June 4th. I got the Facebook message that I need an user access_token. BUT where/how can i get this token? And what do i have to do if i want to use this token all my lofe long?
I had the same issue and made a walkaround using a "gate" php like this:
// Settings
$FBid = 'YOUR PAGE ID'; //Page name or Page ID
$app_id = 'YOUR APP ID';
$app_secret = 'YOUR APP SECRET';
$url_get_access_token = 'https://graph.facebook.com/oauth/access_token';
$url_params = "?type=client_cred&client_id=".$app_id."&client_secret=".$app_secret;
$access_token = file_get_contents($url_get_access_token . $url_params);
//Get the contents of a Facebook page
$dataType = 'posts'; // it could be replaced by feed, etc.
$url_fb_data = "https://graph.facebook.com/".$FBid."/".$dataType."?".$access_token;
$FBpage = file_get_contents($url_fb_data);
//Convert data into a php object format
//$FBdata = json_decode($FBpage);
//Print data in JSON format
echo $FBpage;
Having this script, all you have to do is change the call to this instead of https://graph.facebook.com/......
I hope this helps you, It worked for me.

Facebook iFrame app - how to fetch Preload FQL result using PHP SDK?

since few years I have an FBML app (a small Flash game) which I'm now trying to convert to an iFrame app. Unfortunately there aren't many docs for Facebook iFrame apps yet.
For my game I need the user's first name, picture, gender and the city.
In my old version I had this preload FQL (created once by a PHP script):
$fql = array('info' => array('pattern' => 'facebook',
'query' => 'SELECT first_name, sex, pic_big, current_location
FROM user WHERE uid={*user*}'));
$fb->api_client->admin_setAppProperties(
array('preload_fql' => json_encode($fql)));
and then my FBML app script had been as simple as:
<?php
require_once('facebook.php');
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'YYY');
$fb = new Facebook(FB_API_ID, FB_AUTH_SECRET);
$viewer_id = $fb->require_login();
$data = json_decode($fb->fb_params['info'], true);
$first_name = $data[0][0];
$last_name = $data[0][2];
$female = ($data[0][3] != 'male');
$avatar = $data[0][3];
$city = $data[0][4]['city'];
# and then I'd just construct flashvars attribute
# for the <fb:swf ...> tag and print it
?>
Does anybody please have hints on how to recreate the same script for the iFrame version - i.e. how can I fetch the result of Preload FQL by my iFrame app?
According to an older Facebook blog entry Preload FQL should be accessible by the iFrame apps.
Thank you!
Alex
My own answer after long searching is that Preload FQL results aren't sent to iframe Facebook apps.
That is why Facebook performance doc says:
"Preload FQL Query and Multiquery.
This section applies to FBML canvas pages, but not to websites or IFrame canvas pages."
As Facebook said for Preload FQL
"Facebook will send the result of these FQL queries as JSON-encoded POST parameters to your Canvas URL"
print_r your $_POST and see which variable is the "json-encoded results". You convert json into php object using json_decode
JSON looks like this: {"var":"val","var":"val"}
Also, Facebook already has great docs for iframes. Then you might have missed these great docs:
Facebook Docs Home
http://developers.facebook.com/docs/
Authentication
http://developers.facebook.com/docs/authentication/
Signed Request
http://developers.facebook.com/docs/authentication/signed_request/
iFrame Canvas Apps
http://developers.facebook.com/docs/guides/canvas/
PHP SDK
https://github.com/facebook/php-sdk
Graph API
http://developers.facebook.com/docs/reference/api/
You don't need to call any FQL for the information you are getting. For iFrame you just need to do following steps
Download the PHP SDK of graph api https://github.com/facebook/php-sdk/
Create the object and authorize the app from user
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
// User location extended permission allow you to get user's current location
$loginparams = array('canvas' => 1,'fbconnect' => 0,'req_perms' => 'user_location');
$loginUrl = $facebook->getLoginUrl($loginparams);
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
d($e);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
// You can found all the data in this array.
print_r($fbme);
For more detail you can follow this tutorial http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
Hope it works for you