Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 164

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 167

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 170

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 173

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 176

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 178

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 180

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 202

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 206

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 224

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 225

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 227

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 321

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 321

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 321

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/includes/class.layout.php on line 321

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/admin/class.options.metapanel.php on line 56

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/admin/class.options.metapanel.php on line 56

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/admin/class.options.metapanel.php on line 56

Warning: Creating default object from empty value in /home/ibrfao/masteringapi.com/blog/wp-content/themes/platform/admin/class.options.metapanel.php on line 49
How To: Send An Application Request Using The Facebook Graph API | MasteringAPI

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
Back to top
 

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 top
 

Sending 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!

Back to top
 

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 top
 

Notes

  • We are storing the request id along with the “sender” id because we think this piece of information is useful for some applications
  • The outstanding field 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 date field 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

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

  • http://www.facebook.com/profile.php?id=636774153 Ivan Kurnosov

    What about adding screenshots to your articles?

    I think it would be better if we see the results of requests.

    • http://www.masteringapi.com Ibrahim Faour

      I’m adding screenshots and project sources when necessary. And for this particular article the screenshots will be identical to those in the FB documentation so I thought it’s not needed. Anyways, screenshots will come shortly ;-)

      • Alex

        Hi, I’m new to facebook api, but this article revealed some great info for me, thanks :)
        However, I might be wrong, but why should we store request and its sender id in database, when all info about request (request id, from id, to id) can be fetched from
        $facebook->api(“/$request_id?$app_token”);
        as described http://developers.facebook.com/docs/reference/dialogs/requests/

        • http://www.masteringapi.com Ibrahim Faour

           While you can only save the request id to your DB for later access, but how would you know from which user it was sent? looping over ALL the requests ids and call Facebook servers? your app won’t be responsive enough. So it’s ALWAYS a good idea to save as much info in your end and NOT contacting Facebook until necessary. Please have a read of the notes section again.

  • Ercaneraslan

    it is a very good article thanks but i am not good at php.
    i am using c# language and i want to do this for 2 days i couldnt figure out in c# there are no api that gives me the invitees

    if someone know how to get invited people’s ids in c# please mail me ercaneraslan@gmail.com or post here

  • Tomgolan3

    Seriously man this is awesome. I was referred here from a user at stackoverflow.
    Your code/blog posts shines. it was exactly what i was looking for and it works great.

    Just to see someone explain a facebook api code that make use of functions that must be so common for app builders is a rare sight.

    I bookmarked your website and i will definitely visit every day and take a look also at your archived posts.

    Benj, from Israel.

  • http://www.facebook.com/alkanulas Ulaş Volkan Alkan

    you are life saver man

  • http://www.facebook.com/people/Manoj-Aher/100001163024071 Manoj Aher

    Thanks Man, You saved my day.

  • http://www.facebook.com/profile.php?id=1394400187 Jonathan Tiret

    Thanks a lot! :-)

  • http://twitter.com/andyromero_ Andy Romero

    hi! how to save the names or emails of both , the user and the friend and session information? HELP!

  • http://www.facebook.com/bnieman Bill Nieman

    Brilliant! So easy now to track the round trip!

  • http://twitter.com/andyromero_ Andy Romero

    ok, but.. how we know if the uer invited acept our invitation?¿?¿?

  • http://www.facebook.com/people/Simon-Frntič/1056967679 Simon Frntič

    Super script, it made my application building a lot easyer. Thanks

  • Arun

    Good Tutorial… But I am getting alert message when I try to run this. alert(‘canceled’); What is the reason for this ???

    • http://www.masteringapi.com Ibrahim Faour

      Facebook has changed the way the request ids are sent. Tutorial will get updated soon!

    • cichy

      You must change “response.request_ids” to “response.to”.

      • Ibrahim Faour

        Code has been updated!

  • http://pulse.yahoo.com/_KBH5EZDPZ4EEP3R7S427YDOH5U Arun

    Can you pls let me know what had changed ? Will there be lot of changes… I m developing an app and need it urgently… pls…

  • Pvvijay256

    How to get request ids from request dialog using js sdk

  • http://www.facebook.com/people/Ryudo-Yamazaky/100002987634947 Ryudo Yamazaky

    hi, question:
    Why my facebook->getuser() alway returns the same id of the first user that i made tests??
    did i miss something ?  i just put the code as is here and replace the key and app in the proper places, at the time in my db i made 5 inserts and i made with 5 diferent accounts but as i said before the fb_user_id always is the same as the first test :( please heeeelpp!!

  • Jeff

    Great tut, 
    But I have a message saying : Uncaught exception ‘Exception’ with message ‘Facebook needs CURL PHP extension.
    So we put this CURL PHP extension on our hosting but we still have this message.
    Any idea ?
    Thanks.

  • http://www.facebook.com/vipulskulkarni Vipul Kulkarni

    Can we do the same for iOS graph api ?? I tried it by using dialog with key “app_request”. But after execution of code, only app request count in wall increases, notification is not received. Please advice ..

  • communication team

    The code works gr8. But after sending the app request, I redirect to next page. When I try to come back to app request page again(without refeshing) , I am not able to send app request again.  App request dialog doesnt pop up. So what my problem is that I am not able to send app request second time after going to different page. Does this anything to do with FB.init ??? If I refresh the page, I can send the request. Urgent !!! let me know if you know the solution.

  • Alessio Somma

    great tutorial! know I can learn something new.
    Only one question, how can I do the same with only the PHP-SDK (3.1.1)?I mean something about $fb->api(“/$uid/apprequests”, “post”, $params). do you know all the possible params this call can handle?

    thanks in advantage!

  • http://twitter.com/Vanss472 Vanessa Martinez

    Hi my is not working, i’m running it on my localhost (computer) any advice? when i click Send Application Request link it just jump to nothing. i add the app id and database everything i dont know what im missin out please reply thanks!

  • Guest

    Thanks, very useful post!

    line 43  if (response.request && response.to) {
    should be  if (response && response.request && response.to) {

    and also don’t forget to load jQuery :-)

    • Matsos

      how to load jQuery? Thanks

  • Obsidianmatotoka

    I had to edit the  function to that below, i changed the for loop to a known variable, you also can make it a 49 as this will only send out 50 invites each time it calls the send request method , i did this coz the line had an error on my side:

    $(‘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 && response.request && response.to) {
                    var request_ids = [];
                   
                    for(i=0; i<1; i++) {
                        var temp = response.request + '_' + response.to[i];
                        request_ids.push(temp);
                    }
                    var requests = request_ids.join(',');
                    $.post('handle_requests.php',{uid: ,
                    request_ids: requests},function(resp) {
                        // callback after storing the requests
                    });
                } else {
                    alert(‘canceled’);
                }
            });
            return false;
        }
        

    • Sopanith Meach

      Can u please show me a full working example? millions thanks, I am spending a lots of time working on this!

  • http://www.facebook.com/joe.arputhan Joe Arputhan

    awesome dude.., but just one question…i think it will be simple for u…
    how to get the name of a corresponding request id? is it possible to access it..can u help me?

  • Hoanhdotat

    I try it, but when click do nothing :(

  • Matsos

    when i click do nothing! i am working in localhost! in the field Send Application Request i have to change to change something?

  • Matsos

    when i click do nothing! i am working in localhost! in the field  a href=”#”>Send Application Request</a have to change to change something?
     

    • http://www.facebook.com/Almadana Diego Leandro Guerra Montenegr

      if you change the link for a button it will work properly

  • jupa

    It is not working for me at all.
    I get the following error
    Not FoundThe requested URL /” . $loginUrl . ” was not found on this server.I have been all day in this, please some advice.Thanks

  • DevXen

    Yeah it’s not working for me either. When i click ‘Send Application Request’ it just loads a # after the address. its not executing the code apparently.

  • Salman Ahmad

    Hi
    please check this here is a running script of facebook invite friend api with example..

    http://phpsollutions.blogspot.com/2014/02/facebook-invite-friends-api-in-php.html

  • Tharindu Sri Lanka

    There is a bug in this code. i fixed it. edit $.post comand as bellow. now it works well
    var requests = request_ids.join(‘,’);
    $req=request;
    $.post(‘handle_requests.php?uid=&request_ids=’+$req);

    • Tharindu Sri Lanka

      sorry. a mistake in line. here is correct line: $.post(‘handle_requests.php?uid=&request_ids=’+$req);