Server side flow example - facebook

At the bottom is a working example of server side flow. It is a file fb_server_side_flow.php that I prepared from a template I found on developers.facebook.com. My first question is what exactly is $code = $_REQUEST["code"]; doing? Is it getting a Facebook cookie? If so how is $code = $_REQUEST["code"]; different from the code directly below? Is it really necessary to use session_start at towards the top of fb_server_side_flow.php?
Mainly I am trying to implement a system that gives my user an OPTION to login via Facebook but a login via Facebook is not a requirement. Is there any documentation available on implementing a login via Facebook OPTION as opposed to a required login via Facebook?
Thank you!
....
function get_facebook_cookie($app_id, $app_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $app_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
....
fb_server_side_flow.php
<?php
$app_id = "****";
$app_secret = "****";
$my_url = "http://www.sepserver.net/dsg/fb_server_side_flow.php";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>

The first block of code is for retrieving Facebook cookie parameters for users who are already authorized and logged in.
The second block of code is for letting the user authorize your application (oauth) AND for retrieving an access_token your application can use to make API (FB Graph) calls on the user's behalf.
$_REQUEST relates to POST or GET parameters, not cookies. If you check the docs on authentication flow, you can see that Facebook redirects the user to http://your_redirect_uri?code=1234abcd after the user has approved your application. You're supposed to grab that code parameter and use it to make another call to graph.facebook.com to get the user's access_token.
The purpose of session_start() is to prepare the $_SESSION array, so that $_SESSION['state'] is preserved across page reload. If your framework already has session handling code, you can omit it. It's only used for the CSRF protection bit.
Optional login is pretty straightforward. If you're using the new PHP SDK, you can check the return value of $facebook->getUser(); -- if it's 0, the user is not logged in (and you can show content as normal, with perhaps an additional link to fb_server_side_flow.php to begin the authorization procedure.)

Related

facebook post wall how can I do?

I tried this code to post wall
<?php
$app_id = "XXXXXXXX";
$canvas_page = "XXXXXXXX";
$message = "My story";
$feed_url = "http://www.facebook.com/dialog/feed?app_id="
. $app_id . "&redirect_uri=" .urlencode($canvas_page) . "&message=" . $message;
if (empty($_REQUEST["post_id"])) {
echo("<script> top.location.href='" . $feed_url . "'</script>");
} else {
echo ("Feed Post Id: " . $_REQUEST["post_id"]);
}
?>
But I really want to post wall like this:
Someone can give me an example?please!
That image shows a pop-up that looks like a Facebook dialog, but is actually designed by the app developers so it would something you would build yourself.
P.S: I suggest trying to use https://developers.facebook.com/docs/reference/dialogs/feed/ instead of your current method.

oauth not display user_checkins permission

I have the scrips that redirect to the facebook's oauth dialog and need a user_checkins permission
<?php
session_start();
$app_id = "[APP_ID]";
$app_secret = "[APP_SECRET]";
$my_url = "(back to this page)";
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state']."&scope=user_checkins" ;
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?fields=checkins&access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo "<pre>";
print_r($user);
echo "</pre>";
} else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
dialog display only
THIS APP WILL RECEIVE:
■ Your basic info
but it should have one more line with checkins permission, isn't it?
so, i try to use the Graph API Explorer.
First i test with my APP, the result is the same,
still can't get user_checkins permission
But if i change the "Application:" section to Graph API Explorer and test again,
Everything seems to be OK..
So, I think it's cause of my APP settings.. or something..
Could you please suggest me how to fix this ?
By the looks of it, I would say Facebook has deprecated the user_checkins and friends_checkins permissions and rolled them into user_status and friends_status.
Anyway, request the user_status permission instead, and you will now be able to read the user's checkins.
there is an option to get the checkins. facebook have given other option to this.
http://developers.facebook.com/docs/reference/api/user/#posts
You can get the checkins with
https://graph.facebook.com/me/posts?with=location

Read Facebook page post and token expiration

I need to read, from a server, the stream of a specific fan page.
I tried to read the graph api
https://graph.facebook.com//feed?access_token=&limit=100
and it works.
What I need is to understand if the token will expire and how to renew it programmatically.
Now I generate my token through the http://developers.facebook.com/tools/explorer/ app.
Can you please help me?
I'm using the PHP sdk
thanks,
a.
You can read the facebook page using below codes and you can also get the specified fields
https://graph.facebook.com/$page_id/?fields=link,etc&access_token=page_access_token
or
$response = $fb->api($page_id . '/?fields=link,etc&'. $access_token, 'GET')
Below is the solution for four scenarios
1.The token expires after expires time (2 hours is the default).
2.The user changes her password which invalidates the access token.
3.The user de-authorizes your app.
4.The user logs out of Facebook.
To ensure the best experience for your users, your app needs to be prepared to catch errors for the above scenarios. The following PHP code shows you how to handle these errors and retrieve a new access token.
When you redirect the user to the auth dialog, the user is not prompted for permissions if the user has already authorized your application. Facebook will return you a valid access token without any user facing dialog. However if the user has de-authorized your application then the user will need to re-authorize your application for you to get the access_token.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
for more details info you can visit this link
Thanks

How to redirect a user to Auth Dialog?

I followed the steps here
And my application doesn't redirect the user
$app_id = APP_ID;
$canvas_page = APP_LINK;
$auth_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=email,read_stream";
echo "<script> top.location.href='" . $auth_url . "'</script>";
PS: I was successful in redirecting the user with <fb:redirect> but since FBML will not be supported in some months, I want to find another way and "top.location.href" should be works :(
you probably need a semicolon to get the code to execute. Also, the equals sign is necessary. (Thanks David Barker)
$app_id = APP_ID;
$canvas_page = APP_LINK;
$auth_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=email,read_stream";
echo "<script> top.location.href='" . $auth_url . "';</script>";
What do you get when you do this:echo "<script> alert('".$auth_url."');</script>";?
Also, and easier way to do this in PHP is like this:
$app_id = APP_ID;
$canvas_page = APP_LINK;
$auth_url = "http://www.facebook.com/dialog/oauth?client_id". $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=email,read_stream";
echo <<<EOT
<script>
top.location.href="$auth_url";
//checking the value of auth_url to see if that is the reason redirect is not happening.
if (window.console) {
console.log("$auth_url");
} else {
alert("$auth_url");
}
</script>
EOT;
Using heredoc syntax you will not have to escape anything, you can use single and doublequotes within, and variables are intrinsically replaced in your string. ;)

extended permission using php sdk

I am developing a facebook application using php-sdk. i want to take some extended permissions from user of my application. As this is application where user comes after login into facebook, so how can i take extended permission when user visit my page? We cannot place login button in which we can take permissions.I means when user first time comes to my application a pop up widow having a list of permission. How to display that at first visit of any user to my application. Any one can guide me how to take and where to place that code?
Thanks in advance.
Regards,
Awais Qarni
check this
`<?php
$app_id = "YOUR_APP_ID";
$app_sec = "APP_SEC";
$canvas_page = "APP_CANVAS_PAGE_URL";
$scope = "&scope=user_photos,email,publish_stream"; $auth_url"http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page).$scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"])) {
echo(""); }
$access_token = $data["oauth_token"];
$user_id = $data["user_id"];
$user = json_decode(file_get_contents( "https://graph.facebook.com/me?access_token=" . $access_token));
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
ksort($args);
$payload = "";
foreach ($args as $key => $value) {
if ($key != "sig") {
$payload .= $key . "=" . $value;
}
}
if (md5($payload . $application_secret) != $args["sig"]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($app_id, $app_sec);
?>