Game Updates via Messenger and Server Communication

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.

Details

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.

Download Sample Code

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.

Communicating with your Game Updates via Messenger

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();
  })
});

Communicating with your custom backend

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.

In your 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
    );
   });

On your server (Node.js code example provided):

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'
}
*/

Game Updates via Messenger Opt-in flow

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:

  • canSubscribeBotAsync( )
  • subscribeBotAsync( )

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.

Guidelines

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.

Implementation and Set Up:

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.

Do:

Provide relevant, timely and valuable updates to the players.

Triggers and frequency - complement your game loops:

  • Time: e.g. Friday night / Long weekend / etc - Optimize time of day for message sends per user, being sensitive to timezones
  • Change of in-game progress: e.g. someone scored
  • Social network: e.g. a friend has joined
  • Programmatic: e.g. new daily reward unlocked
  • Frequency: Games with high retention tend to avoid sending more than 1-2 updates per day (this includes Game and Custom Updates, since to a user, it looks the same).

Content

  • Sending fresh and different content each day also helps maintain engagement. Make use of social updates like turn reminders, tournaments results, timed rewards and challenges.
  • Use Game Updates to announce new features or content.

Landing experience:

  • Make sure your players have the right incentives to open the game by using the message payload to reward them in-game with something valuable. A Game Update via Messenger is generally not effective if it opens your game to the start screen.
  • Use entry point data on play buttons to load the game in contextually relevant ways.

Do not:

Promotion:

  • Promote or advertise another game separate from the game the user is playing.
  • Link to any app store.

Triggers and frequency:

  • Send a Game Update immediately after the player closes the game. Spammy experiences can create churn for your players.
  • Continue to send a user Game Updates when they repeatedly do not engage. Policy limits will apply and block your update from being sent. Current limits are 5 updates over 10 days since the last game play session. When testing, make sure to play your game at least once every 5 updates.

Content:

  • Send Game Updates to re-engage the player with no context (e.g.: "Come back to the game now!"). Instead prefer re-engagement updates with rich context (e.g.: "Your scout has come back with more info")
  • Adopt the voice of other Facebook users or mislead players to believe their friends are communicating with them.

Best Practices for Game Updates via Messenger Opt-in

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:

  • Prompt part of your new audience as part of the tutorial/First-Time-User-Experience during a player's first session after they have experienced some of the gameplay.
  • Prompt part of your new audience immediately upon entering the game for the first time.
  • Prompt part of your new audience when more familiar with your game.

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:

  • Reminders about in-game tasks
  • Player progress updates
  • Leaderboard updates / resets
  • Social activity (new friend started playing, ask friend for help)
  • Game update-specific rewards (hints, boosts, coins)
  • Strategy tips
  • New content / game updates

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:

  • Daily Reward
  • Challenging a Friend
  • Places on a Leaderboard

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.