How To: Send An Application Request Using The Facebook Graph API
Providing your users a way to send requests to their friends may be the key of your application success. So we are going to learn today how to send an application request to your friends.
Before we start, have a read of the Requests Dialog provided by Facebook. As usual, we are not going to write back the whole documentation here.
Requirements for this tutorial
- The Facebook PHP-SDK and JS-SDK (The PHP-SDK is not really needed if you have your own server-side flow implementation or client-side)
- The jQuery Javascript library
Requests 2.0 Efficient
On Friday, September 30, 2011 Facebook introduced a new “improved” and more efficient request structure.
To help you understand what have been changed, previously when we were sending a single request to multiple friends multiple request_ids are being created. All these requests data are identical but with different to field. Now Facebook is creating one request_id and appending the recipient id to it you get a recipient specific request.
Code below has been updated to reflect the change.
Back to topSending the application request
Sending an application request is quite easy and here is a full example of how we do it:
Requests 2.0 Efficient implementation:
<?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: 'Check out this application!',
title: 'Send your friends an application request',
},
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 Application Request</a>
</body>
</html>Old Requests implementation:
function sendRequest() {
FB.ui({
method: 'apprequests',
message: 'Check out this application!',
title: 'Send your friends an application request',
},
function (response) {
if (response && response.request_ids) {
var requests = response.request_ids.join(',');
$.post('handle_requests.php',{uid: <?php echo $user; ?>, request_ids: requests},function(resp) {
});
} else {
alert('canceled');
}
});
return false;
}UPDATE: The code above has been updated to use the latest PHP-SDK (v3.x)
As you can see, we are using the jQuery.post() method to send the application request ids to our handling script.
The reason of doing this is to save the request ids along with the “sender” id ($uid). For me, this is very important since Facebook will only give you the ability to access this request by knowing the “recipient” or the request id!
Storing the requests
From the code above, we are sending the request ids (more than one if the user selects more than one friend) along with the current logged-in/connected user id to handle_requests.php. Which reads as follows:
<?php
if( isset($_POST['request_ids']) && isset($_POST['uid']) ) {
$dbhost = "DB_HOST";
$dbname = "DB_NAME";
$dbuser = "DB_USER";
$dbpass = "DB_PASSWORD";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$uid = mysql_real_escape_string($_POST['uid']);
$requests = explode(',',$_POST['request_ids']);
foreach($requests as $request_id) {
$request_id = mysql_real_escape_string($request_id);
mysql_query("INSERT INTO fb_requests (fb_user_id, request_id) VALUES ('$uid', '$request_id')") or die("MySQL Error: " . mysql_error());
}
}
?>Where the Database structure may look like:
CREATE TABLE `fb_requests` ( `fb_user_id` VARCHAR(25) NOT NULL, `request_id` VARCHAR(35) NOT NULL, `outstanding` tinyint(1) NOT NULL DEFAULT '1', UNIQUE KEY `unique_pair` (`fb_user_id`,`request_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
And we are done!
Back to topNotes
- We are storing the request id along with the “sender” id because we think this piece of information is useful for some applications
- The
outstandingfield in the Database table is just a flag indicating that this request has not been processed yet, and you should update it to zero as soon as the “receiver” open the request! This is a better choice than deleting the record (can be used for statistics for later stages) - You may add a
datefield to your table to “expire” the request after a certain period if the “receiver” didn’t interact with it as Facebook will not handle it for you! (Facebook will wait for 14 days before expiring the request)
UPDATE:
How to read/delete these requests and more advanced uses will come shortly in our next tutorial!. Read: How To: Handle Application Requests Using The Facebook Graph API
Advertisment
Recent Tutorials







Pingback: How To: Handle Application Requests Using The Facebook Graph API | API? Yes Master!