How To: Handle Application Requests Using The Facebook Graph API
We have learned from our previous tutorial how to send Facebook application requests and store the resultant ids to our DB.
But how should your application act when the “receiver/invitee” accept a request? This will be explained in this tutorial along with an additional tips of how to maximize the use of this great feature.
Requirements
Back to topExplanation
Before we start, let us revise our code from our previous tutorial and add the data field to the apprequests dialog (read the Facebook documentation):
<?php
// PATH TO THE FB-PHP-SDK
require_once '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET'
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl();
if ( empty($user) ) {
echo("<script> top.location.href='" . $loginUrl . "'</script>");
exit();
}
?>
<!doctype html>
<html>
<head>
<title>How To: Send An Application Request Using The Facebook Graph API - MasteringAPI.com</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: 'APP_ID',
status: true,
cookie: true,
oauth: true
});
};
$('a').click(sendRequest);
function sendRequest() {
FB.ui({
method: 'apprequests',
message: 'I want to give you this flower!',
title: 'Give a flower to some of your friends',
data: '{"item_id":1254,"item_type":"plant"}'
},
function (response) {
if (response.request && response.to) {
var request_ids = [];
for(i=0; i<response.to.length; i++) {
var temp = response.request + '_' + response.to[i];
request_ids.push(temp);
}
var requests = request_ids.join(',');
$.post('handle_requests.php',{uid: <?php echo $user; ?>, request_ids: requests},function(resp) {
// callback after storing the requests
});
} else {
alert('canceled');
}
});
return false;
}
// 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>
<a href="#">Send your friends a flower!</a>
</body>
</html>UPDATE: The code above has been updated to use the latest PHP-SDK (v3.x) and the new Requests 2.0 Efficient implementation
To better understand the Facebook application requests, we are going to assume that you have an application that allows the users to send their friends gifts/items. In the code above, the user will send his friends an item.
This item has the an id = 1254 (the id of “flower“s in our application/system) and of type/category plant.
As you can see, we are using json format in the data field. This would allow us to send data along with the request in a more structured way.
Handling the applications requests
From the Facebook documentation:
If a user clicks ‘Accept’ on a request, they will be sent to the canvas URL of the application that sent the request. This URL will contain an additional parameter,
request_ids, which is a comma delimited list of Request IDs that a user is trying to act upon
But be aware if you are setting the Bookmark URL in your application settings, Facebook will send the user to that url instead.
Handling the requests can be done in various ways depending on your application and its functionality and here is a basic usage:
<?php
if(!empty($_REQUEST['request_ids'])) {
$APPLICATION_ID = "APP_D";
$APPLICATION_SECRET = "APP_SECRET";
/*
* Get the current user, you may use the PHP-SDK
* or your own server-side flow implementation
*/
$user = getUserFromSignedRequest();
$app_token = get_app_access($APPLICATION_ID,$APPLICATION_SECRET);
// We may have more than one request, so it's better to loop
$requests = explode(',',$_REQUEST['request_ids']);
foreach($requests as $request_id) {
// If we have an authenticated user, this would return a recipient specific request: <request_id>_<recipient_id>
if($user) {
$request_id = $request_id . "_{$user}";
}
// Get the request details using Graph API
$request_content = json_decode(file_get_contents("https://graph.facebook.com/$request_id?$app_token"), TRUE);
// An example of how to get info from the previous call
$request_message = $request_content['message'];
$from_id = $request_content['from']['id'];
// An easier way to extract info from the data field
extract(json_decode($request_content['data'], TRUE));
// Now that we got the $item_id and the $item_type, process them
// Or if the recevier is not yet a member, encourage him to claims his item (install your application)!
echo $item_id;
if($user) {
/*
* When all is done, delete the requests because Facebook will not do it for you!
* But first make sure we have a user (OR access_token - not used here)
* because you can't delete a "general" request, you can only delete a recipient specific request
* <request_id>_<recipient_id>
*/
$deleted = file_get_contents("https://graph.facebook.com/$request_id?$app_token&method=delete"); // Should return true on success
}
}
}
function get_app_access($appId, $appSecret) {
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $appId .
"&client_secret=" . $appSecret .
"&grant_type=client_credentials";
$token = file_get_contents($token_url);
return $token;
}
function getUserFromSignedRequest() {
if(!empty($_REQUEST['signed_request'])) {
$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']) )
return $data['user_id'];
}
return null;
}
?>Here, we are:
- Getting an application access token
- Looping through the request ids (if we have any)
- Appending a recipient id if we have a user
- And based on the
datafield, we can do various actions - After that, we are deleting the request as recommended by Facebook
As you can see, we are not using the PHP-SDK. But you can always use it like so:
Reading the request:
$facebook->api("/$request_id?$app_token");Deleting the request:
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
//Assuming the user has already authenticated the app
$user_id = $facebook->getUser();
//get the request ids from the query parameter
$request_ids = explode(',', $_REQUEST['request_ids']);
//build the full_request_id from request_id and user_id
function build_full_request_id($request_id, $user_id) {
return $request_id . '_' . $user_id;
}
//for each request_id, build the full_request_id and delete request
foreach ($request_ids as $request_id)
{
echo ("reqeust_id=".$request_id."<br>");
$full_request_id = build_full_request_id($request_id, $user_id);
echo ("full_reqeust_id=".$full_request_id."<br>");
try {
$delete_success = $facebook->api("/$full_request_id",'DELETE');
if ($delete_success) {
echo "Successfully deleted " . $full_request_id;}
else {
echo "Delete failed".$full_request_id;}
}
catch (FacebookApiException $e) {
echo "error";}
}
?>Back to topNotes
It is always a good idea to set your Bookmark URL in your application settings so you have a separate script to handle the requestsBookmark URL is no longer in use- After deleting the request, it would be a good practice to update the DB record and set the
outstandingfield to zero (refer to the previous tutorial)
Table of contents
Advertisment
Recent Tutorials
- How To: Create A User Photo Albums Browser Using Facebook Graph API
- How To: Upload A Photo To A User’s Profile Using Facebook Graph API
- How To: Check Status And RSVP To Facebook Events Using Graph API & FQL
- Facebook Javascript SDK Best Practices
- How To: Create Facebook Events Using Graph API – Advanced







Pingback: How To: Send An Application Request Using The Facebook Graph API | API? Yes Master!