This tutorial shows you how to use the Facebook Requests Dialog to let players invite their friends to join Friend Smash. Invites from friends are one of the primary ways that games can generate organic traffic and acquire new players. Now that you have implemented authentication and personalization, you can take the next step and add invites to Friend Smash.
This guide will walk through these steps:
Requests are one of Facebook's primary social channels, used for direct 1-to-1 communication between players. See Getting Started - Requests to learn more about the request experience. Otherwise, let's implement requests to let people challenge their friends in Friend Smash.
Since you implemented our Facebook enabled front menu in the personalization section of this guide, there is a 'Challenge' button on the title screen. Clicking this button executes the sendChallenge() method inside the ui.js file.
The method is currently empty. Add this code to let players send requests by spawning the Requests Dialog through the Facebook SDK for JavaScript.
if (gScore) {
FB.ui({method: 'apprequests',
title: 'Friend Smash Challenge!',
message: 'I just smashed ' + gScore + ' friends! Can you beat it?',
}, fbCallback);
} else {
FB.ui({method: 'apprequests',
title: 'Play Friend Smash with me!',
message: 'Friend Smash is smashing! Check it out.',
}, fbCallback);
}
Our sendChallenge() function implements FB.ui which allows us to display any of the Facebook Dialogs on top of our app.
In this example, you are popping-up the Requests Dialog by specifying the method property 'apprequests'.
Next enter in the titles of our request and the message that will customize how the request displays to the player's friends. Notice that there's a choice to display one of two messages in the dialog. If the player has already completed a game, they will have populated the gScore variable with their latest score, you can use that achievement as a challenge to their friends. Otherwise, simply populate the dialog with a generic message inviting friends to join them in the game.
Next, you need to implement a callback function so that our app can process any actions the player took within the dialog. FB.ui will invoke the callback method provided when the player has finished interacting with a dialog. It will send to the callback function details on any actions completed by the player, such as successfully sending a request, or cancelling.
At the bottom of the ui.js file, paste the following code:
function fbCallback(response) {
console.log(response);
}
You'll notice that all that's happening is getting the response object and then outputting this in the debug console. For a production app you may want to inspect the response object and take further action depending on the player's state, but in this case, just take a look at what the object looks like.
If the player sent a request you will see something similar to (Chrome's debug console):

If the player canceled the Dialog response will be undefined.

The previous code is very simple, but is somewhat limited in what it can achieve. You can pass other parameters in the 'params' dictionary to customize the Requests Dialog's behavior. Let's run through a few specific examples now.
For a full list of the parameters available check out our full documentation for the Requests Dialog, Dialog API and FB.ui.
FB.ui({method: 'apprequests',
title: 'Friend Smash Challenge!',
to: gFriendID,
message: 'I just smashed ' + gScore + ' friends! Can you beat it?',
}, fbCallback);
If you provide a parameter with the key 'to' and the value as a specific player's Facebook ID, the request dialog will be fixed to prompt the player to send a request to that player only. They won't be able to add more friends or remove the 'to' suggested friend.
This use-case is appropriate when you're implementing a turn-based game and you need to alert the other player that it's their turn. In this scenario, you want the request to go to the specified player.

FB.ui({method: 'apprequests',
title: 'Friend Smash Challenge!',
message: 'I just smashed ' + gScore + ' friends! Can you beat it?',
filters: [{name: 'Suggested', user_ids: ["685145706", "605665581", "596824621"]}]
}, fbCallback);
This example passes in an extra parameter with the key 'filters'. The value is an array of tuples which define different lists, or filters, of friends. In this example, the array contains only one entry, a 'Suggested' list, which is coupled with an array contained three Facebook IDs. This creates a list of suggested friends, who appear first, in order of your specification in the dialog.
This is useful if you want the player to be able to pick friends to send a request to, but you have suggestions based on the context of the game. Perhaps the suggested players are people recently interacted with inside the game, or friends you know the player interacts with frequently. This is a best-practice, as it removes the requirement for the player to scroll through lots of friends looking for specific people.

var challengeData = {"challenge_score" : gScore};
FB.ui({method: 'apprequests',
title: 'Friend Smash Challenge!',
message: 'I just smashed ' + gScore + ' friends! Can you beat it?',
data: challengeData
}, fbCallback);
Finally, you can bundle more data with the request using the 'data' parameter. Here, you created a simple JSON challengeData dictionary that contains the player's last score. This becomes the target score of the challenge for the receiving player. You pass it into the FB.ui call with the key 'data', and the JSON object is stored with the request on Facebook. Then, when a person receives a request with data attached, the app can poll Facebook using the request's unique ID to provide the additional data. This will be covered in detail later in this tutorial, when an incoming request is handled.
Note: It is not necessary to explicitly give details about where a request originated. Facebook handles this for you and makes it available when handling the incoming request.
We touched on a scenario where players exchange requests back and forth. If this scenario is typical in your game, it can be a bad experience to force them through the request dialog every time they want to send a request. The solution for this is frictionless requests.
Frictionless requests let players send requests to friends from an app without having to click on a pop-up confirmation dialog. When sending a request to a friend, a player can authorize the app to send subsequent requests to the same friend without another dialog. This streamlines the process of sharing with friends.
To turn on frictionless requests with the Javascript SDK, return to the FB.init that you previously implemented inside index.php. The following parameter needs to be added to the call: frictionlessRequests: true
The full call should therefore end up looking like this:
// Initialize the JS SDK
FB.init({
appId: appId,
frictionlessRequests: true,
cookie: true,
});
Refresh the application and try to send another request. You'll now see the extra checkbox in the request dialog. The behavior for managing frictionless requests is entirely handled by the Facebook SDK. Add this extra line of code and the rest is taken care of for you.

We've looked at the various methods you can use to send requests, now let's look at receiving them.
When a player clicks on a request on Facebook.com and is redirected to your game, it's possible to process the incoming link to provide a contextual experience. Previously, you sent a request with an additional data parameter containing the score of the challenging player. Now, let's add code to Friend Smash to process that incoming request, obtain the data that was sent and do something with the score.
An incoming link from a request looks something like this:
http://apps.facebook.com/friendsmashsampledev/?fb_source=notification&request_ids=324663694317526&ref=notif&app_request_type=user_to_user¬if_t=app_request
Notice that within the url there is a parameter named 'app_request_type' with a value of 'user_to_user'. This is specific and unique to requests, so you can look for this token within our incoming url string. Let's add code to do that now.
Head back to the createMenu() function inside the ui.js file. Scroll to the section where you query the Facebook Javascript SDK for the player's login status. Here, if the person is connected as expected, call a function named processIncomingRequest, which you'll will implement to parse the incoming URL. If that function successfully finds a request token in the URL, it will query Facebook for additional data about the request. If that data comes back successfully, you can launch straight into a game making our challenging player the subject of the smashing, and their last score as our target score. However, if you don't find any request token in the URL, it means the games hasn't launched from a request and should display the front menu as normal. Therefore, return a boolean from our new processIncomingRequest function, to indicate if Friend Smash were able to successfully launch into a game. Alter the FB.getLoginStatus block to look like so:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
gPlayerFBID = response.authResponse.userID;
if (!processIncomingRequest()) {
welcomePlayer(gPlayerFBID);
showScores();
}
}
});
Next, implement the processIncomingRequest function. Scroll to the bottom of ui.js and add the following function:
function processIncomingRequest() {
var startedGame = false;
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
var requestType = urlParams["app_request_type"];
if (requestType == "user_to_user") {
var requestID = urlParams["request_ids"];
FB.api(requestID, function(response) {
var gChallengerID = response.from.id;
var gChallengerName = response.from.name.split(" ")[0];
startGame(gChallengerID, gChallengerName);
startedGame = true;
});
}
return startedGame;
}
This method looks rather complex, but is actually fairly straightforward. First, define a quick helper function which contains a regular expression which will be used to pull out the various extra parameters attached to the incoming url. Then, you can query the urlParams for the parameter app_request_type equaling user_to_user. If found, you know that the game launched from a request. You can then extract the request_ids and create an HTTP GET request to the Open Graph using the Facebook SDK convenience method FB.api. You are requesting from the path https://graph.facebook.com/REQUEST_ID. Assuming the Request ID and User Access Token (sent implicitly) are valid, Facebook will return an object which looks like this:

In the callback function for this request, parse the incoming response to extract the challenger's name and Facebook ID. As you can see, this is simply a case of pulling them out of the data array that was returned by Facebook. As you can see, the result also contains the data parameter originally bundled with the request. Now have all the information needed to start a new game with the challenging player as the smash target, and with the challenge score as the score target.
You've successfully implemented requests, which will allow us to grow Friend Smash organically by allowing players to invite their friends to play the game. Now, let's use the feed channel to implement bragging.