Facebook Instant Games extension for the Defold game engine.
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.
Before the extension can be used you need to add the Facebook Instant Games API to the index.html of your game. Refer to the index.html in the root of this project for an example of this.
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 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 API is designed to wrap version 6.2 of the Instant Games API.
The async API functions are Promise based in Javascript while the Lua counterparts are callback based.
The Facebook Instant Games platform is still evolving and new APIs are added by Facebook quite frequently. This means that there's likely parts of the API that isn't yet provided by this extension. Refer to the GitHub Issues tagged "Missing API" for a list of know missing APIs.
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
Initialize the Facebook Instant Games SDK.
PARAMETERS
callback
(function) - Function to call when the SDK is initialized
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Indicate that the game is ready to start.
PARAMETERS
callback
(function) - Function to call when the game has started
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Update 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 retrieved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Set a callback to be fired when a pause event is triggered.
PARAMETERS
callback
(function) - Function to call when the game has started
The callback
function is expected to accept the following values:
self
(userdata) - Script self reference
Quit the current game session.
Report the game's initial loading progress.
PARAMETERS
progress
(number) - A number between 0 and 100
Get information about the player.
RETURN
player
(table) - Player information
The player
table contains the following key-value pairs:
name
(string) - Player nameid
(string) - Player idphoto
(string) - URL to the player photolocale
(string) - Player locale
Fetch 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 players
The 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 an list of players that are connected to the current player.
PARAMETERS
callback
(function) - Function to call with the list of connected players
The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceplayers
(string) - JSON encoded array of connected player information
Each 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 name
Retrieve 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 retrieved
The 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 saved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Immediately flushes any changes to the player data to the designated cloud storage.
PARAMETERS
callback
(function) - Function to call when the data has been flushed
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Retrieve 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 retrieved
The 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 saved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Increment 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 increased
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencestats
(string) - JSON encoded key-value pairs with the incremented stats
Returns 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 bot
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Prompts 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 not
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Get 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) - 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 created
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)
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 made
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)
Get entry point data.
RETURN
data
(string) - The entry point data as a JSON string
Get 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 point
Set data associated with the session.
PARAMETERS
data
(string) - JSON encoded object containing session data
Get 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 context
Each entry in the players
table has the following values:
id
(string) - User idname
(string) - User namephoto
(string) - URL to a photo of the user
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".
Gets 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
if fbinstant.get_supported_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 created
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Prompts 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 not
Invoke 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 not
Log 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)
Preload an interstitial ad.
PARAMETERS
placement
(string) - The placement ID that's been setup in your Audience Network settingscallback
(function) - Function to call when the interstitial ad has loaded
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Present an interstitial ad.
PARAMETERS
placement
(string) - The placement ID that's been setup in your Audience Network settingscallback
(function) - Function to call when user finished watching the ad
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Preload a rewarded video.
PARAMETERS
placement
(string) - The placement ID that's been setup in your Audience Network settingscallback
(function) - Function to call when the rewarded video has loaded
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Present the rewarded video.
PARAMETERS
placement
(string) - The placement ID that's been setup in your Audience Network settingscallback
(function) - Function to call when user finished watching the ad
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Create a new activity store associated with the current context.
PARAMETERS
name
(string) - Name of the store to createcallback
(function) - Function to call when the store has been created
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencestore_id
(string) - Id of the created activity store
Close an activity store associated with the current context.
PARAMETERS
name
(string) - Name of the store to closecallback
(function) - Function to call when the store 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 not
Get data from an activity store in the current context.
PARAMETERS
store_name
(string) - Name of the store to get data fromkeys
(string) - JSON encoded array of keys to stored valuescallback
(function) - Function to call when the values have been retrieved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencedata
(string) - JSON encoded key-value pairs with the retrieved values
Get all activity stores in the current context.
PARAMETERS
callback
(function) - Function to call when the stores have been retrieved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencestores
(string) - JSON encoded array of activity stores
Each entry in stores
contains the following values:
id
(string) - Store idname
(string) - Store namestatus
(string) - Store status (STORE_*)context_id
(string) - Id of the context the store belongs to
Save data to an activity store in the current context.
PARAMETERS
store_name
(string) - Name of the store to save data todata
(string) - JSON encoded array of key-value pairs (note limitations on key and value length in official documentation).callback
(function) - Function to call when the data has been saved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencesuccess
(boolean) - Indicating if the operation was successful or not
Increment the data of an activity store in the current context.
PARAMETERS
store_name
(string) - Name of the store to increment data indata
(string) - JSON encoded array of key-value pairscallback
(function) - Function to call when the data has been saved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referencedata
(string) - JSON encoded table with the incremented data
Get information about a leaderboard.
PARAMETERS
name
(string) - Name of the leaderboard to getcallback
(function) - Function to call with leaderboard information
The 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 leaderboard
Updates 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) - Metadata to associate with the stored score. Must be less than 2KB in size.callback
(function) - Function to call when the score has been set
The 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 score
Retrieves 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 retrieved
The 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 score
Retrieves 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 retrieved
The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceentries
(string) - JSON encoded table of entries
Each 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 player
Sets a callback to be triggered when Payments operations are available.
PARAMETERS
callback
(function) - Function to call when Payments operations are available
The callback
function is expected to accept the following values:
self
(userdata) - Script self reference
Fetches the game's product catalog.
PARAMETERS
callback
(function) - Function to call with the set of products that are registered to the game
The callback
function is expected to accept the following values:
self
(userdata) - Script self referenceproducts
(table) - The products
Each 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 product
Fetches 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 game
The 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 game
Each 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 product descriptionpurchase_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 request
Begins 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 fromfbinstant.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 not
fbinstant.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
The original Tic Tac Toe example made in Phaser has been recreated in Defold to show how the API is supposed to be user. Refer to the tictactoe folder for the example.
The example has support for two different backends:
- Activity Store - This stores the game state using the Facebook Instant Games Activity Store API (2018-04-16: activity stores are currently disabled). Change
game.gui_script
so that it requirestictactoe.game.data.activity_store
to use this solution. - Node.js server - This stores the game state in a simple Node.js backend and a Postgres database. This is what the official Facebook Instant Games Tic Tac Toe example uses. The server code, created by a Facebook engineer, is located in the
tictactoe-server
folder. It's quite easy to get the server up an running on Heroku. Changegame.gui_script
so that it requirestictactoe.game.data.heroku
to use this solution.