# SDK Reference


This page provides a comprehensive overview of the **Facebook Instant Games SDK**

## Loading the SDK

Include the Instant Games SDK in your game's HTML file using the following script tag:

```html
<script src="https://connect.facebook.net/en_US/fbinstant.8.0.js"></script>
```

The SDK is loaded from Facebook's CDN and must be included before your game code executes. Once loaded, you access the SDK globally as `FBInstant`.

### SDK versioning

The Instant Games SDK is versioned. The version number appears in the script URL (e.g., `fbinstant.8.0.js` is version 8.0). Each version is stable and will not receive breaking changes. When a new version is released, you can upgrade at your own pace by updating the script URL.

**Recommendations:**

- **Pin to a specific version** in your production builds for stability. Do not use an unversioned or "latest" URL.
- **Test thoroughly** before upgrading to a new SDK version, even for minor version bumps.
- **Check the changelog** (available in the [App Dashboard](https://developers.facebook.com/apps/)) when upgrading to understand what has changed.

The current recommended SDK version is **8.0**.

### Checking the SDK version at runtime

```javascript
const sdkVersion = FBInstant.getSDKVersion();
console.log('SDK Version:', sdkVersion); // e.g., "7.1"
```

## API overview

The SDK is organized into several namespaces, each covering a distinct area of functionality. The sections below list the key methods and properties in each namespace along with a brief description of what they do.

---

## FBInstant (Core)

The root `FBInstant` namespace contains methods for initializing your game, managing the loading screen, and controlling the game.

| Method | Description |
|--------|-------------|
| `FBInstant.initializeAsync()` | Initializes the SDK. Must be called before any other SDK methods. Returns a `Promise` that resolves when initialization is complete. |
| `FBInstant.startGameAsync()` | Signals to the platform that the game is ready to be displayed. Call this after your game assets have loaded. Hides the loading screen and shows the game. Returns a `Promise`. |
| `FBInstant.setLoadingProgress(percentage)` | Updates the loading progress bar shown to the player during initialization. `percentage` is a number between 0 and 100. Call this between `initializeAsync()` and `startGameAsync()`. |
| `FBInstant.quit()` | Quits the game and returns the player to the Facebook surface they came from. |
| `FBInstant.updateAsync(payload)` | Sends a custom update to the current game context (e.g., sends a message to the Messenger thread or Room where the game is being played). Returns a `Promise`. |
| `FBInstant.inviteAsync(payload)` | Opens a dialog that lets the player invite one or more people to the game. Returns a `Promise`. |
| `FBInstant.shareAsync(payload)` | Opens a share dialog that lets the player share game content to their Facebook feed or Messenger conversations. Returns a `Promise`. |
| `FBInstant.switchGameAsync(appID, data)` | Switches to a different Instant Game. Returns a `Promise`. If successful, the current game will be terminated. |
| `FBInstant.canCreateShortcutAsync()` | Checks whether the player can add a shortcut to the game on their home screen. Returns a `Promise<boolean>`. |
| `FBInstant.createShortcutAsync()` | Prompts the player to add a home screen shortcut. Returns a `Promise`. |
| `FBInstant.logEvent(eventName, valueToSum, parameters)` | Logs a custom analytics event. Use this to track game-specific events and metrics. |
| `FBInstant.onPause(callback)` | Registers a callback that fires when the game is paused (e.g., the player switches to another app or tab). |
| `FBInstant.getSDKVersion()` | Returns the version string of the currently loaded SDK (e.g., `"7.1"`). |
| `FBInstant.getSupportedAPIs()` | Returns an array of API method names supported on the current platform and device. Use this to check for feature availability before calling optional APIs. |
| `FBInstant.getLocale()` | Returns the player's locale string (e.g., `"en_US"`, `"ja_JP"`). Use this for localization. |
| `FBInstant.getPlatform()` | Returns the platform the game is running on: `"IOS"`, `"ANDROID"`, or `"WEB"`. |
| `FBInstant.getEntryPointData()` | Returns the data object associated with the entry point from which the player launched the game (e.g., data from a custom update or ad). May return `null`. |
| `FBInstant.getEntryPointAsync()` | Returns a `Promise<string>` with the entry point from which the game was launched (e.g., `"feed"`, `"game_search"`, `"notification"`). |
| `FBInstant.setSessionData(data)` | Sets session-level data associated with this game session. This data is included in any game updates sent during the session. |
| `FBInstant.performHapticFeedbackAsync()` | Triggers haptic feedback (vibration) on supported devices. Returns a `Promise`. See [Haptic Feedback](https://developers.facebook.com/documentation/games/build/haptic-feedback). |

### Lifecycle flow

The typical lifecycle of an Instant Game follows this sequence:

```
1. SDK script loads
2. FBInstant.initializeAsync()     --> SDK initializes
3. Load game assets                --> Your loading logic
4. FBInstant.setLoadingProgress()  --> Update progress bar
5. FBInstant.startGameAsync()      --> Game becomes visible
6. Gameplay begins
7. FBInstant.quit()                --> (optional) Exit the game
```

---

## FBInstant.player

The `player` namespace provides access to information about the current player and methods for reading and writing persistent player data.

| Method / Property | Description |
|-------------------|-------------|
| `FBInstant.player.getID()` | Returns the player's unique ID for this game. This ID is consistent across sessions but is specific to your game (different games see different IDs for the same player). |
| `FBInstant.player.getSignedPlayerInfoAsync(requestPayload)` | Returns a `Promise` with a `SignedPlayerInfo` object containing a cryptographic signature that your server can verify to authenticate the player. |
| `FBInstant.player.getName()` | Returns the player's display name. |
| `FBInstant.player.getPhoto()` | Returns a URL to the player's profile photo. |
| `FBInstant.player.canSubscribeBotAsync()` | Returns a `Promise<boolean>` indicating whether the player can subscribe to the game's Messenger bot. |
| `FBInstant.player.subscribeBotAsync()` | Prompts the player to subscribe to the game's Messenger bot. Returns a `Promise`. |
| `FBInstant.player.setDataAsync(data)` | Saves persistent data for the current player. `data` is an object of key-value pairs. Values are serialized as JSON. Returns a `Promise`. |
| `FBInstant.player.getDataAsync(keys)` | Reads persistent data for the current player. `keys` is an array of strings. Returns a `Promise<Object>` with the requested key-value pairs. |
| `FBInstant.player.flushDataAsync()` | Immediately flushes any pending data writes to the server. Normally, data writes are batched. Use this when you need to guarantee that data has been persisted (e.g., before quitting). Returns a `Promise`. |
| `FBInstant.player.getStatsAsync(keys)` | Reads numeric stats for the current player. Returns a `Promise<Object>`. |
| `FBInstant.player.setStatsAsync(stats)` | Saves numeric stats for the current player. Returns a `Promise`. |
| `FBInstant.player.incrementStatsAsync(increments)` | Atomically increments numeric stats for the current player. Returns a `Promise<Object>` with the updated values. |
| `FBInstant.player.getConnectedPlayersAsync()` | Returns a `Promise` with an array of `ConnectedPlayer` objects representing players who are friends of the current player and have also played this game. |

### Player data storage

Facebook stores player data on its servers, and the data persists across sessions, devices, and platforms. There are two types of storage:

- **Key-value data** (`setDataAsync` / `getDataAsync`): For arbitrary game data, such as progress, settings, and inventory. Values can be strings, numbers, booleans, or objects.
- **Stats** (`setStatsAsync` / `getStatsAsync` / `incrementStatsAsync`): For numeric values that may need atomic increments, such as scores, currency, and play counts.

---

## FBInstant.context

The `context` namespace provides information about the current game context -- who the player is playing with and where the game was launched from.

| Method / Property | Description |
|-------------------|-------------|
| `FBInstant.context.getID()` | Returns the unique ID of the current game context, or `null` if the player is playing solo (no specific context). |
| `FBInstant.context.getType()` | Returns the type of the current context: `"SOLO"`, `"THREAD"`, `"GROUP"`, or `"ROOM"`. |
| `FBInstant.context.isSizeBetween(minSize, maxSize)` | Returns an object indicating whether the current context has a player count between `minSize` and `maxSize` (inclusive). Useful for checking group sizes. Returns `null` if size information is not available. |
| `FBInstant.context.switchAsync(contextID)` | Switches the game to a different context (e.g., a different Messenger thread). Returns a `Promise`. The game will reload in the new context. |
| `FBInstant.context.chooseAsync(options)` | Opens a dialog that lets the player choose a context to switch to (e.g., select a friend or Messenger thread). Returns a `Promise`. |
| `FBInstant.context.createAsync(playerID)` | Creates a new context with the specified player. Returns a `Promise`. Useful for starting a 1-on-1 game with a specific friend. |
| `FBInstant.context.getPlayersAsync()` | Returns a `Promise` with an array of `ContextPlayer` objects representing the other players in the current context. |

### Context types

| Type | Description |
|------|-------------|
| `SOLO` | The player is playing alone with no specific social context. |
| `THREAD` | The game was launched from a Messenger thread (1-on-1 or group). |
| `GROUP` | The game was launched from a Facebook Group. |
| `ROOM` | The game was launched from a Messenger Room (video call). See [Rooms Co-Play](https://developers.facebook.com/documentation/games/build/rooms-coplay). |

---

## FBInstant.payments

The `payments` namespace provides methods for handling in-app purchases (IAP). Use these APIs to sell virtual goods, currency packs, subscriptions, and other items within your game.

| Method | Description |
|--------|-------------|
| `FBInstant.payments.getCatalogAsync()` | Returns a `Promise` with an array of `Product` objects representing all products configured for your game in the App Dashboard. |
| `FBInstant.payments.purchaseAsync(purchaseConfig)` | Initiates a purchase flow for a specific product. `purchaseConfig` must include a `productID`. Returns a `Promise<Purchase>` with the purchase details. |
| `FBInstant.payments.getPurchasesAsync()` | Returns a `Promise` with an array of `Purchase` objects representing the player's unconsumed purchases. |
| `FBInstant.payments.consumePurchaseAsync(purchaseToken)` | Consumes a purchase, indicating that the purchased item has been delivered to the player. Must be called for consumable items to allow the player to purchase them again. Returns a `Promise`. |
| `FBInstant.payments.onReady(callback)` | Registers a callback that fires when the payments system is ready. You should not call other payment methods until this callback has fired. |

### IAP flow

```
1. FBInstant.payments.onReady(callback)     --> Wait for payments to be ready
2. FBInstant.payments.getCatalogAsync()      --> Retrieve available products
3. FBInstant.payments.purchaseAsync(config)  --> Player initiates a purchase
4. Deliver the item to the player            --> Your game logic
5. FBInstant.payments.consumePurchaseAsync() --> Mark the purchase as consumed
```

**Important:** In-app purchases are **not available on iOS** due to Apple's App Store policies regarding in-app purchases in web-based games. Use `FBInstant.getSupportedAPIs()` to check whether payments are available on the current platform before showing purchase UI.

```javascript
const paymentsSupported = FBInstant.getSupportedAPIs().includes('payments.purchaseAsync');
if (paymentsSupported) {
  showPurchaseButton();
}
```

---

## FBInstant.tournament

The `tournament` namespace provides methods for creating and managing tournaments -- time-limited competitive events where players compete for high scores.

| Method | Description |
|--------|-------------|
| `FBInstant.tournament.createAsync(config)` | Creates a new tournament with the specified configuration (title, score format, sort order, end time, image). Returns a `Promise<Tournament>`. |
| `FBInstant.tournament.shareAsync(payload)` | Opens a share dialog for the current tournament, letting the player invite friends. Returns a `Promise`. |
| `FBInstant.tournament.joinAsync(tournamentID)` | Joins an existing tournament. Returns a `Promise`. |
| `FBInstant.tournament.postScoreAsync(score)` | Posts the player's score to the current tournament. Returns a `Promise`. |
| `FBInstant.tournament.getTournamentsAsync()` | Returns a `Promise` with an array of `Tournament` objects the player is eligible to join or is already participating in. |

### Tournament Configuration

When creating a tournament with `createAsync()`, you can configure:

- **Title:** The display name of the tournament.
- **Score format:** How scores are displayed (`NUMERIC` or `TIME`).
- **Sort order:** Whether higher or lower scores are better (`HIGHER_IS_BETTER` or `LOWER_IS_BETTER`).
- **End time:** When the tournament ends (Unix timestamp).
- **Image:** A base64-encoded image to display with the tournament.

---

## FBInstant.leaderboard

The `leaderboard` namespace provides methods for interacting with leaderboards -- ranked lists of player scores.

| Method | Description |
|--------|-------------|
| `FBInstant.getLeaderboardAsync(name)` | Returns a `Promise<Leaderboard>` for the leaderboard with the specified name. The leaderboard must be configured in the App Dashboard. |

### Leaderboard object methods

Once you have a `Leaderboard` object, you can call the following methods on it:

| Method | Description |
|--------|-------------|
| `leaderboard.setScoreAsync(score, extraData)` | Sets the player's score on this leaderboard. If the player already has a higher score, the existing score is preserved. Returns a `Promise<LeaderboardEntry>`. |
| `leaderboard.getPlayerEntryAsync()` | Returns a `Promise<LeaderboardEntry>` with the current player's entry on this leaderboard, or `null` if the player has no entry. |
| `leaderboard.getEntriesAsync(count, offset)` | Returns a `Promise` with an array of `LeaderboardEntry` objects representing the top entries on this leaderboard. `count` specifies how many entries to return, and `offset` specifies where to start. |
| `leaderboard.getConnectedPlayerEntriesAsync(count, offset)` | Returns a `Promise` with an array of `LeaderboardEntry` objects for friends of the current player. This is useful for displaying a "friends only" leaderboard. |
| `leaderboard.getEntryCountAsync()` | Returns a `Promise<number>` with the total number of entries on this leaderboard. |

### Leaderboard example

```javascript
async function submitAndShowLeaderboard(score) {
  // Get the leaderboard
  const leaderboard = await FBInstant.getLeaderboardAsync('my_leaderboard');

  // Submit the player's score
  await leaderboard.setScoreAsync(score);

  // Get the player's rank
  const playerEntry = await leaderboard.getPlayerEntryAsync();
  console.log('Your rank:', playerEntry.getRank());

  // Get the top 10 entries
  const topEntries = await leaderboard.getEntriesAsync(10, 0);
  topEntries.forEach(entry => {
    console.log(
      `${entry.getRank()}. ${entry.getPlayer().getName()}: ${entry.getScore()}`
    );
  });

  // Get friends' entries
  const friendEntries = await leaderboard.getConnectedPlayerEntriesAsync(10, 0);
  friendEntries.forEach(entry => {
    console.log(
      `${entry.getRank()}. ${entry.getPlayer().getName()}: ${entry.getScore()}`
    );
  });
}
```

---

## Utility methods

These methods are available on the root `FBInstant` namespace and provide general-purpose utilities.

| Method | Description |
|--------|-------------|
| `FBInstant.getLocale()` | Returns the player's locale (e.g., `"en_US"`). |
| `FBInstant.getPlatform()` | Returns the current platform: `"IOS"`, `"ANDROID"`, or `"WEB"`. |
| `FBInstant.getSDKVersion()` | Returns the SDK version string (e.g., `"7.1"`). |
| `FBInstant.getSupportedAPIs()` | Returns an array of supported API method names. Use this to detect feature availability. |
| `FBInstant.getEntryPointData()` | Returns custom data passed to the game at launch (e.g., from a custom update, share, or ad). |
| `FBInstant.getEntryPointAsync()` | Returns a `Promise<string>` with the name of the entry point surface (e.g., `"feed"`, `"notification"`). |
| `FBInstant.logEvent(eventName, valueToSum, parameters)` | Logs a custom analytics event. `eventName` is a string (max 40 characters), `valueToSum` is a number, and `parameters` is an optional object (max 25 keys, values must be strings). |

### Feature detection

Not all APIs are available on all platforms. Before using an optional API, check whether it is supported:

```javascript
function isSupported(apiName) {
  return FBInstant.getSupportedAPIs().includes(apiName);
}

// Examples
if (isSupported('payments.purchaseAsync')) {
  // IAP is available on this platform
}

if (isSupported('performHapticFeedbackAsync')) {
  // Haptic feedback is available on this device
}

if (isSupported('tournament.createAsync')) {
  // Tournaments are supported
}
```

---

## Error handling

All async SDK methods return Promises. When a Promise rejects, it provides an error object with a `code` property and a `message` property. Common error codes include:

| Error Code | Description |
|------------|-------------|
| `INVALID_PARAM` | One or more parameters are invalid. |
| `INVALID_OPERATION` | The operation is not valid in the current state. |
| `NETWORK_FAILURE` | A network request failed. |
| `PENDING_REQUEST` | A request of this type is already pending. |
| `CLIENT_UNSUPPORTED_OPERATION` | The current client does not support this operation. |
| `USER_INPUT` | The user canceled the operation (e.g., closed a share dialog). |
| `SAME_CONTEXT` | Attempted to switch to the same context the game is already in. |
| `RATE_LIMITED` | The operation was called too frequently and was throttled. |
| `PAYMENTS_NOT_INITIALIZED` | A payment method was called before the payments system was ready. |

### Error handling example

```javascript
try {
  await FBInstant.context.switchAsync(newContextId);
} catch (error) {
  switch (error.code) {
    case 'SAME_CONTEXT':
      console.log('Already in this context.');
      break;
    case 'USER_INPUT':
      console.log('Player canceled the context switch.');
      break;
    case 'NETWORK_FAILURE':
      console.log('Network error. Please try again.');
      break;
    default:
      console.error('Unexpected error:', error.code, error.message);
  }
}
```

---

## Quick start example

Below is a minimal but complete example showing how to initialize the SDK, access player information, and start gameplay.

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My Instant Game</title>
  <script src="https://connect.facebook.net/en_US/fbinstant.8.0.js"></script>
</head>
<body>
  <canvas id="game-canvas"></canvas>
  <script src="game.js"></script>
</body>
</html>
```

```javascript
// game.js

async function main() {
  // Step 1: Initialize the SDK
  await FBInstant.initializeAsync();

  // Step 2: Load your game assets (replace with your actual loading logic)
  FBInstant.setLoadingProgress(25);
  await loadImages();
  FBInstant.setLoadingProgress(50);
  await loadSounds();
  FBInstant.setLoadingProgress(75);
  await loadLevels();
  FBInstant.setLoadingProgress(100);

  // Step 3: Start the game
  await FBInstant.startGameAsync();

  // Step 4: Access player and context information
  const playerID = FBInstant.player.getID();
  const playerName = FBInstant.player.getName();
  const playerPhoto = FBInstant.player.getPhoto();
  const contextType = FBInstant.context.getType();
  const platform = FBInstant.getPlatform();
  const locale = FBInstant.getLocale();

  console.log(`Welcome, ${playerName}!`);
  console.log(`Platform: ${platform}, Locale: ${locale}`);
  console.log(`Context type: ${contextType}`);

  // Step 5: Load saved player data
  const savedData = await FBInstant.player.getDataAsync(['level', 'highScore']);
  const currentLevel = savedData.level || 1;
  const highScore = savedData.highScore || 0;

  // Step 6: Start your game logic
  startGame(currentLevel, highScore);
}

main();
```

---

## Additional resources

- **[Rooms Co-Play](https://developers.facebook.com/documentation/games/build/rooms-coplay)** -- Multiplayer in Messenger Rooms.
- **[Haptic Feedback](https://developers.facebook.com/documentation/games/build/haptic-feedback)** -- Trigger device vibrations from your game.
- **[Game Performance](https://developers.facebook.com/documentation/games/build/game-performance)** -- Optimize loading and runtime performance.
- **[Best Practices](https://developers.facebook.com/documentation/games/overview/best-practices)** -- Design, social, and monetization best practices.
- **[FAQ](https://developers.facebook.com/documentation/games/build/faq)** -- Frequently asked questions about building Instant Games.
- **[App Dashboard](https://developers.facebook.com/apps/)** -- Manage your apps, configure products, and view analytics.