Instant Games is a new way for people to play games across Facebook platforms. Powered by HTML5 technology, it allows people to find and play games directly in the News Feed or Messenger conversations, on both desktops and mobile devices. This extension provides an integration with the Facebook Instant Games API. The extension currently supports version 6.3 of the Facebook Instant Games API.
You can use the extension in your own project by adding this project as a Defold library dependency. Open your game.project file and in the dependencies field under project add:
https://github.com/defold/extension-fbinstant/archive/master.zip
Or point to the ZIP file of a specific release.
Configure your game.project
HTML5 section according to the manual.
Facebook Instant Games can show the progress while the game is loaded. It is quite easy to set this up for a Defold game. All that is required is to override the Progress.updateProgress() function and pass along the value to the Instant Games API (this is done for you in the default index.html provided with this extension):
// Set up a progress listener and feed progress to FBInstant
Progress.updateProgress = function (percentage, text) {
FBInstant.setLoadingProgress(percentage);
}
It has been observed that the progress updates do not work properly on Android. The progress stays at 0 and immediately jumps to 100 when the game has finished loaded. This seems to be caused by the Instant Games API not being initialized until after the game has loaded. In order to avoid this it is recommended to initialize the Instant Games API and flag this to the extension (this is done for you in the default index.html provided with this extension):
// Do early initialization of FBInstant
// This is required to be able to properly update the loading
// progress above.
FBInstant.initializeAsync().then(function() {
// This will be checked by the FBInstant Defold extension
Module._fbinstant_inited = true;
});
You also need to create a Facebook App in the Facebook App Dashboard where Instant Games is enabled. Please refer to the Getting Started documentation on the Instant Games page for further instructions.
You can include an fbapp-config.json
configuration file in the application bundle that you publish. The file is put in the root directory of your bundle to specify settings for your application. These settings will apply to all users who the bundle is served to. This enables you to launch different bundles along with different application settings to different audiences. Read more about the format here.
Defold can automatically include this file in the HTML5 bundle using the Bundle Resources setting in game.project
. Create a folder in your project to hold the configuration file:
/my_bundle_resources/web/fbapp-config.json
And set my_bundle_resources
as the value in the Bundle Resources field in game.project
.
The extension wraps the Instant Games Javascript API in a Lua interface. The Instant Games extension is accessible through the fbinstant.*
namespace where it wraps the Javascript SDK in a Lua API. The extension provides an almost 1 to 1 mapping between the Javascript SDK and the Lua API.
For example, consider this Javascript code:
FBInstant.initializeAsync().then(function() {
FBInstant.startGameAsync().then(function() {
var playerID = FBInstant.player.getID();
var playerName = FBInstant.player.getName();
});
});
The corresponding Lua code looks like this:
fbinstant.initialize(function(self, success)
fbinstant.start_game(function(self, success)
local player_id = fbinstant.get_player().id
local player_name = fbinstant.get_player().name
end)
end)
The async API functions are Promise based in Javascript while the Lua counterparts are callback based.
The LiveUpdate functionality of Defold can be combined with Facebook Instant Games to create really small application bundles where additional content can be downloaded while the player is progressing through game. Combine the excluded content with the application bundle in a single zip file when uploading to the web hosting provided by Facebook Instant Games. When loading the excluded content you’re required to load the content from the same base URL as the rest of the game is loaded from. There is a helper module that will get the base URL from the browser:
local baseurl = require "fbinstant.baseurl"
local missing_resources = collectionproxy.missing_resources("#level3")
for _,resource in ipairs(missing_resources) do
local id = http.request(baseurl.get() .. resource, "GET", callback)
end
The Facebook Instant Games best practices recommends an initial loading time less than 5 seconds. Defold adds little overhead to your games and provide a number of tools allowing you to reduce the size of your game:
This functionality is still in an alpha state and needs further documentation. Tools for generating app.manifests file can be found here: https://forum.defold.com/t/stripping-appmanifest-maker/16059
This process of excluding parts of the game content, storing it on a server and then downloading and caching it while the game is running is perfect for reducing the application size of an Instant Game. The entire process is handled by Defold’s Live Update system.
The source code is available on GitHub
A bare bones “game” with code to initialize and end a Facebook Instant game session can be found in the examples/balls folder
A Tic Tac Toe game is available in a separate repository.
An example project with all APIs implemented can be found in the examples/apis folder
Initialize the Facebook Instant Games SDK.
PARAMETERS
callback
(function) - Function to call when the SDK is initializedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notIndicate that the game is ready to start.
PARAMETERS
callback
(function) - Function to call when the game has startedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notRequest that the client switch to a different Instant Game. The API will reject if the switch fails - else, the client will load the new game
PARAMETERS
app_id
(string) - The Application ID of the Instant Game to switch to.data
(string) - Optional JSON encoded object containing entrypoint data for the game being switched to.callback
(function) - Function to call if the switch failsThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notUpdate the game session.
PARAMETERS
data
(string) - JSON encoded object containing game information (refer to the CustomUpdatePayload object of the Javascript API)callback
(function) - Function to call when the value has been retrievedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notSet a callback to be fired when a pause event is triggered.
PARAMETERS
callback
(function) - Function to call when the game has startedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceQuit the current game session.
Report the game’s initial loading progress.
PARAMETERS
progress
(number) - A number between 0 and 100Get information about the player.
RETURN
player
(table) - Player informationThe player
table contains the following key-value pairs:
name
(string) - Player nameid
(string) - Player idphoto
(string) - URL to the player photolocale
(string) - Player localeFetch the player’s unique identifier along with a signature that verifies that the identifier indeed comes from Facebook without being tampered with.
PARAMETERS
payload
(string) - A developer-specified payload to include in the signed response.callback
(function) - Function to call with the list of connected playersThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesignature
(string) - A signature to verify this object indeed comes from Facebook.Get a list of players that are connected to the current player.
PARAMETERS
callback
(function) - Function to call with the list of connected playersThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceplayers
(string) - JSON encoded array of connected player informationEach entry in the players
array represents a player with these properties:
id
(string) - Id of the connected playerphoto
(string) - The player’s public profile photoname
(string) - The player’s full nameRetrieve data from the designated cloud storage of the current player.
PARAMETERS
keys
(string) - An array of unique keys to retrieve data for.callback
(function) - Function to call when the data has been retrievedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencedata
(string) - JSON encoded key-value pair map containing the requested data.Set data to be saved to the designated cloud storage of the current player.
PARAMETERS
data
(string) - JSON encoded key-value pairs containing player datacallback
(function) - Function to call when the data has been savedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notImmediately flushes any changes to the player data to the designated cloud storage.
PARAMETERS
callback
(function) - Function to call when the data has been flushedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notRetrieve stats from the designated cloud storage of the current player.
PARAMETERS
stats
(string) - Optional JSON encoded array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats.callback
(function) - Function to call when the stat has been retrievedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencestats
(string) - JSON encoded key-value pair map containing the requested stats.Set stats to be saved to the designated cloud storage of the current player.
PARAMETERS
stats
(string) - JSON encoded key-value pairs containing player statscallback
(function) - Function to call when the stat have been savedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notIncrement stats saved in the designated cloud storage of the current player.
PARAMETERS
increments
(string) - JSON encoded key-value pairs indicating how much to increment each stat.callback
(function) - Function to call when the stats have been increasedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencestats
(string) - JSON encoded key-value pairs with the incremented statsReturns whether or not the player is eligible to subscribe to the associated chat bot.
PARAMETERS
callback
(function) - Function to call if player can be subscribed to botThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notPrompts the player to subscribe to the chat bot. Player will only be able to see this bot subscription dialog once for a specific game.
PARAMETERS
callback
(function) - Function to call to decide what to do if the player was subscribed or notThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notGet the current context.
RETURN
id
(string) - The context id, or nil if none existstype
(string) - The context type, or nil if none exists (see fbinstant.CONTEXT_* constants)Opens a context selection dialog for the player.
PARAMETERS
options (string |
nil) - OPTIONAL! JSON encoded object containing options (refer to the documentation for chooseAsync) |
callback
(function) - Function to call when a context has been selected. It is now possible to call get_context() to get the context.The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceid
(string) - The context id, or nil if none existstype
(string) - The context type, or nil if none exists (see fbinstant.CONTEXT_* constants)Attempts to create or switch into a context between a specified player and the current player.
PARAMETERS
player_id
(string) - ID of the playercallback
(function) - Function to call when the context has been createdThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceid
(string) - The context id, or nil if none existstype
(string) - The context type, or nil if none exists (see fbinstant.CONTEXT_* constants)Request a switch into a specific context.
PARAMETERS
context_id
(string) - ID of the contextcallback
(function) - Function to call when when the switch has been madeThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceid
(string) - The context id, or nil if none existstype
(string) - The context type, or nil if none exists (see fbinstant.CONTEXT_* constants)Get entry point data.
RETURN
data
(string) - The entry point data as a JSON stringGet the entry point that the game was launched from.
PARAMETERS
callback
(function) - Function to call when the entry point has been received.The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceentry_point
(string) - The entry pointSet data associated with the session.
PARAMETERS
data
(string) - JSON encoded object containing session dataGet the players in the current context.
PARAMETERS
callback
(function) - Function to call when the players have been received.The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceplayers
(table) - Table with players in the contextEach entry in the players
table has the following values:
id
(string) - User idname
(string) - User namephoto
(string) - URL to a photo of the userPosts the player’s best score for the session to Facebook.
PARAMETERS
score
(number) - An integer value representing the player’s best score in a session.Get the players in the current context.
Gets the active platform the game is running on.
RETURN
platform
(string) - The current platform one of “IOS” or “ANDROID” or “WEB” or “MOBILE_WEB”.The current locale. See https://origincache.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. Use this to determine what languages the current game should be localized with. The value will not be accurate until FBInstant.startGameAsync() resolves.
RETURN
locale
(string) - The localeGets a list of supported apis by the current platform.
Check this list before attempting to use features which don’t yet work on all platforms such as ads. Refer to the SDK documentation for a complete list of APIs: https://developers.facebook.com/docs/games/instant-games/sdk
RETURN
apis
(string) - JSON encoded string with a key value mapping of supported APIs.EXAMPLE
local apis_json = fbinstant.get_supported_apis()
local apis = json.decode(apis_json)
if apis["getInterstitialAdAsync"] then
-- load/show interstitial
end
Gets the current SDK version. Can be used as a sanity check.
RETURN
version
(string) - Example “6.1”Returns whether or not the user is eligible to have shortcut creation requested.
Will return false if createShortcutAsync was already called this session or the user is ineligible for shortcut creation.
Currently only a feature on Android for adding a shortcut to the home screen.
PARAMETERS
callback
(function) - Function to call if shortcut can be createdThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notPrompts the user to create a shortcut to the game if they are eligible to. For now, only for adding a shortcut to the Android home screen. Can only be called once per session.
PARAMETERS
callback
(function) - Function to call to decide what to do if a shortcut was or wasn’t created (such as storing data to ask again sometime in the future)The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notInvoke a share dialog.
PARAMETERS
payload
(string) - JSON encoded share payload (refer to the SharePayload object from the Javascript API)callback
(function) - Function to call when the share dialog has been closed.The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or notLog an app event with FB Analytics.
PARAMETERS
event_name
(string) - Name of the event (refer to the Javascript API for event name limitations)value_to_sum
(number) - An numeric value that FB Analytics can calculate a sum with.parameters
(string) - JSON encoded object of key value pairs (refer to the Javascript API for parameter limitations)Displaying an ad is a three step process:
Get an interstitial ad instance.
PARAMETERS
placement
(string) - The placement ID that’s been setup in your Audience Network settingscallback
(function) - Function to call when the interstitial ad has been createdThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencead_id
(string) - Id of the ad instanceerror
(string) - Error code if something went wrongPreload an interstitial ad.
PARAMETERS
ad_id
(string) - Id of the ad instance to preloadcallback
(function) - Function to call when the interstitial ad has loadedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or noterror
(string) - Error code if something went wrongPresent an interstitial ad.
PARAMETERS
ad_id
(string) - Id of the ad instance to showcallback
(function) - Function to call when user finished watching the adThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or noterror
(string) - Error code if something went wrongGet a rewarded video instance.
PARAMETERS
placement
(string) - The placement ID that’s been setup in your Audience Network settingscallback
(function) - Function to call when the rewarded video has loadedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencead_id
(boolean) - Id of the crated ad instanceerror
(string) - Error code if something went wrongPreload a rewarded video.
PARAMETERS
ad_id
(string) - Id of the ad instance to preloadcallback
(function) - Function to call when the rewarded video has loadedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or noterror
(string) - Error code if something went wrongPresent the rewarded video.
PARAMETERS
placement
(string) - Id of the ad instance to showcallback
(function) - Function to call when user finished watching the adThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or noterror
(string) - Error code if something went wrongGet information about a leaderboard.
PARAMETERS
name
(string) - Name of the leaderboard to getcallback
(function) - Function to call with leaderboard informationThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencecontext_id
(string) - The ID of the context that the leaderboard is associated with, or nil if the leaderboard is not tied to a particular contextentry_count
(number) - The total number of player entries in the leaderboardUpdates the player’s score. If the player has an existing score, the old score will only be replaced if the new score is better than it. NOTE: If the leaderboard is associated with a specific context, the game must be in that context to set a score for the player.
PARAMETERS
name
(string) - Name of the leaderboard to set score inscore
(number) - The new score for the player. Must be a 64-bit integer number.extra_data (string |
nil) - Metadata to associate with the stored score. Must be less than 2KB in size. |
callback
(function) - Function to call when the score has been setThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencescore
(number) - The current score for the playerextra_data
(string) - Metadata to associate with the stored scoreRetrieves the leaderboard’s entry for the current player.
PARAMETERS
name
(string) - Name of the leaderboard to get score fromcallback
(function) - Function to call when the score has been retrievedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencerank
(number) - The current rank of the playerscore
(number) - The current score for the playerextra_data
(string) - Metadata to associate with the stored scoreRetrieves a set of leaderboard entries, ordered by score ranking in the leaderboard.
PARAMETERS
name
(string) - Name of the leaderboard to get entries fromcount
(number) - The number of entries to attempt to fetch from the leaderboardoffset
(number) - The offset from the top of the leaderboard that entries will be fetched fromcallback
(function) - Function to call when the entries have been retrievedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceentries
(string) - JSON encoded table of entriesEach entry in entries
contains:
rank
(number) - The rank of the player’s score in the leaderboardscore
(number) - The score associated with the entryformatted_score
(string) - The score associated with the entry, formatted with the score format associated with the leaderboardtimestamp
(number) - The timestamp of when the leaderboard entry was last updatedextra_data
(string) - The developer-specified payload associated with the scoreplayer_name
(string) - The player’s localized display nameplayer_photo
(string) - The url to the player’s public profile photoplayer_id
(number) - The game’s unique identifier for the playerRetrieves the leaderboard score entries of the current player’s connected players (including the current player), ordered by local rank within the set of connected players.
PARAMETERS
name
(string) - Name of the leaderboard to get entries fromcount
(number) - The number of entries to attempt to fetch from the leaderboardoffset
(number) - The offset from the top of the leaderboard that entries will be fetched fromcallback
(function) - Function to call when the entries have been retrievedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceentries
(string) - JSON encoded table of entriesEach entry in entries
contains:
rank
(number) - The rank of the player’s score in the leaderboardscore
(number) - The score associated with the entryformatted_score
(string) - The score associated with the entry, formatted with the score format associated with the leaderboardtimestamp
(number) - The timestamp of when the leaderboard entry was last updatedextra_data
(string) - The developer-specified payload associated with the scoreplayer_name
(string) - The player’s localized display nameplayer_photo
(string) - The url to the player’s public profile photoplayer_id
(number) - The game’s unique identifier for the playerSets a callback to be triggered when Payments operations are available.
PARAMETERS
callback
(function) - Function to call when Payments operations are availableThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceFetches the game’s product catalog.
PARAMETERS
callback
(function) - Function to call with the set of products that are registered to the gameThe callback
function is expected to accept the following values:
self
(userdata) - Script self referenceproducts
(table) - The productsEach entry in products
contains:
title
(string) - The title of the productproduct_id
(string) - The product’s game-specified identifierdescription
(string) - The product descriptionimage_uri
(string) - A link to the product’s associated imageprice
(string) - The price of the productprice_currency_code
(string) - The currency code for the productFetches all of the player’s unconsumed purchases. As a best practice, the game should fetch the current player’s purchases as soon as the client indicates that it is ready to perform payments-related operations. The game can then process and consume any purchases that are waiting to be consumed.
PARAMETERS
callback
(function) - Function to call with the set of purchases that the player has made for the gameThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencepurchases
(table) - The set of purchases that the player has made for the gameEach entry in purchases
contains:
developer_payload
(string) - A developer-specified string, provided during the purchase of the productpayment_id
(string) - The identifier for the purchase transactionproduct_id
(string) - The identifier of the purchased productpurchase_time
(string) - Unix timestamp of when the purchase occurredpurchase_token
(string) - A token representing the purchase that may be used to consume the purchasesigned_request
(string) - Server-signed encoding of the purchase requestBegins the purchase flow for a specific product. Will fail if called before FBInstant.startGameAsync() has finished.
PARAMETERS
product_id
(string) - The identifier of the product to purchasedeveloper_payload
(string) - n optional developer-specified payload, to be included in the returned purchase’s signed requestcallback
(function) - Function to call when the product is successfully purchased by the player.The callback
function is expected to accept the following values:
self
(userdata) - Script self referencepurchase
(table) - Information about the purchase, same data as an entry returned from fbinstant.get_purchases()
Consumes a specific purchase belonging to the current player. Before provisioning a product’s effects to the player, the game should request the consumption of the purchased product. Once the purchase is successfully consumed, the game should immediately provide the player with the effects of their purchase.
PARAMETERS
purchase_token
(string) - The purchase token of the purchase that should be consumedcallback
(function) - Function to call when the purchase has been consumed successfully.The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Boolean indicating if the purchase was successfully consumed or notChecks if the current player is eligible for the matchPlayerAsync API.
PARAMETERS
callback
(function) - Function to call when the check has completedThe callback
function is expected to accept the following values:
self
(userdata) - Script self referencecan_match
(boolean) - true if the player is eligible to match with other players and false otherwiseerror
(string) - Error code if something went wrongAttempts to match the current player with other users looking for people to play with.
PARAMETERS
match_tag
(string) - Optional extra information about the player used to group them with similar playersswitch_context_when_matched
(boolean) - Optional extra parameter that specifies whether the player should be immediately switched to the new context when a match is foundoffline_match
(boolean) - Optional extra parameter that specifies whether to start a match asynchronously.callback
(function) - Function to call when the player has been added to a group thread and switched into the thread’s context.The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceerror
(string) - Error code if something went wrongfbinstant.get_context().type
fbinstant.get_context().type
fbinstant.get_context().type
fbinstant.get_context().type
For fbinstant.share() payload table
For fbinstant.share() payload table
For fbinstant.share() payload table
For fbinstant.share() payload table
For fbinstant.choose_context() options table
For fbinstant.choose_context() options table
For fbinstant.choose_context() options table
For fbinstant.get_stores() activity store status
For fbinstant.get_stores() activity store status
Did you spot an error or do you have a suggestion? Please let us know on GitHub!
GITHUB