Although the Instant Games SDK provides player-specific data storage and Leaderboard storage, you may wish to store some information on your own web server — especially if building a Game Update via Messenger.
In this section, you will learn how to use the Instant Games SDK and the Messenger Bot platform for Instant Games to build and communicate with your backend infrastructure.
WARNING: Don't make Game Update via Messenger essential to your gameplay. Facebook Gaming allows players to opt into or out of these conversations.
Game Updates via Messenger can help you create re-engagement experiences. They are conversational bots, built on top of the Messenger Platform, that can interact with your players and invite them to return to your game in meaningful moments. You can use Game Updates to offer side quests, story modes, player progression updates, nudges, and more.
Whenever a player closes your game, your Game Updates via Messenger's server will receive a webhook notification that allows it to send a message directly to the player. Your updates can also offer a Play Game button that can be customized for the purpose of context choosing.
We have a sample app where you can try the code below. It allows you to save data to a backend service, as well as send payloads to and from the Game Updates via Messenger.
Download Communication Demo (.zip)The sample code contains two folders: client/ and server/. The server folder contains a sample Node.js application that you can either test in a local server or deploy to a cloud-based hosting solution. The client folder contains your Instant Game sample code with additional tooling to test and deploy it. Make sure to read the README.md files of both projects for detailed instructions on how to test and deploy.
When an Instant Game session ends and the user is opted into your Game Updates via Messenger a messaging_game_plays webhook event is sent. Game Updates via Messenger can also use the game_play button to allow direct access to the game.
From your game client, you can send data to your Game Updates via Messenger by using the FBInstant.setSessionData method:
FBInstant.setSessionData({
scoutSent:true,
scoutDurationInHours:24
});The object passed as a parameter to setSessionData will be available in the payload property of the game_play webhook. Here's how to retrieve the data in your Game Updates via Messenger (Node.js code example provided):
//
// Process game_play webhook
//
function receivedGameplay(event) {
// Messenger platform Page-Scope ID
var senderId = event.sender.id;
// FBInstant player id
var playerId = event.game_play.player_id;
// FBInstant context id
var contextId = event.game_play.context_id;
if (event.game_play.payload) {
// Get data from payload
var payload = JSON.parse(event.game_play.payload);
var scoutSent = payload['scoutSent'];
var scoutDurationInHours = payload['scoutDurationInHours'];
// Schedule sending message to player when scout returns.
if (scoutSent) {
Scheduler.after(scoutDurationInHours).hours().then(function(){
sendMessage(
senderId,
contextId,
'Your scout has come back with more intel. Want to find out more?',
'Get scout report!',
{deeplinkTo:'scout_screen'}
);
}
)}
}
}You can also check our sample code for a full working example. Note that the sample uses the Generic Template for sending a message to the player. You can check out the Messenger Platform docs for many other template examples that are also compatible with the Instant Games game_play button.
Note in the example above, that the update's game_play button sent more information that should be checked next time the game client gets opened.
To check from our game if the session is being started from this bot message, and access its payload, we need to use FBInstant.getEntryPointData. The example below shows how to perform this check upon game initialization.
FBInstant.initializeAsync().then(function(){
const entryPointData = FBInstant.getEntryPointData();
if (entryPointData) {
switch(entryPointData.deepLinkTo) {
case 'scout_screen':
game.loadAssetsFor(SCOUT_SCENE);
case 'daily_chest_dialog':
game.loadAssetsFor(DAILY_CHEST_SCENE);
// case...
default:
game.loadAssetsFor(START_MENU);
}
}
FBInstant.startGameAsync().then(function(){
game.start();
})
});Although webhooks provide one way to send data to your game, they will not be sent for users who have opted out of your Game Updates via Messenger. You can also use XMLHttpRequest or the fetch API to communicate with your game's server. In order to secure these communications, we provide the getSignedPlayerInfoAsync function, which allows you to verify that data sent to your server actually originates from the Instant Game.
FBInstant.player.getSignedPlayerInfoAsync('custom_payload_supplied_with_request')
.then(function (result) {
// The verification of the ID and signature should happen on server side.
SendToMyServer(
result.getPlayerID(), // same value as FBInstant.player.getID()
result.getSignature(),
... //any additional parameters required for your server call
);
});const CryptoJS = require('crypto-js');
var firstpart = signedRequest.split('.')[0];
firstpart = firstpart.replace(/-/g, '+').replace(/_/g, '/');
const signature = CryptoJS.enc.Base64.parse(firstpart).toString();
const dataHash = CryptoJS.HmacSHA256(signedRequest.split('.')[1], '<APP_SECRET>').toString();
var isValid = signature === dataHash;
const json = CryptoJS.enc.Base64.parse(signedRequest.split('.')[1]).toString(CryptoJS.enc.Utf8);
const data = JSON.parse(json);
console.log(isValid); // this will be true if the request is verified as coming from the game
console.log(data); // a JSON object as follows:
/*
{
algorithm: 'HMAC-SHA256',
issued_at: 1517294566,
player_id: '1114685845316172',
request_payload: 'custom_payload_supplied_with_request'
}
*/You cannot send messages to players who have not been explicitly opted-in to your Game Updates via Messenger, you only can send Game Updates via Messenger updates to opted-in users.
In the US and Canada, Game Updates via Messenger are opted-in by default for players that are highly engaged with your game. As part of this experience, if players opt out of your Game Updates via Messenger but remain highly engaged with your game, they will be prompted periodically to opt back in. Note that given the automated opt in nature in these locales, the subscribe API does not work for these locales.
Outside the US and Canada, you only can send messages to subscribed users. You must implement the subscribe API to subscribe new users to your Game Updates via Messenger.

Implement bots subscribe API:
Note: Players will only see the Game Updates via Messenger subscription dialog once every 90 days for a given game, but developers are not subject to that restriction on their own games.
var canSubscribeBot = false;
FBInstant.player.canSubscribeBotAsync().then(function (can_subscribe) {
canSubscribeBot = can_subscribe;
});
// Then when you want to ask the player to subscribe
if (canSubscribeBot) {
FBInstant.player.subscribeBotAsync().then(
// Player is subscribed to the bot
).catch(function (e) {
// Handle subscription failure
});
}FBInstant.player.canSubscribeBotAsync() will always return true if the player is a developer of the game.
Game Updates via Messenger can be a powerful retention mechanic when used effectively, but used poorly they can provide an annoying player experience and drive users away from your game. We provide the following guidelines to help you optimize your Game Updates via Messenger experience.
Name the Facebook Page associated with the Game Updates via Messenger the same as the game.bot the same as the game.
Set the default action to use game_play on game updates, so that the entire image takes you into the game.
Do not set messaging_type to any other value than RESPONSE or UPDATE.
Do not use the Messenger Platform's Broadcast API as it is currently not yet available for Game Updates via Messenger.
Provide relevant, timely and valuable updates to the players.
Triggers and frequency - complement your game loops:
Content
Landing experience:
Follow the general best practices for Messenger Bots.
Promotion:
Triggers and frequency:
Content:
For countries outside of the US and Canada, We've put together some tips about how to create and test opt-ins for your new players. We recommend that you test different variables and variations to find what works best for your audience.
A/B TEST WHEN TO PROMPT: Test different timing of when to show the prompt: players should see the prompt to opt-in to the game updates at a moment that makes sense within the flow of gameplay and you should test different moments to find the sweet spot. Examples:
A/B TEST THE VALUE MESSAGE: Make sure to convey clear value to set expectations for players when they subscribe to the game updates. Value of subscribing to updates should be clear to players before prompting them. Examples:
A/B TEST CUSTOM PROMPTS: Test surfacing a custom message to players prior to calling the API to part of your audience and show the standard dialogue to another part. When creating a custom prompt, make sure to seamlessly integrate the in-game message so it fits the look and feel of the game.
CONTEXTUALIZE THE PROMPT Surface the opt-in prompt such that it makes sense within the context of actions the player is taking. Examples:
REWARD PLAYERS WHO OPT-IN Provide players with a reward for subscribing to the bot that they can redeem through the call-to-action presented in the initial bot message.
AVOID INTERRUPTING PLAYERS Make sure the opt-in prompt does not interrupt an action the player is in the middle of trying to take. If interrupted, players will be more likely to decline the request without consideration.