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

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

Related

I want to create post with web site preview

I want to create a post with web site preview. It must be similar as on screenshot.
How do I create a post with web preview? I want to add it on pages.
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"Post with web preview", #"message", nil];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed", myself.pageID]
parameters:dict HTTPMethod:#"POST" completionHandler:nil];
More info about posting links (what you call "post with web site preview") here:
http://developers.facebook.com/docs/reference/api/link/
I asumme you have your Facebook APP with your permissions set, and that you're using PHP-sdk classes. Anyway, the proccess is the same for any language, just changing the way you write it. Also, you need the user Access Token with the proper permission set.
Using the PHP-sdk from Facebook, process would be:
// Load FB class, and init it
require_once("facebook.php");
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$facebook = new Facebook($config);
// You set the User Access Token (you need to have it previously to this: Because you
// requested before, or because you obtain it from Facebook)
$facebook->setAccessToken( $user_access_token );
try {
// Set the link params:
if ( isset($config['link']) ) {
$args = array(
'link' => $link_url //Url to be linked
, 'name' => $link_titulo //Box title
, 'description' => $link_descripcion //Box Description
, 'picture' => $link_foto //Photo to be posted
, 'message' => $link_message //Message over the "link box"
);
// Post in the User/FB_Page wall
$facebook->api('/me/feed', 'post', $args);
}
} catch (FacebookApiException $e) {
$fbError = $e->getResult();
$result = array(
'tipo' => 'error'
, 'code' => $fbError['error']['code']
, 'text' => $fbError['error']['message']
);
print_r($result);
}
Update
After reading your answer to my comment, I think you're looking just for the CSS and the layout. You can find something to achive the post formatting here:
http://jsfiddle.net/5NYD5/3/
This can be done using multiple ways,
If you are using facebook API then its easy, just like on FB(image will be automatically fetched)
Dim fb As FacebookClient = New FacebookClient('access_token')
Dim args As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()
args("message") = "Your Message to be posted"
args("link") = "http://www.example.com"
fb.Post("/me/feed", args)
I hope this will do,
else if you are not using FB API then its comparatively long way to grab image or create snapshot, of site manually. Just like search engine crawlers crawl after entering website. Its long way but yes possible.

CodeIgniter and Facebook Connect

I am trying to integrate my Codeigniter website with the Facebook PHP SDK. What I want to do is let a user share an article from my site on their facebook wall, if they are logged into a facebook account. My library appears to load correctly, but everytime I try to do something, I get some kind of error... primarily with the auth. getUser does not appear to return the correct results. I set up my facebook application and set the config vars for my library, but no luck. It says I am not logged into facebook. When I click on the "login" anchor, the link takes me to the same page, but with the facebook url, and doesn't ask me to login with the app. Here's my code:
function facebook($article_id){
$config = array(
'appId' => '276870792431073',
'secret' => '8d49eee575413fb9a8063d22f65dbf6a'
);
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if($user){
try {
$user_profile = $this->facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
}
if($user){
$article = $this->article->fetch_article($article_id);
$config = array(
'message' => 'I just read an '.anchor('articles/'.url_title($article['title']).'/'.$article_id, 'article').' on '.anchor('', 'TrackTheOutbreak.com').'!',
);
$this->facebook->api('/me/feed', 'post', $config);
} else {
$data['MESSAGE_TITLE'] = 'Authentication Error';
$data['MESSAGE_TEXT'] = 'You must be logged into an existing Facebook account to use this feature. Click '.anchor($this->facebook->getLoginUrl(), 'here').' to login.';
$this->parser->parse('error_body.tpl', $data);
}
}
In order to access a users information and post anything to their wall you first need to get a access token from them. To do that you need to make sure that you have gained their permission through Facebook's FB_login (and then Open Graph). I would double check with this guide and make sure that you have everything set up properly to post to their timeline.
https://developers.facebook.com/docs/reference/javascript/FB.login/
I hope this helps

facebook php-sdk providing same functionality as javascript FB.getLoginStatus

I am using javascript sdk to know if user is login and connected to our web-site' application by using FB.getLoginStatus() function.
I want to know if php-sdk provides me details about the user logged into facebook.
If user is logged in facebook and connected to our application, i have to make them to directly logged into our site.
How can this be done using php sdk.
Thanks in advance.
You can do the following:
$user_details=$fb->api_client->users_getInfo($fb_user, array('last_name','first_name','pic_square'));
And yes they do have a similar thing to the FB.getLoginStatus() :)
$params = array(
'ok_session' => 'https://www.myapp.com/',
'no_user' => 'https://www.myapp.com/no_user',
'no_session' => 'https://www.myapp.com/no_session',
);
$next_url = $facebook->getLoginStatusUrl($params);
Found it here: https://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
Just check the Example/Usage at the GitHub-Page:
https://github.com/facebook/facebook-php-sdk
according to documentation ( https://github.com/facebook/facebook-php-sdk ), after doing:
require 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
To check if the user is still logged in on facebook (kind of FB.getLoginStatus) you need to:
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
As noted by #DMCS this function should be used:
http://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
You generate an url: $next_url = $facebook->getLoginStatusUrl();
redirect the user to this url: header('Location: '.$next_url);
the user will be returned by FB with session information (POST) about the login status
the SDK will parse the return $_POST info
use $facebook->getUser(); to get the userid (if logged in)
So far so good. The only problem is, this function (point 4) is broken since the transition to oAuth2.0 by Facebook, see also this bug report:
http://developers.facebook.com/bugs/295348980494364
So please let FB know that you have the same issue by adding a reproduction.
Cheers!

Redirect back to page tab after user authenticates?

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!

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.