# "Instant Games SDK v7.1"


## Changelog
1. Adding APIs for apps to render video content natively

## FBInstant (Core)

Represents the type of section to include.  All section types may include both

### getLocale()

The current locale. See https://lookaside.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.initializeAsync() resolves.

**Returns:** `string` — The current locale.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var locale = FBInstant.getLocale(); // 'en_US'
```

---

### getPlatform()

The platform on which the game is currently running. The value will always
be null until FBInstant.initializeAsync() resolves.

**Returns:** `?`[`Platform`](#platform) — The platform on which the game is running.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var platform = FBInstant.getPlatform(); // 'IOS'
```

---

### getSDKVersion()

The string representation of this SDK version.

**Returns:** `string` — The SDK version.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var sdkVersion = FBInstant.getSDKVersion(); // '2.0'
```

---

### initializeAsync()

Initializes the SDK library. This should be called before any other SDK
functions.

**Returns:** `Promise` — A promise that resolves when the SDK is ready to use.

**Throws:**

- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.initializeAsync().then(function() {
  // Many properties will be null until the initialization completes.
  // This is a good place to fetch them:
  var locale = FBInstant.getLocale(); // 'en_US'
  var platform = FBInstant.getPlatform(); // 'IOS'
  var sdkVersion = FBInstant.getSDKVersion(); // '3.0'
  var playerID = FBInstant.player.getID();
});
```

---

### setLoadingProgress()

Report the game's initial loading progress.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `percentage` | `number` | A number between 0 and 100. |

**Example:**

```javascript
FBInstant.setLoadingProgress(50); // Assets are 50% loaded
```

---

### getSupportedAPIs()

Provides a list of API functions that are supported by the client.

**Returns:** `Array<string>` — List of API functions that the client explicitly supports.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
FBInstant.getSupportedAPIs();
// ['getLocale', 'initializeAsync', 'player.getID', 'context.getType', ...]
```

---

### getEntryPointData()

Returns any data object associated with the entry point that the game was
launched from.

The contents of the object are developer-defined, and can
occur from entry points on different platforms. This will return null for
older mobile clients, as well as when there is no data associated with
the particular entry point.

This function should be called after FBInstant.initializeAsync()
resolves.

**Returns:** `?Object` — Data associated with the current entry point.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
const entryPointData = FBInstant.getEntryPointData();
```

---

### getEntryPointAsync()

Returns the entry point that the game was launched from.

This function should not be called until FBInstant.startGameAsync has
resolved.

**Returns:** `string` — The name of the entry point from which the user started the game

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
FBInstant.getEntryPointAsync().then(entrypoint => console.log(entrypoint));
// 'admin_message'
```

---

### setSessionData()

Sets the data associated with the individual gameplay session for the
current context.

This function should be called whenever the game would like to update the
current session data. This session data may be used to populate a variety
of payloads, such as game play webhooks.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `sessionData` | `Object` | An arbitrary data object, which must be less than or equal to 1000 characters when stringified. |

**Example:**

```javascript
FBInstant.setSessionData({coinsEarned: 10, eventsSeen: ['start', ...]});
```

---

### startGameAsync()

This indicates that the game has finished initial loading and is ready to
start. Context information will be up-to-date when the returned promise
resolves.

**Returns:** `Promise` — A promise that resolves when the game should start.

**Throws:**

- `INVALID_PARAM`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.startGameAsync().then(function() {
  myGame.start();
});
```

---

### graphApi

Contains functions and properties related to Graph APIs

---

### achievement

[IN CLOSED BETA]
Contains functions and properties related to in-game achievements.

---

### inviteAsync()

This invokes a dialog to let the user invite one or more people to the game.
  A blob of data can be attached to the invite which every game session
  launched from the invite will be able to access from
  FBInstant.getEntryPointData(). This data must be less than or equal to
  1000 characters when stringified. The user may choose to cancel the
  action and close the dialog, and the returned promise will resolve when
  the dialog is closed regardless of whether the user actually invited people
  or not.
The sections included in the dialog can be customized by using the sections
  parameter.  This can specify which sections to include, how many results to
  include in each section, and what order the sections should appear in.  The
  last section will include as many results as possible.  If no sections are
  specified, the default section settings will be applied.
The filters parameter allows for filtering the results.  If no results are
  returned when the filters are applied, the results will be generated without
  the filters.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | [`InvitePayload`](#invitepayload) | Specify what to share. See example for   details. |

**Returns:** `Promise` — A promise that resolves when the share is completed or   cancelled.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `PENDING_REQUEST`
- `CLIENT_UNSUPPORTED_OPERATION`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.inviteAsync({
  image: base64Picture,
  text: {
    default: 'X just invaded Y\'s village!',
    localizations: {
      ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' +
        '\u0642\u0631\u064A\u0629 Y!',
      en_US: 'X just invaded Y\'s village!',
      es_LA: '\u00A1X acaba de invadir el pueblo de Y!'
    }
  },
  data: { myReplayData: '...' }
}).then(function() {
  // continue with the game.
});
```

```javascript
FBInstant.inviteAsync({
  image: base64Picture,
  text: {
    default: 'X just invaded Y\'s village!',
    localizations: {
      ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' +
        '\u0642\u0631\u064A\u0629!',
      en_US: 'X just invaded Y\'s village!',
      es_LA: '\u00A1X acaba de invadir el pueblo de Y!'
    }
  },
  cta: {
    default: 'Join the fight!',
    localizations: {
      ar_AR: '\u0627\u0646\u0636\u0645 \u0625\u0644\u0649' +
        '\u0627\u0644\u0642\u062A\u0627\u0644!',
      en_US: 'Join the fight!',
      es_LA: '\u00A1\u00DAnete a la pelea!'
    }
  },
  dialogTitle: {
    default: 'Enlist your friends',
    localizations: {
      ar_AR: '\u062D\u0634\u062F \u0623\u0635\u062F\u0642' +
        '\u0627\u0621\u0643',
      en_US: 'Enlist your friends',
      es_LA: 'Alistar a tus amigos'
    }
  },
  filters: ['NEW_CONTEXT_ONLY', 'EXISTING_PLAYERS_ONLY'],
  sections: [
    {sectionType: 'GROUPS', maxResults: 2},
    {sectionType: 'USERS'}
  ],
  data: { myReplayData: '...' }
}).then(function() {
  // continue with the game.
});
```

---

### shareAsync()

This invokes a dialog to let the user share specified content, as a post
on the user's timeline, for example. A blob of data can be attached to the
share which every game session launched from the share will be able to
access from FBInstant.getEntryPointData(). This data must be less than or
equal to 1000 characters when stringified. The user may choose to cancel
the share action and close the dialog, and the returned promise will
resolve when the dialog is closed regardless if the user actually shared
the content or not.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | [`SharePayload`](#sharepayload) | Specify what to share. See example for   details. |

**Returns:** `Promise` — A promise that resolves when the share is completed or   cancelled.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `PENDING_REQUEST`
- `CLIENT_UNSUPPORTED_OPERATION`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.shareAsync({
  image: base64Picture,
  text: 'X is asking for your help!',
  data: { myReplayData: '...' },
  shareDestination: ['NEWSFEED', 'GROUP', 'COPY_LINK', 'MESSENGER']
  switchContext: false,
}).then(function() {
  // continue with the game.
});
```

---

### registerScreenshotProvider()

This registers a callback function that will get called when the user
attempts to capture a screenshot of the game. Through the callback,
the game can pass an image along with metadata that associates the
screenshot. Users will then have the option to share the screenshot, or
save it to their library.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `provideer` | `@link `[`ScreenshotProvider`](#screenshotprovider) | Specify the callback function that   gets called when the user attempts to capture a screenshot. |

**Throws:**

- `INVALID_PARAM`
- `CLIENT_UNSUPPORTED_OPERATION`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.registerScreenshotProvider(function (submitAsync) {
  submitAsync({
    image: myBase64Image,
    text: 'my awesome screenshot',
    data: { custom_field: 'my awesome data' }
  }).then(function () {
    resumeGame();
  }).catch(function (error) {
    log(error);
  });
});
```

---

### shareLinkAsync()

This invokes a dialog that contains a custom game link that users can copy
to their clipboard, or share. A blob of data can be attached
to the custom link - game sessions initiated from the link will be able to access the data through
FBInstant.getEntryPointData(). This data should be less than or equal to
1000 characters when stringified. The provided text and image will be used to
generate the link preview, with the game name as the title of the preview.
The text is recommended to be less than 44 characters.
The image is recommended to either be a square or of the aspect ratio 1.91:1.
The returned promise will resolve when the dialog is closed regardless if the
user actually shared the link or not.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | [`LinkSharePayload`](#linksharepayload) | Specify the payload for the custom link. See example for   details. |

**Returns:** `Promise` — A promise that resolves when the share is completed or   cancelled.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `PENDING_REQUEST`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.shareLinkAsync({
  image: base64Picture,
  text: 'Come check out what Joe has built!',
  data: { customData: '...' },
}).then(function() {
  // continue with the game.
});
```

---

### updateAsync()

Informs Facebook of an update that occurred in the game. This will
temporarily yield control to Facebook and Facebook will decide what to do
based on what the update is. The returned promise will resolve/reject when
Facebook returns control to the game.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | [`UpdatePayload`](#updatepayload) | A payload that describes the update. |

**Returns:** `Promise` — A promise that resolves when Facebook gives control   back to the game.

**Throws:**

- `INVALID_PARAM`
- `PENDING_REQUEST`
- `INVALID_OPERATION`

**Example:**

```javascript
// This will post a custom update. When people launch the game from this
// message, those game sessions will be able to access the specified blob
// of data through FBInstant.getEntryPointData().
FBInstant.updateAsync({
  action: 'CUSTOM',
  cta: 'Join The Fight',
  image: base64Picture,
  text: {
    default: 'X just invaded Y\'s village!',
    localizations: {
      ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' +
      '\u0642\u0631\u064A\u0629 Y!',
      en_US: 'X just invaded Y\'s village!',
      es_LA: '\u00A1X acaba de invadir el pueblo de Y!',
    }
  }
  template: 'VILLAGE_INVASION',
  data: { myReplayData: '...' },
  strategy: 'IMMEDIATE',
  notification: 'NO_PUSH',
}).then(function() {
  // closes the game after the update is posted.
  FBInstant.quit();
});
```

---

### switchGameAsync()

Request 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:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `appID` | `string` | The Application ID of the Instant Game to switch to.   The application must be an Instant Game, and must belong to the same   business as the current game. To associate different games with the same   business, you can use Business Manager:   https://developers.facebook.com/docs/apps/business-manager#update-business. |
| `data` | `Object` _(optional)_ | An optional data payload. This will be set as the   entrypoint data for the game being switched to. Must be less than or   equal to 1000 characters when stringified. |

**Throws:**

- `USER_INPUT`
- `INVALID_PARAM`
- `PENDING_REQUEST`
- `CLIENT_REQUIRES_UPDATE`

**Example:**

```javascript
FBInstant.switchGameAsync('12345678').catch(function (e) {
  // Handle game change failure
});
```

```javascript
FBInstant.switchGameAsync(
  '12345678',
  {referrer: 'game_switch', reward_coins: 30},
).catch(function (e) {
  // Handle game change failure
});
```

---

### canSwitchNativeGameAsync()

Utility function to check if the current player
can call switchNativeGameAsync()

**Returns:** `Promise<boolean>` — if the player can call switchNativeGameAsync

---

### switchNativeGameAsync()

Request that the client switch to its Native (Android/iOS) Game. The API
will reject if the switch fails - else, the client will open the Game
or Store.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `data` | `Object` _(optional)_ | An optional data payload. This will be set as the   entrypoint data for the game being switched to. Must be less than or   equal to 1000 characters when stringified. |

---

### canCreateShortcutAsync()

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.

**Returns:** `Promise<boolean>` — Promise that resolves with true if the game can request the player create a shortcut to the game, and false otherwise

**Throws:**

- `PENDING_REQUEST`
- `CLIENT_REQUIRES_UPDATE`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.canCreateShortcutAsync()
  .then(function(canCreateShortcut) {
    if (canCreateShortcut) {
      FBInstant.createShortcutAsync()
        .then(function() {
          // Shortcut created
        })
        .catch(function() {
          // Shortcut not created
        });
    }
  });
```

---

### createShortcutAsync()

Prompts the user to create a shortcut to the game if they are eligible to
Can only be called once per session.
(see [`canCreateShortcutAsync`](#cancreateshortcutasync))

**Throws:**

- `USER_INPUT`
- `PENDING_REQUEST`
- `CLIENT_REQUIRES_UPDATE`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.canCreateShortcutAsync()
  .then(function(canCreateShortcut) {
    if (canCreateShortcut) {
      FBInstant.createShortcutAsync()
        .then(function() {
          // Shortcut created
        })
        .catch(function() {
          // Shortcut not created
        });
    }
  });
```

---

### quit()

Quits the game.

**Example:**

```javascript
FBInstant.quit();
```

---

### onPause()

Set a callback to be fired when a pause event is triggered (when the user switches away from the window/tab on desktop or when the user switches apps on mobile).

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `func` | `Function` | A function to call when a pause event occurs. |

**Example:**

```javascript
FBInstant.onPause(function() {
  console.log('Pause event was triggered!');
  pauseGameplay();
})
```

---

### hideBannerAdAsync()

Attemp to hide a banner ad.

**Returns:** `Promise` — A promise that resolves after the ad is hidden.

**Throws:**

- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.hideBannerAdAsync();
```

---

### getInterstitialAdAsync()

Attempt to create an instance of interstitial ad. This instance can then be
preloaded and presented.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `placementID` | `string` | The placement ID that's been setup in your   Audience Network settings. |

**Returns:** `Promise` — A promise that resolves with a   [`AdInstance`](#adinstance), or rejects with a [`APIError`](#apierror) if   it couldn't be created.

**Throws:**

- `ADS_TOO_MANY_INSTANCES`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.getInterstitialAdAsync(
  'my_placement_id'
).then(function(interstitial) {
  interstitial.getPlacementID(); // 'my_placement_id'
});
```

---

### isAdBreakTest()

Check if the user is in the ad break testing group

**Returns:** `boolean` — true if the user is in the ad break testing group

---

### getRewardedVideoAsync()

Attempt to create an instance of rewarded video. This instance can then be
preloaded and presented.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `placementID` | `string` | The placement ID that's been setup in your   Audience Network settings. |

**Returns:** `Promise` — A promise that resolves with a   [`AdInstance`](#adinstance), or rejects with a [`APIError`](#apierror) if   it couldn't be created.

**Throws:**

- `ADS_TOO_MANY_INSTANCES`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.getRewardedVideoAsync(
  'my_placement_id'
).then(function(rewardedVideo) {
  rewardedVideo.getPlacementID(); // 'my_placement_id'
});
```

---

### checkCanPlayerMatchAsync()

Checks if the current player is eligible for the matchPlayerAsync API.

**Returns:** `Promise<boolean>` — A promise that resolves with true if the player   is eligible to match with other players and false otherwise.

**Throws:**

- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant
  .checkCanPlayerMatchAsync()
  .then(canMatch => {
    if (canMatch) {
      FBInstant.matchPlayerAsync('level1');
    }
  });
```

---

### getLeaderboardAsync()

Fetch a specific leaderboard belonging to this Instant Game.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the leaderboard. Each leaderboard for an   Instant Game must have its own distinct name. |

**Returns:** `Promise<`[`Leaderboard`](#leaderboard)`>` — A promise that resolves with the   matching leaderboard, rejecting if one is not found.

**Throws:**

- `LEADERBOARD_NOT_FOUND`
- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`
- `INVALID_OPERATION`
- `INVALID_PARAM`

**Example:**

```javascript
FBInstant.getLeaderboardAsync('my_awesome_leaderboard')
  .then(leaderboard => {
    console.log(leaderboard.getName()); // 'my_awesome_leaderboard'
  });
```

---

### postSessionScoreAsync()

Posts a player's score to Facebook and resolves when score has been posted.
This API should only be called at the end of an activity (example: when the
player doesn't have "lives" to continue the game). This API will be rate-limited
when called too frequently. Scores posted using this API should be consistent
& comparable across game sessions. For example, if Player A achieves 200 points in a
session, and Player B achieves 320 points in a session, those two scores
should be generated from activities where the scores are fair to be
compared and ranked against each other.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `score` | `number` | An integer value representing the player's score at   the end of an activity. |

**Returns:** `Promise` — A promise that resolves when all platform behavior (such as dialogs)   generated from the posted score has completed, and the game should resume.   If the behavior resulted in a social context change, that will be reflected   by the time the Promise resolves.

**Example:**

```javascript
function onScore(score) {
  if (score > bestSessionScore) {
    bestSessionScore = score;
    FBInstant.postSessionScoreAsync(bestSessionScore)
      .then(() => {
        ...
      });
  }
}
```

---

### getTournamentAsync()

Fetch the instant tournament out of the current context the user is playing.
This will reject if there is no instant tournament link to the current context.
The instant tournament returned can be either active or expired (An instant
tournament is expired if its end time is in the past). For each instant
tournament, there is only one unique context ID linked to it, and that ID
doesn't change.

**Returns:** `Promise<`[`Tournament`](#tournament)`>` — A promise that resolves with the matched instant   tournament a user is playing. This rejects if no instant tournament is found.

**Throws:**

- `PENDING_REQUEST`
- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `TOURNAMENT_NOT_FOUND`

**Example:**

```javascript
FBInstant.getTournamentAsync()
  .then(function(tournament) {
     console.log(tournament.getContextID());
     console.log(tournament.getEndTime());
  });
```

---

### performHapticFeedbackAsync()

Requests and performs haptic feedback on supported devices.

**Returns:** `Promise<void>` — haptic feedback requested successfully

**Throws:**

- `CLIENT_UNSUPPORTED_OPERATION`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.performHapticFeedbackAsync();
```

---

### getPlacementID()

Return the Audience Network placement ID of this ad instance.

---

### loadAsync()

Preload the ad. The returned promise resolves when the preload
completes, and rejects if it failed.

**Throws:**

- `ADS_FREQUENT_LOAD`
- `ADS_NO_FILL`
- `INVALID_PARAM`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.getInterstitialAdAsync(
  'my_placement_id',
).then(function(interstitial) {
  return interstitial.loadAsync();
}).then(function() {
  // Ad loaded
});
```

---

### showAsync()

Present the ad. The returned promise resolves when user
finished watching the ad, and rejects if it failed to present or
was closed during the ad.

**Throws:**

- `ADS_NOT_LOADED`
- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `RATE_LIMITED`
- `USER_INPUT`

**Example:**

```javascript
var ad = null;
FBInstant.getRewardedVideoAsync(
  'my_placement_id',
).then(function(rewardedVideo) {
  ad = rewardedVideo;
  return ad.loadAsync();
}).then(function() {
  // Ad loaded
  return ad.showAsync();
}).then(function() {
  // Ad watched
});
```

---

### getName()

The name of the leaderboard.

**Example:**

```javascript
FBInstant.getLeaderboardAsync('my_leaderboard')
  .then(function(leaderboard) {
    console.log(leaderboard.getName()); // my_leaderboard
  });
```

---

### getContextID()

The ID of the context that the leaderboard is associated with, or null if
the leaderboard is not tied to a particular context.

**Example:**

```javascript
FBInstant.getLeaderboardAsync('contextual_leaderboard')
  .then(function(leaderboard) {
    console.log(leaderboard.getContextID()); // 12345678
  });
```

```javascript
FBInstant.getLeaderboardAsync('global_leaderboard')
  .then(function(leaderboard) {
    console.log(leaderboard.getContextID()); // null
  });
```

---

### getEntryCountAsync()

Fetches the total number of player entries in the leaderboard.

**Returns:** `Promise<number>` — A unique identifier for the player.

**Throws:**

- `NETWORK_FAILURE`
- `RATE_LIMITED`

**Example:**

```javascript
FBInstant.getLeaderboardAsync('my_leaderboard')
  .then(function(leaderboard) {
    return leaderboard.getEntryCountAsync();
  })
  .then(function(count) { console.log(count); }); // 24
```

---

### getPlayerEntryAsync()

Retrieves the leaderboard's entry for the current player, or null if the
player has not set one yet.

**Returns:** `?Promise<`[`LeaderboardEntry`](#leaderboardentry)`>` — Resolves with the current leaderboard   entry for the player.

**Throws:**

- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `RATE_LIMITED`

**Example:**

```javascript
FBInstant.getLeaderboardAsync('my_leaderboard')
  .then(function(leaderboard) {
    return leaderboard.getPlayerEntryAsync();
  })
  .then(function(entry) {
    console.log(entry.getRank()); // 2
    console.log(entry.getScore()); // 42
    console.log(entry.getExtraData()); // '{race: "elf", level: 3}'
  });
```

---

### getScore()

Gets the score associated with the entry.

**Returns:** `number` — Returns an integer score value.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getScore()); // 9001
  });
```

---

### getFormattedScore()

Gets the score associated with the entry, formatted with the score format
associated with the leaderboard.

**Returns:** `string` — Returns a formatted score.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getFormattedScore()); // '90.01 meters'
  });
```

---

### getTimestamp()

Gets the timestamp of when the leaderboard entry was last updated.

**Returns:** `number` — Returns a Unix timestamp.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getTimestamp()); // 1515806355
  });
```

---

### getRank()

Gets the rank of the player's score in the leaderboard.

**Returns:** `number` — Returns the entry's leaderboard ranking.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getRank()); // 2
  });
```

---

### getExtraData()

Gets the developer-specified payload associated with the score, or null
if one was not set.

**Returns:** `?string` — An optional developer-specified payload associated with the score.

**Example:**

```javascript
leaderboard.setScoreAsync(42, '{race: "elf", level: 3}');
  .then(function(entry) {
    console.log(entry.getExtraData()); // '{race: "elf", level: 3}'
  });
```

---

### getPlayer()

Gets information about the player associated with the entry.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getPlayer().getName()); // Sally
  });
```

---

### getPhoto()

Returns a url to the player's public profile photo.

**Returns:** `?string` — Url to the player's public profile photo.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getPlayer().getPhoto()); // <photo_url>
  });
```

---

### getID()

Gets the game's unique identifier for the player.

**Returns:** `?string` — The game-scoped identifier for the player.

**Example:**

```javascript
leaderboard.setScoreAsync(9001)
  .then(function(entry) {
    console.log(entry.getPlayer().getID()); // 12345678
  });
```

---

### getEndTime()

Timestamp when the instant tournament ends. If the end time is in the past,
then the instant tournament is already finished and has expired.

**Example:**

```javascript
FBInstant.getTournamentAsync()
  .then(function(tournament) {
    console.log(tournament.getEndTime());
  });
```

---

### getTournamentType()

Type of the tournament, eg default, page_hosted, daily, etc.

**Example:**

```javascript
FBInstant.getTournamentAsync()
  .then(function(tournament) {
    console.log(tournament.getTournamentType());
  });
```

---

### getTitle()

Title of the tournament provided upon the creation of the tournament. This
is an optional field that can be set by creating the tournament using the
FBInstant.tournament.createAsync() API.

Returns null if none was provided.

**Example:**

```javascript
FBInstant.getTournamentAsync()
  .then(function(tournament) {
    console.log(tournament.getTitle());
  })
```

---

### getPayload()

Payload of the tournament provided upon the creation of the tournament.
This is an optional field that can be set by creating the tournament using
the FBInstant.tournament.createAsync() API.

Returns null if none was provided.

**Example:**

```javascript
FBInstant.getTournamentAsync()
  .then(function(tournament) {
    console.log(tournament.getPayload());
  })
```

---

### constructor()

Creates a new APIError instance.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `args` | [`APIErrorArgs`](#apierrorargs) | - The error arguments. |

**Returns:** `void`

---

### Types

#### Platform

Represents the current platform that the user is playing on.

---

#### InvitePayload

Represents content to be shared in invites sent by the user.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `image` | `string` | A base64 encoded image to be shared. |
| `text` | `string \| `[`LocalizableContent`](#localizablecontent) | A text message, or an object   with the default text as the value of 'default' and another object   mapping locale keys to translations as the value of 'localizations'. |
| `cta` | `string \| ?`[`LocalizableContent`](#localizablecontent) _(optional)_ | Optional call-to-action button   text. By default we will use a localized 'Play' as the button text.   To provide localized versions of your own call to action, pass an object   with the default cta as the value of 'default' and another object   mapping locale keys to translations as the value of 'localizations'. |
| `dialogTitle` | `string \| ?`[`LocalizableContent`](#localizablecontent) _(optional)_ | An optional title to   display at the top of the invite dialog instead of the generic title.  This   param is not sent as part of the message, but only displays in the dialog   header.  The title can be either a string or an object with the default   text as the value of 'default' and another object mapping locale keys to   translations as the value of 'localizations'. |
| `data` | `Object` _(optional)_ | A blob of data to attach to the share. All game   sessions launched from the share will be able to access this blob through   FBInstant.getEntryPointData(). |
| `filters` | `Array<`[`InviteFilter`](#invitefilter)`>` _(optional)_ | The set of filters to apply to the   suggestions. Multiple filters may be applied. If no results are returned   when the filters are applied, the results will be generated without the   filters. |
| `sections` | `Array<`[`InviteSection`](#invitesection)`>` _(optional)_ | The set of sections to be   included in the dialog. Each section can be assigned a maximum number of   results to be returned (up to a maximum of 10). If no max is included, a   default max will be applied.  Sections will be included in the order they   are listed in the array. The last section will include a larger maximum   number of results, and if a maxResults is provided, it will be ignored. If   this array is left empty, default sections will be used. |

---

#### InviteFilter

A filter that may be applied to an inviteAsync operation.  If no results are returned
  with the filters, then the filters will not be applied.
'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been
  played in before.  This can include players who have not played the game before.
'NEW_PLAYERS_ONLY' - Prefer to only surface people who have not played the
  game before.
'EXISTING_CONTEXT_ONLY' - Prefer to only surface contexts the game has been
  played in before.
'EXISTING_PLAYERS_ONLY' - Prefer to only surface people who have played the
  game before.

---

#### InviteSection

Represents a section in the inviteAsync dialog that contains suggested matches.
  The sections will be shown in the order they are included in the array, and the last
  section will contain as many results as possible.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `sectionType` | `InviteSectionType` | The type of section to include in the   inviteAsync dialog |
| `maxResults` | `number` _(optional)_ | Optional maximum number of results to include   in the section.  This can be no higher than 10.  This will be disregarded for the last   section, which will contain as many results as possible.  If not included, the default   maximum number of results for that section type will be used. |

---

#### ShareDestination

A parameter that may be applied to a shareAsync operation. This set up sharing
destination in the share dialog.
'NEWSFEED' - Enable share to newsfeed option
'GROUP' - Enable share to official game group option. This is only available
  for games with official game group. To set up official game group, add a
  page in the game app setting in https://www.developers.facebook.com, and then
  create a group for the page in https://facebook.com.
'COPY_LINK' - Enable copy the game link in clipboard
'MESSENGER' - Enable share game to messenger option

---

#### SharePayload

Represents content to be shared by the user.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `image` | `string` | A base64 encoded image to be shared. |
| `media` | [`MediaParams`](#mediaparams) _(optional)_ | Optional content for the gif or video. |
| `text` | `string` | A text message to be shared. |
| `data` | `Object` _(optional)_ | A blob of data to attach to the share. All game   sessions launched from the share will be able to access this blob through   FBInstant.getEntryPointData(). |
| `shareDestination` | `Array<`[`ShareDestination`](#sharedestination)`>` _(optional)_ | A optional array to set   sharing destinations in the share dialog.If not specified all available   sharing destinations will be displayed. |
| `switchContext` | `boolean` _(optional)_ | A flag indicating whether to switch the user   into the new context created on sharing |

---

#### LinkSharePayload

Represents a custom link to be shared by the user.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `image` | `string` _(optional)_ | A base64 encoded image to be shown for the link preview. The image is recommended to either be a square or of the aspect ratio 1.91:1 |
| `text` | `string` _(optional)_ | A text description for the link preview. Recommended to be less than 44 characters |
| `data` | `Object` | A blob of data to associate with the shared link. All game   sessions launched from the share will be able to access this blob through   FBInstant.getEntryPointData(). |

---

#### MediaContent

Specify how we could get the content for the media.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `URL` | `string` | for the media that stores in the developers' server. |

---

#### MediaParams

Represents the media payload used by custom update and custom share.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `Optional` | [`MediaContent`](#mediacontent) | , if provided, the content should contain   information for us to get the gif. |
| `Optional` | [`MediaContent`](#mediacontent) | , if provided, the content should contain   information for us to get the video. |

---

#### CustomUpdatePayload

Represents a custom update for FBInstant.updateAsync. Note that if localized
content is not provided, a Facebook supplied localized string will be used
for the call to action and text.

The `default` string should always be in English.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `action` | `UpdateAction` | For custom updates, this should be 'CUSTOM'. |
| `template` | `string` | ID of the template this custom update is using.   Templates should be predefined in fbapp-config.json. See   the [Bundle Config documentation][https://developers.facebook.com/docs/games/instant-games/bundle-config](https://developers.facebook.com/docs/games/instant-games/bundle-config) for   documentation about fbapp-config.json. |
| `cta` | `string \| ?`[`LocalizableContent`](#localizablecontent) _(optional)_ | Optional call-to-action button   text. By default we will use a localized 'Play' as the button text.   To provide localized versions of your own call to action, pass an object   with the default cta as the value of 'default' and another object   mapping locale keys to translations as the value of 'localizations'. |
| `image` | `string` _(optional)_ | Optional data URL of a base64 encoded image. |
| `media` | [`MediaParams`](#mediaparams) _(optional)_ | Optional content for the gif or   video. At least one image or media should be provided in order to render   the update. |
| `text` | `string \| `[`LocalizableContent`](#localizablecontent) | A text message, or an object   with the default text as the value of 'default' and another object   mapping locale keys to translations as the value of 'localizations'. |
| `data` | `Object` _(optional)_ | A blob of data to attach to the update. All game   sessions launched from the update will be able to access this blob through   FBInstant.getEntryPointData(). Must be less than or equal to 1000   characters when stringified. |
| `strategy` | `string` _(optional)_ | Specifies how the update should be   delivered. This can be one of the following:   'IMMEDIATE' - The update should be posted immediately.   'LAST' - The update should be posted when the game session ends. The most     recent update sent using the 'LAST' strategy will be the one sent.   If no strategy is specified, we default to 'IMMEDIATE'. |
| `notification` | `string` _(optional)_ | Specifies notification setting for the   custom update. This can be 'NO_PUSH' or 'PUSH', and defaults to 'NO_PUSH'.   Use push notification only for updates that are high-signal and immediately   actionable for the recipients. Also note that push notification is not   always guaranteed, depending on user setting and platform policies. |

---

#### LeaderboardUpdatePayload

Represents a leaderboard update for FBInstant.updateAsync.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `action` | `UpdateAction` | For a leaderboard update, this should be   'LEADERBOARD'.   text. By default we will use a localized 'Play Now' as the button text. |
| `name` | `string` | The name of the leaderboard to feature   in the update. |
| `text` | `string` _(optional)_ | Optional text message. If not specified, a   localized fallback message will be provided instead. |

---

#### LocalizableContent

Represents a string with localizations and a default value to fall back on.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `default` | `string` | The default value of the string to use if   the viewer's locale is not a key in the localizations object. |
| `localizations` | [`LocalizationsDict`](#localizationsdict) | Specifies what string to use   for viewers in each locale.   See https://lookaside.facebook.com/developers/resources/?id=FacebookLocales.xml   for a complete list of supported locale values. |

---

#### UpdatePayload

---

#### AdInstance

Represents an instance of an ad.

---

#### Leaderboard

An Instant Game leaderboard

---

#### LeaderboardEntry

A score entry for an Instant Game leaderboard

---

#### LeaderboardPlayer

Details about the player associated with a score entry.

---

#### LocalizationsDict

Represents a mapping from locales to translations of a given string.
Each property is an optional five-character Facebook locale code of the form
xx_XX.
See https://lookaside.facebook.com/developers/resources/?id=FacebookLocales.xml
for a complete list of supported locale codes.

---

#### ScreenshotPayload

Represents screenshot content provided by the game that later on can be
shared by the user.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `image` | `string` | A base64 encoded image that is the screenshot. |
| `text` | `string` | A text message to describes the screenshot. |
| `data` | `Object` _(optional)_ | A blob of data to attach to the screenshot. If the   user ended up sharing this screenshot, all game sessions launched from the   share will be able to access this blob through   FBInstant.getEntryPointData(). |

---

#### ScreenshotSubmitter

A function that allows the game to submit a screenshot.

---

#### ScreenshotProvider

A function that will get called when user requested to capture a screenshot.

---

#### Tournament

An instant game tournament.

---

#### ErrorCode

Error codes that may be returned by the Instant Games API

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `ADS_FREQUENT_LOAD` | `string` | - Ads are being loaded too frequently. |
| `ADS_NO_FILL` | `string` | - We were not able to serve ads to the current   user. This can happen if the user has opted out of interest-based ads on   their device, or if we do not have ad inventory to show for that user. |
| `ADS_NOT_LOADED` | `string` | - Attempted to show an ad that has not   been loaded successfully. |
| `ADS_TOO_MANY_INSTANCES` | `string` | - There are too many concurrent   ad instances. Load and show existing ad instances before creating new ones. |
| `ANALYTICS_POST_EXCEPTION` | `string` | - The analytics API experienced a   problem while attempting to post an event. |
| `CLIENT_REQUIRES_UPDATE` | `string` | [Deprecated] - The client requires   an update to access the feature that returned this result. If this result   is returned on web, it means the feature is not supported by the web client  yet. Deprecated in favor of CLIENT_UNSUPPORTED_OPERATION in v5.0 and above |
| `CLIENT_UNSUPPORTED_OPERATION` | `string` | - The client does not support   the current operation. This may be due to lack of support on the client   version or platform, or because the operation is not allowed for the game   or player. |
| `OPERATION_SUPPRESSED` | `string` | - The operation was suppressed by the   platform. This may be due to user-level rate limiting, play style   restrictions, or other reasons. |
| `GLOBAL_LEADERBOARD_NOT_FOUND` | `string` | - No global leaderboard with  the requested ID was found. Either the leaderboard does not exist yet, or the  ID did not match any registered leaderboard, you can verify the leaderboard ID  in the Global Leaderboard section of the Instant Games Dashboard. |
| `IARC_CERT_NOT_FOUND` | `string` | - The requested IARC (International  Age Rating Coalition) certificate was not found. |
| `IARC_CERT_TEST_ONLY` | `string` | - This is a test IARC (International  Age Rating Coalition) operation. |
| `IARC_SUBMIT_CERT_FAILED` | `string` | - Thw IARC (International Age  Rating Coalition) certificate failed to be submitted. |
| `IARC_SUBMIT_EMAIL_FAILED` | `string` | - The developer's IARC (International Age Rating Coalition) contact email failed to be submitted. |
| `INVALID_OPERATION` | `string` | - The requested operation is invalid   or the current game state. This may include requests that violate   limitations, such as exceeding storage thresholds, or are not available in   a certain state, such as making a context-specific request in a solo   context. |
| `INVALID_PARAM` | `string` | - The parameter(s) passed to the API are   invalid. Could indicate an incorrect type, invalid number of arguments, or   a semantic issue (for example, passing an unserializable object to a   serializing function). |
| `LEADERBOARD_NOT_FOUND` | `string` | - No leaderboard with the requested   name was found. Either the leaderboard does not exist yet, or the name   did not match any registered leaderboard configuration for the game. |
| `LEADERBOARD_WRONG_CONTEXT` | `string` | - Attempted to write to a   leaderboard that's associated with a context other than the one the game is   currently being played in. |
| `MOCK_IAP` | `string` | - User is temporarily turning off Mock IAP and   switching to production flow for current purchase |
| `NETWORK_FAILURE` | `string` | - The client experienced an issue with a   network request. This is likely due to a transient issue, such as the   player's internet connection dropping. |
| `PAYMENTS_NOT_INITIALIZED` | `string` | - The client has not completed   setting up payments or is not accepting payments API calls. |
| `PENDING_REQUEST` | `string` | - Represents a rejection due an existing   request that conflicts with this one. For example, we will reject any calls   that would surface a Facebook UI when another request that depends on a   Facebook UI is pending. |
| `RATE_LIMITED` | `string` | - Some APIs or operations are being called   too often. This is likely due to the game calling a particular API an   excessive amount of times in a very short period. Reducing the rate of   requests should cause this error to go away. |
| `SAME_CONTEXT` | `string` | - The game attempted to perform a context   switch into the current context. |
| `TOURNAMENT_NOT_SHAREABLE` | `string` | - The game attempted to share   a private tournament. This is only possible for non-private tournaments. If   a score was submitted with the share call, then the score was still   submitted. |
| `UNKNOWN` | `string` | - An unknown or unspecified issue occurred. This   is the default error code returned when the client does not specify a code. |
| `USER_INPUT` | `string` | - The user made a choice that resulted in a   rejection. For example, if the game calls up the Context Switch dialog and   the player closes it, this error code will be included in the promise   rejection. |

---

#### ErrorCodeType

An Instant Games error code, one of [`ErrorCode`](#errorcode)

---

#### APIErrorArgs

Arguments for creating an API Error.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `code` | [`ErrorCodeType`](#errorcodetype) _(optional)_ | - The error code. Defaults to UNKNOWN if not provided. |
| `message` | `string` | - A message describing the error. |
| `extraData` | `string` _(optional)_ | - Optional extra data for logging purposes. |

---

#### APIError

An API Error returned by the Instant Games SDK

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `code` | [`ErrorCodeType`](#errorcodetype) | - The relevant error code |
| `message` | `string` | - A message describing the error |
| `extraData` | `string` _(optional)_ | - Optional extra data for logging purposes |

---

## FBInstant.community



### getName()

Get live stream name

---

### getCVC()

Get live stream concurrent viewer count

---

### getThumbnailURL()

Get video thumbnail URL

---

### getAuthorName()

Get author name

---

### getAuthorPictureURL()

Get author picture URL

---

### getCustomPayload()

Get custom payload

---

### watchAsync()

Open video player overlay

**Throws:**

- `VIDEO_NOT_FOUND`
- `INVALID_OPERATION`
- `INVALID_PARAM`

---

### canGetLiveStreamsAsync()

Check if user can get live streams

**Returns:** `Promise<boolean>` — Returns bool for whether user/game can get live streams

**Throws:**

- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.community.canGetLiveStreamsAsync()
  .then(function(data) {
    console.log(data);
  });
```

---

### canFollowOfficialPageAsync()

Check if user can follow official game page

**Returns:** `Promise<boolean>` — Returns bool for whether user can follow official game page

**Throws:**

- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.community.canFollowOfficialPageAsync()
  .then(function(data) {
    console.log(data);
  });
```

---

### canJoinOfficialGroupAsync()

Check if user can join official game group

**Returns:** `Promise<boolean>` — Returns bool for whether user can join official game group

**Throws:**

- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.community.canJoinOfficialGroupAsync()
  .then(function(data) {
    console.log(data);
  });
```

---

### getLiveStreamsAsync()

Fetch list of live streams tagged with the current game.

**Returns:** `Promise<`[`LiveStream`](#livestream)`>` — A promise that resolves with list of live streams. This rejects if no countent is found or no taggable game associated with this Instant Game.

**Throws:**

- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `LIVE_STREAMS_NOT_FOUND`

**Example:**

```javascript
FBInstant.community.getLiveStreamsAsync({maxCount:1})
  .then(function(liveStreams) {
    console.log(liveStreams);
  });
```

---

### followOfficialPageAsync()

Renders overlay with follow official page CTA

**Returns:** `Promise<void>`

**Throws:**

- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `PAGE_NOT_LINKED`

**Example:**

```javascript
FBInstant.community.followOfficialPageAsync()
```

---

### joinOfficialGroupAsync()

Renders overlay with join group CTA

**Returns:** `Promise<void>`

**Throws:**

- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `GROUP_NOT_LINKED`

**Example:**

```javascript
FBInstant.community.joinOfficialGroupAsync()
```

---

### Types

#### LiveStream

A Live stream.

---

## FBInstant.context

This function determines whether the number of participants in the current

### getID()

A unique identifier for the current game context. This represents a
specific context that the game is being played in (for example, a
facebook post). The identifier will be null if game is being played
in a solo context. This function should not be called until
FBInstant.startGameAsync has resolved.

**Returns:** `?string` — A unique identifier for the current game context.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var contextID = FBInstant.context.getID();
```

---

### getType()

The type of the current game context.
POST - A facebook post.
THREAD - A chat thread.
GROUP - A facebook group.
SOLO - Default context, where the player is the only participant.

This function should not be called until FBInstant.startGameAsync has
resolved.

**Returns:** `('POST'|'THREAD'|'GROUP'|'SOLO')` — Type of the current game context.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var contextType = FBInstant.context.getType();
```

---

### createAsync()

Attempts to create a context between the current player and a specified
 player or a list of players.
This API supports 3 use cases:
1) When the input is a single playerID, it attempts to create or switch
into a context between a specified player and the current player
2) When the input is a list of connected playerIDs, it attempts to create
a context containing all the players
3) When there's no input, a friend picker will be loaded to ask the player
to create a context with friends to play with

For each of these cases, the returned promise will reject if any of the
players listed are not Connected Players of the current player, or if the
player denies the request to enter the new context. Otherwise, the promise
will resolve when the game has switched into the new context.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `suggestedPlayerIDs` | `string \| Array<String>` _(optional)_ | A list of game suggested playerIDs or a single suggested playerID or no input |

**Returns:** `Promise<void>` — A promise that resolves when the game has   switched into the new context, or rejects otherwise.

**Throws:**

- `INVALID_PARAM`
- `SAME_CONTEXT`
- `NETWORK_FAILURE`
- `USER_INPUT`
- `PENDING_REQUEST`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
console.log(FBInstant.context.getID());
// 1122334455
FBInstant.context
  .createAsync('12345678')
  .then(function() {
    console.log(FBInstant.context.getID());
    // 5544332211
  });
```

```javascript
console.log(FBInstant.context.getID());
// 1122334455
FBInstant.context
  .createAsync(['12345678', '87654321'])
  .then(function() {
    console.log(FBInstant.context.getID());
    // 55443322112232
  });
```

```javascript
console.log(FBInstant.context.getID());
// 1122334455
FBInstant.context
  .createAsync()
  .then(function() {
    console.log(FBInstant.context.getID());
    // 55443322112232
  });
```

---

### getPlayersAsync()

Gets an array of [`ContextPlayer`](#contextplayer) objects containing information
about active players in the current context (people who played the game in
the current context in the last 90 days). This may include the current
player.

**Returns:** `Promise<Array<@link `[`ContextPlayer`](#contextplayer)`>>` — A promise that resolves with a   list of context player objects.   NOTE: This function should not be called until FBInstant.initializeAsync()   has resolved.

**Throws:**

- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`
- `INVALID_OPERATION`

**Example:**

```javascript
var contextPlayers = FBInstant.context.getPlayersAsync()
  .then(function(players) {
    console.log(players.map(function(player) {
      return {
        id: player.getID(),
        name: player.getName(),
      }
    }));
  });
// [{id: '123456789', name: 'Luke'}, {id: '987654321', name: 'Leia'}]
```

---

### getName()

Get the player's localized display name.

**Returns:** `?string` — The player's localized display name.

---

### getPhoto()

Get the player's public profile photo.

**Returns:** `?string` — A url to the player's public profile photo

---

### constructor()

Creates a new GameContext instance.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `context` | [`ContextData`](#contextdata) | - The context data to initialize with |

---

### getSize()

Returns the number of participants in this context.

**Returns:** `number|null` — The context size, or null if not available

---

### getContextSizeResponse()

Returns the response from the last context size check.

**Returns:** [`ContextSizeResponse`](#contextsizeresponse)`|null` — The context size response, or null if no check has been performed

---

### setContextSizeResponse()

Sets the response for a context size check.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `contextSizeResponse` | [`ContextSizeResponse`](#contextsizeresponse) | - The response from a context size check |

**Returns:** `void`

---

### Types

#### ContextFilter

A filter that may be applied to a Context Choose operation
'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been
  played in before.
'INCLUDE_EXISTING_CHALLENGES' - Include the "Existing Challenges" section,
  which surfaces actively played-in contexts that the player is a part of.
'NEW_PLAYERS_ONLY' - In sections containing individuals, prefer people who
  have not played the game.

---

#### ContextPlayer

Represents information about a player who is in the context that the
current player is playing in.

---

#### ContextData

Data structure representing a game context.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `id` | `string` _(optional)_ | - The unique identifier for this context |
| `size` | `number` _(optional)_ | - The number of participants in this context |
| `type` | `ContextType` | - The type of context (e.g., SOLO, THREAD, GROUP) |

---

#### ContextSizeResponse

Response object for context size checks.
The answer field is true if the current context size is between
the minSize and maxSize values that are specified in the object,
and false otherwise.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `answer` | `boolean` | - Whether the context size is within the specified range |
| `minSize` | `number` _(optional)_ | - The minimum size specified in the check |
| `maxSize` | `number` _(optional)_ | - The maximum size specified in the check |

---

#### GameContext

Represents the social context in which the game is being played.
This class provides methods to access information about the current game context,
such as its ID, type, and size (number of participants).

---

## FBInstant.payments



### getCatalogAsync()

Fetches the game's product catalog.

**Returns:** `Promise<Array<`[`Product`](#product)`>>` — The set of products that are registered to the game.

**Throws:**

- `CLIENT_UNSUPPORTED_OPERATION`
- `PAYMENTS_NOT_INITIALIZED`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.payments.getCatalogAsync().then(function (catalog) {
  console.log(catalog); // [{productID: '12345', ...}, ...]
});
```

---

### purchaseAsync()

Begins the purchase flow for a specific product.  Will immediately reject
if called before FBInstant.startGameAsync() has resolved.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `purchaseConfig` | [`PurchaseConfig`](#purchaseconfig) | The purchase's configuration details. |

**Returns:** `Promise<`[`Purchase`](#purchase)`>` — A Promise that resolves when the product is successfully purchased by the player. Otherwise, it rejects.

**Throws:**

- `CLIENT_UNSUPPORTED_OPERATION`
- `PAYMENTS_NOT_INITIALIZED`
- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `INVALID_OPERATION`
- `USER_INPUT`

**Example:**

```javascript
FBInstant.payments.purchaseAsync({
  productID: '12345',
  developerPayload: 'foobar',
}).then(function (purchase) {
  console.log(purchase);
  // {productID: '12345', purchaseToken: '54321', developerPayload: 'foobar', ...}
});
```

---

### getPurchasesAsync()

Fetches all of the player's unconsumed purchases. The game must fetch the
current player's purchases as soon as the client indicates that it is ready
to perform payments-related operations, i.e. at game start. The game can then
process and consume any purchases that are waiting to be consumed.

**Returns:** `Promise<Array<`[`Purchase`](#purchase)`>>` — The set of purchases that the player has made for the game.

**Throws:**

- `CLIENT_UNSUPPORTED_OPERATION`
- `PAYMENTS_NOT_INITIALIZED`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.payments.getPurchasesAsync().then(function (purchases) {
  console.log(purchase);
  // [{productID: '12345', ...}, ...]
});
```

---

### consumePurchaseAsync()

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:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `purchaseToken` | `string` | The purchase token of the purchase that should be consumed. |

**Returns:** `Promise<void>` — A Promise that resolves when the purchase has been consumed successfully.

**Throws:**

- `CLIENT_UNSUPPORTED_OPERATION`
- `PAYMENTS_NOT_INITIALIZED`
- `INVALID_PARAM`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.payments.consumePurchaseAsync('54321').then(function () {
  // Purchase successfully consumed!
  // Game should now provision the product to the player
});
```

---

### onReady()

Sets a callback to be triggered when Payments operations are available.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `callback` | `Function` | The callback function to be executed when Payments are available. |

**Example:**

```javascript
FBInstant.payments.onReady(function () {
  console.log('Payments Ready!')
});
```

---

### Types

#### Product

Represents a game's product information.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `title` | `string` | The title of the product |
| `productID` | `string` | The product's game-specified identifier |
| `description` | `string` _(optional)_ | The product description |
| `imageURI` | `string` _(optional)_ | A link to the product's associated image |
| `price` | `string` | The price of the product |
| `priceCurrencyCode` | `string` | The currency code for the product |
| `priceAmount` | `number` | The numeric price of a product |

---

#### Purchase

Represents an individual purchase of a game product.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `developerPayload` | `string` _(optional)_ | A developer-specified string, provided during the purchase of the product |
| `isConsumed` | `boolean` | Whether or not the purchase has been consumed |
| `paymentActionType` | `string` | The current status of the purchase, such as 'charge' or 'refund' |
| `paymentID` | `string` | The identifier for the purchase transaction |
| `productID` | `string` | The product's game-specified identifier |
| `purchasePlatform` | `PurchasePlatform` | The platform associated with the purchase, such as "FB" for Facebook and "GOOGLE" for Google. |
| `purchasePrice` | `Object` | Contains the local amount and currency associated with the purchased item |
| `purchaseTime` | `string` | Unix timestamp of when the purchase occurred |
| `purchaseToken` | `string` | A token representing the purchase that may be used to consume the purchase |
| `signedRequest` | `SignedPurchaseRequest` | Server-signed encoding of the purchase request |

---

#### SignedPurchaseRequest
A signature to verify this object indeed comes from Facebook. The string is
base64url encoded and signed with an HMAC version of your App Secret, based
on the OAuth 2.0 spec.

You can validate it with the following 4 steps:

Split the signature into two parts delimited by the '.' character.
Decode the first part (the encoded signature) with base64url encoding.
Decode the second part (the response payload)  with base64url encoding,
  which should be a string representation of a JSON object that has the
  following fields:
* algorithm - always equals to HMAC-SHA256
* issued_at - a unix timestamp of when this response was issued
* app_id - The game's application ID
* is_consumed - Whether the purchase has been consumed by the player.
* payment_action_type - The current status of the purchase
* payment_id - The identifier for the purchase transaction
* product_id - The product's game-specified identifier
* purchase_price - Contains the local amount and currency associated with
     the purchased item
* purchase_token - A token representing the purchase that may
     be used to consume the purchase
* purchase_time - Unix timestamp of when the purchase occurred
* developer_payload - A developer-specified string, provided
     during the purchase of the product
Hash the whole response payload string using HMAC SHA-256 and your app
  secret and confirm that it is equal to the encoded signature.
You may also wish to validate the issued_at timestamp in the response
  payload to ensure the request was made recently.

Signature validation should only happen on your server. Never do it on the
client side as it will compromise your app secret key.

---

#### PurchaseConfig

The configuration of a purchase request for a product registered to the game.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `productID` | `string` | The identifier of the product to purchase |
| `developerPayload` | `string` _(optional)_ | An optional developer-specified payload, to be included in the returned purchase's signed request. |

---

## FBInstant.player



### getID()

A unique identifier for the player. A Facebook user's player ID will
remain constant, and is scoped to a specific game. This means that
different games will have different player IDs for the same user.
This function should not be called until FBInstant.initializeAsync() has
resolved.

**Returns:** `?string` — A unique identifier for the player.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerID = FBInstant.player.getID();
```

---

### getASIDAsync()

A unique identifier for the player. This is the standard Facebook
Application-Scoped ID which is used for all Graph API calls. If your
game shares an AppID with a native game this is the ID you will see in the
native game too.

**Returns:** `Promise<?string>` — A unique identifier for the player.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerASID = FBInstant.player.getASIDAsync().then(
 asid => console.log(asid);
);
```

---

### getSignedASIDAsync()

A unique identifier for the player. This is the standard Facebook
Application-Scoped ID which is used for all Graph API calls. If your
game shares an AppID with a native game this is the ID you will see in the
native game too.

**Returns:** `Promise<?`[`SignedASID`](#signedasid)`>` — A promise that resolves with a [`SignedASID`](#signedasid) object.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerASID = FBInstant.player.getSignedASIDAsync()
  .then(function (result) {
    result.getASID();
  });
```

---

### getSignedPlayerInfoAsync()

Fetch the player's unique identifier along with a signature that verifies
that the identifier indeed comes from Facebook without being tampered with.
This function should not be called until FBInstant.initializeAsync() has
resolved.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `requestPayload` | `string` _(optional)_ | A developer-specified payload to include in the signed response. |

**Returns:** `Promise<`[`SignedPlayerInfo`](#signedplayerinfo)`>` — A promise that resolves with a [`SignedPlayerInfo`](#signedplayerinfo) object.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
FBInstant.player.getSignedPlayerInfoAsync('my_metadata')
  .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(),
      'GAIN_COINS',
      100);
  });
```

---

### canSubscribeBotAsync()

Returns a promise that resolves with whether the player can subscribe to
the game bot or not.

**Returns:** `Promise<boolean>` — Whether a player can subscribe to the game bot or not. Developer can only call subscribeBotAsync() after checking canSubscribeBotAsync(), and the game will only be able to show the player their bot subscription dialog once per week.

**Throws:**

- `RATE_LIMITED`
- `INVALID_OPERATION`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
// This function should be called before FBInstant.player.subscribeBotAsync()
FBInstant.player.canSubscribeBotAsync().then(
  can_subscribe => console.log(can_subscribe)
);
// 'true'
```

---

### subscribeBotAsync()

Request that the player subscribe the bot associated to the game. The API
will reject if the subscription fails - else, the player will subscribe the
game bot.

**Returns:** `Promise` — A promise that resolves if player successfully subscribed to the game bot, or rejects if request failed or player chose to not subscribe.

**Throws:**

- `INVALID_PARAM`
- `PENDING_REQUEST`
- `CLIENT_REQUIRES_UPDATE`

**Example:**

```javascript
FBInstant.player.subscribeBotAsync().then(
  // Player is subscribed to the bot
).catch(function (e) {
  // Handle subscription failure
});
```

---

### getName()

The player's localized display name. This function should not be called
until FBInstant.initializeAsync() has resolved.

**Returns:** `?string` — The player's localized display name.

**Example:**

```javascript
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerName = FBInstant.player.getName();
```

---

### getPhoto()

A url to the player's public profile photo. The photo will always be a
square, and with dimensions of at least 200x200. When rendering it in the
game, the exact dimensions should never be assumed to be constant. It's
recommended to always scale the image to a desired size before rendering.
The value will always be null until FBInstant.initializeAsync() resolves.

WARNING: Due to CORS, using these photos in the game canvas can cause it
to be tainted, which will prevent the canvas data from being extracted.
To prevent this, set the cross-origin attribute of the images you use to
'anonymous'.

**Returns:** `?string` — Url to the player's public profile photo.

**Example:**

```javascript
var playerImage = new Image();
playerImage.crossOrigin = 'anonymous';
// This function should be called after FBInstant.initializeAsync()
// resolves.
playerImage.src = FBInstant.player.getPhoto();
```

---

### getDataAsync()

Retrieve data from the designated cloud storage of the current player.
Please note that JSON objects stored as string values would be returned back as JSON objects

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `keys` | `Array<string>` | An array of unique keys to retrieve data for. |

**Returns:** `Promise.<Object>` — A promise that resolves with an   object which contains the current key-value pairs for each key   specified in the input array, if they exist.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.player
  .getDataAsync(['achievements', 'currentLife'])
  .then(function(data) {
     console.log('data is loaded');
     var achievements = data['achievements'];
     var currentLife = data['currentLife'];
  });
```

---

### setDataAsync()

Set data to be saved to the designated cloud storage of the current
player. The game can store up to 1MB of data for each unique player.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `data` | `Object` | An object containing a set of key-value pairs   that should be persisted to cloud storage. The object must contain   only serializable values - any non-serializable values will cause   the entire modification to be rejected. |

**Returns:** `Promise` — A promise that resolves when the input values are set.   NOTE: The promise resolving *does not* necessarily mean that the input   has already been persisted. Rather, it means that the data was valid   and has been scheduled to be saved. It also guarantees that all   values that were set are now available in player.getDataAsync.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `PENDING_REQUEST`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.player
  .setDataAsync({
    achievements: ['medal1', 'medal2', 'medal3'],
    currentLife: 300,
  })
  .then(function() {
    console.log('data is set');
  });
```

---

### flushDataAsync()

Immediately flushes any changes to the player data to the designated
cloud storage. This function is expensive, and should primarily be used
for critical changes where persistence needs to be immediate and known
by the game. Non-critical changes should rely on the platform to persist
them in the background.
NOTE: Calls to player.setDataAsync will be rejected while this function's
result is pending.

**Returns:** `Promise` — A promise that resolves when changes have been   persisted successfully, and rejects if the save fails.

**Throws:**

- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `PENDING_REQUEST`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.player
  .setDataAsync({
    achievements: ['medal1', 'medal2', 'medal3'],
    currentLife: 300,
  })
  .then(FBInstant.player.flushDataAsync)
  .then(function() {
    console.log('Data persisted to FB!');
  });
```

---

### getConnectedPlayersAsync()

Fetches an array of ConnectedPlayer objects containing information about
active players (people who played the game in the last 90 days) that are
connected to the current player.

**Returns:** `Promise<Array<`[`ConnectedPlayer`](#connectedplayer)`>>` — A promise that resolves with a   list of connected player objects.   NOTE: This function should not be called until FBInstant.initializeAsync()   has resolved.

**Throws:**

- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
var connectedPlayers = FBInstant.player.getConnectedPlayersAsync()
  .then(function(players) {
    console.log(players.map(function(player) {
      return {
        id: player.getID(),
        name: player.getName(),
      }
    }));
  });
// [{id: '123456789', name: 'Paul Atreides'}, {id: '987654321', name: 'Duncan Idaho'}]
```

---

### constructor()

Creates a new ConnectedPlayer instance.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `playerID` | `string` | - The ID of the connected player. |

---

### getPlayerID()

Get the id of the player.

**Returns:** `string` — The ID of the player

**Example:**

```javascript
FBInstant.player.getSignedPlayerInfoAsync()
  .then(function (result) {
    result.getPlayerID(); // same value as FBInstant.player.getID()
  });
```

---

### getSignature()

A signature to verify this object indeed comes from Facebook. The string is
base64url encoded and signed with an HMAC version of your App Secret, based
on the OAuth 2.0 spec.

You can validate it with the following 5 steps:

1. Split the signature into two parts delimited by the '.' character.
2. Decode the first part (the encoded signature) with base64url encoding.
3. Decode the second part (the response payload) with base64url encoding,
  which should be a string representation of a JSON object that has the
  following fields:
algorithm - always equals to HMAC-SHA256
issued_at - a unix timestamp of when this response was issued.
player_id - unique identifier of the player.
request_payload - the requestPayload string you specified when calling
      FBInstant.player.getSignedPlayerInfoAsync.
4. Hash the whole response payload string using HMAC SHA-256 and your app
  secret and confirm that it is equal to the encoded signature.
5. You may also wish to validate the issued_at timestamp in the response
  payload to ensure the request was made recently.

Signature validation should only happen on your server. Never do it on the
client side as it will compromise your app secret key.

**Returns:** `string` — The signature string.

**Example:**

```javascript
FBInstant.player.getSignedPlayerInfoAsync()
  .then(function (result) {
    result.getSignature();
    // Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ
  });
```

---

### getASID()

Get the app-scoped user id of the player.

**Returns:** `string` — The ID of the player

**Example:**

```javascript
FBInstant.player.getSignedASIDAsync()
  .then(function (result) {
    result.getASID();
  });
```

---

### Types

#### ConnectedPlayer

Represents information about a player who is connected to the current player.

---

#### SignedPlayerInfoData

Data structure containing player information and signature.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `playerID` | `string` | - The unique identifier of the player. |
| `signature` | `string` | - The signature to verify the player information. |

---

#### SignedPlayerInfo

Represents information about the player along with a signature to verify that
it indeed comes from Facebook.

---

#### SignedASIDData

Data structure containing app-scoped user ID and signature.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `asid` | `string` | - The app-scoped user ID of the player. |
| `signed_request` | `string` | - The signature to verify the ASID information. |

---

#### SignedASID

Represents app-scoped user id of current player along with a signature to
verify that it indeed comes from Facebook.

---

## FBInstant.room



### getID()

The unique live match ID.

**Returns:** `string` — The live match ID

**Example:**

```javascript
FBInstant.room.getCurrentMatchAsync()
  .then(function(match) {
    console.log(match.getID());
  });
```

---

### getContextID()

The unique context ID that is associated with this live match.

**Returns:** `string` — The context ID for this live match

**Example:**

```javascript
FBInstant.room.getCurrentMatchAsync()
  .then(function(match) {
    console.log(match.getContextID());
  });
```

---

### showAsync()

Shows the AR effect for the user in the room session. If the user has a
non-game effect applied, it will prompt the user for permission for the
first time. If the user denies, the promise is rejected, otherwise it is
resolved after applying the effect

**Returns:** `Promise<void>` — Resolves when the effect is applied to the player

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`

**Example:**

```javascript
FBInstant.room.loadCameraEffectAsync()
  .then(function(effect) {
    effect.showAsync().then(() => console.log("Effect shown"));
  });
```

---

### getCurrentMatchAsync()

Retrieves the current real-time match for the gameplay environment, if one
exists.

**Returns:** `Promise<`[`LiveMatch`](#livematch)`>` — The current live match being played in this session

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `LIVE_MATCH_NOT_FOUND`

**Example:**

```javascript
FBInstant.room.getCurrentMatchAsync()
  .then(function(match) {
    ...
  });
```

---

### loadCameraEffectAsync()

Retrieves & loads a specified AR effect that has been registered for the game

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `cameraEffectArgs` | [`CameraEffectArgs`](#cameraeffectargs) | The args representing the effect to be loaded. See example for details |

**Returns:** `Promise<`[`CameraEffect`](#cameraeffect)`>` — The AR effect to apply to the player in the call

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `CAMERA_EFFECT_NOT_FOUND`

**Example:**

```javascript
FBInstant.room.loadCameraEffectAsync({effectID: '123'})
  .then(function(effect) {
    ...
  });
```

---

### clearCameraEffectAsync()

Clears the current AR effect in the rooms call. If an effect is present that
was not applied by the game, the player will be prompted to approve the
removal of the effect. The API will resolve after the effect is cleared, or
will reject if the user denies the effect removal.

**Returns:** `Promise<void>` — Resolves if the effect is cleared

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`

**Example:**

```javascript
FBInstant.room.clearCameraEffectAsync()
  .then(function() {
    ...
  });
```

---

### Types

#### CameraEffectArgs

Represents arguments to be sent to load an AR effect in Messenger Rooms.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `effectID` | `string` | The ID of the effect to be loaded that is registered with the game |

---

#### LiveMatch

An instant game live match that is played in a Messenger Rooms call
simultaneously by all the participants.

---

#### CameraEffect

Represents an AR effect object that can be shown in a Messenger Rooms call.

---

## FBInstant.squads



### getID()

The unique gaming squad ID.

**Returns:** `string` — The gaming squad ID

**Example:**

```javascript
FBInstant.squads.getAsync(contextID)
  .then(function(squad) {
    console.log(squad.getID());
  });
```

---

### getName()

The gaming squad name.

**Returns:** `string` — The name of the squad

**Example:**

```javascript
FBInstant.squads.getAsync(contextID)
  .then(function(squad) {
    console.log(squad.getName());
  });
```

---

### getImage()

The URI for the gaming squad image.

**Returns:** `string` — URI for gaming squad image

**Example:**

```javascript
FBInstant.squads.getAsync(contextID)
  .then(function(squad) {
    console.log(squad.getImage());
  });
```

---

### getContextID()

The unique context ID that is associated with this gaming squad.

**Returns:** `string` — The context ID for this gaming squad

**Example:**

```javascript
FBInstant.squads.getAsync(id)
  .then(function(squad) {
    console.log(squad.getContextID());
  });
```

---

### joinAsync()

Brings up a dialog for the player to join a Squad if they are not part of it. If the user accepts, they become part
of the squad thread and the game context switches into the squad. If they are part of the Squad already,
the dialog will prompt the user to switch into the Squad context.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | `@link `[`JoinGamingSquadPayload`](#joingamingsquadpayload) | An optional configuration object for the join dialog of the squad |

**Returns:** `Promise<void>`

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `USER_INPUT`

**Example:**

```javascript
FBInstant.squads.getAsync(squadID)
  .then(function(squad) {
    squad.joinAsync().then(...)
  });
```

---

### leaveAsync()

Brings up a dialog for the player to confirm if they want to leave the Squad.
If the player confirms, they are removed from the Squad and the messenger thread that is associated with this Squad.

**Returns:** `Promise<void>`

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `USER_INPUT`

**Example:**

```javascript
FBInstant.squads.getAsync(squadID)
  .then(function(squad) {
    squad.leaveAsync().then(...)
  });
```

---

### addToSquadAsync()

Brings up a dialog for the player to add their friends to the current squad.

**Returns:** `Promise<void>`

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `USER_INPUT`

**Example:**

```javascript
FBInstant.squads.getAsync(squadID)
  .then(function(squad) {
    squad.addToSquadAsync().then(...)
  });
```

---

### createAsync()

Brings up a dialog for the player to create a Squad. If the player creates the Squad, the promise will resolve
with the new Squad instance and the game session will be switched into this newly created Squad context.
The promise will reject if the player closes the dialog instead

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | `@link `[`CreateGamingSquadPayload`](#creategamingsquadpayload) | An optional configuration object for the creation of the squad |

**Returns:** `Promise<`[`GamingSquad`](#gamingsquad)`>` — The gaming squad created by the player

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`
- `USER_INPUT`

**Example:**

```javascript
FBInstant.squads.createAsync()
  .then(function(squad) {
    ...
  });
```

---

### getAsync()

Fetch an existing Squad. If the Squad does not exist, or the player cannot
interact with the Squad, this API will reject with the GAMING_SQUAD_NOT_FOUND error code.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | `string` | The squad ID or context ID |

**Returns:** `Promise<`[`GamingSquad`](#gamingsquad)`>` — The gaming squad created by the player

**Throws:**

- `GAMING_SQUAD_NOT_FOUND`
- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.squads.getAsync(squadID)
  .then(function(squad) {
    console.log(squad.getID())
  });
```

---

### getPlayerSquadsAsync()

Fetches the current player's existing squads, if any.

**Returns:** `Promise<Array<`[`GamingSquad`](#gamingsquad)`>>` — The gaming squads the current player is in

**Throws:**

- `GAMING_SQUAD_NOT_FOUND`
- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.squads.getPlayerSquadsAsync()
  .then(function(squads) {
    squads.forEach(squad => console.log(squad.getID()));
  });
```

---

### canUseSquadsAsync()

Fetches the current player's existing squads, if any.

**Returns:** `Promise<boolean>` — Returns whether the current user is eligible to use squads

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.squads.canUseSquadsAsync()
  .then(function(isEligible) {
    if (isEligible) {
     FBInstant.squads.getAsync(squadID)
      .then(function(squad) {
      console.log(squad.getID())
    });
    }
  });
```

---

### Types

#### GamingSquad

Representation of a group of players playing together in a messenger thread

---

#### CreateGamingSquadPayload

Represents parameters used to configure a Gaming Squad

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | An optional prefill for the squad name input in the creation dialog. The player ultimately has control over the actual name. |
| `image` | `string` | Optional base64 encoded image that will be   associated with the gaming squad and will show up in the creation dialog. It will be the profile icon for the Messenger thread |
| `squadTerm` | `string` | Optional localized term to use in place of 'Squad' in the dialog. |

---

#### JoinGamingSquadPayload

Represents parameters used to configure the Join dialog

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `squadTerm` | `string` | Optional localized term to use in place of 'Squad' in the dialog. |

---

#### LeaveGamingSquadPayload

Represents parameters used to configure the Leave dialog

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `squadTerm` | `string` | Optional localized term to use in place of 'Squad' in the dialog. |

---

#### AddToGamingSquadPayload

Represents parameters used to configure the Add to Squad dialog

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `squadTerm` | `string` | Optional localized term to use in place of 'Squad' in the dialog. |

---

## FBInstant.tournament



### postScoreAsync()

Posts a player's score to Facebook. This API should only be called within a
tournament context at the end of an activity (example: when the player doesn't
have "lives" to continue the game). This API will be rate-limited when called too
frequently. Scores posted using this API should be consistent & comparable
across game sessions. For example, if Player A achieves 200 points in a
session, and Player B achieves 320 points in a session, those two scores
should be generated from activities where the scores are fair to be
compared and ranked against each other.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `score` | `number` | An integer value representing the player's score at   the end of an activity. |

**Returns:** `Promise<void>` — A promise that resolves when the score post is completed.

**Throws:**

- `INVALID_PARAM`
- `TOURNAMENT_NOT_FOUND`
- `NETWORK_FAILURE`

**Example:**

```javascript
function onScore(score) {
  if (score > bestScore) {
    bestScore = score;
    FBInstant.tournament.postScoreAsync(bestScore)
      .then(function() {
        ...
      });
  }
}
```

---

### createAsync()

Opens the tournament creation dialog if the player is not currently in a tournament session

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | `@link `[`CreateTournamentPayload`](#createtournamentpayload) | Specifies the payload for the creation of the tournament |

**Returns:** `Promise<@link `[`Tournament`](#tournament)`>` — A promise that resolves if the tournament creation is a success, or rejects otherwise

**Throws:**

- `INVALID_PARAM`
- `INVALID_OPERATION`
- `DUPLICATE_POST`
- `NETWORK_FAILURE`
- `OPERATION_SUPPRESSED`

---

### shareAsync()

Opens the reshare tournament dialog if the player is currently in a
tournament session

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | [`ShareTournamentPayload`](#sharetournamentpayload) | Specifies share content. See example for   details. |

**Returns:** `Promise<void>` — A promise that resolves if the tournament is shared, or   rejects otherwise.

**Throws:**

- `INVALID_OPERATION`
- `TOURNAMENT_NOT_FOUND`
- `NETWORK_FAILURE`

**Example:**

```javascript
FBInstant.tournament.shareAsync({
  score: 3,
  data: { myReplayData: '...' }
}).then(function() {
  // continue with the game.
});
```

---

### joinAsync()

Request a switch into a specific tournament context. If the player is not a
participant of the tournament, or there are not any connected players
participating in the tournament, this will reject. Otherwise, the promise
will resolve when the game has switched into the specified context.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | `string` | The Tournament ID of the desired context to switch into. |

**Returns:** `Promise<void>` — A promise that resolves when the game has   switched into the specified tournament context, or rejects otherwise.

**Throws:**

- `INVALID_OPERATION`
- `INVALID_PARAM`
- `SAME_CONTEXT`
- `NETWORK_FAILURE`
- `USER_INPUT`
- `TOURNAMENT_NOT_FOUND`

**Example:**

```javascript
FBInstant.getTournamentAsync().then((tournament) => {
   console.log(tournament.getID());
});
// 1122334455
FBInstant.tournament
  .joinAsync('1122334455')
  .then(function() {
     // Context switch completed successfully.
  });
```

---

### getTournamentsAsync()

Returns a list of eligible tournaments that can be surfaced in-game, including
tournaments 1) the player has created; 2) the player is participating in; 3)
the player's friends (who granted permission) are participating in.
The instant tournaments returned are active. An instant tournament is expired
if its end time is in the past. For each instant tournament, there is only
one unique context ID linked to it, and that ID doesn't change.

**Returns:** `Promise<Array<@link `[`Tournament`](#tournament)`>>` — A promise that resolves if the tournaments are fetched, or rejects otherwise.

**Throws:**

- `NETWORK_FAILURE`
- `INVALID_OPERATION`

**Example:**

```javascript
FBInstant.tournament.getTournamentsAsync()
 .then(tournaments => {
   // tournament list
 });
```

---

### Types

#### CreateTournamentConfig

Represents the configurations used in creating an Instant Tournament

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `title` | `string` _(optional)_ | Optional text title for the tournament, please do not include user names in title. |
| `forceScoreValidation` | `boolean` _(optional)_ | Optional boolean that specifies   if the tournament requires game server validation before a score can be   added to or updated on the leaderboard. |
| `image` | `string` _(optional)_ | Optional base64 encoded image that will be   associated with the tournament and included in posts sharing the tournament |
| `sortOrder` | `string` _(optional)_ | Optional input for the ordering of which score   is best in the tournament. The options are 'HIGHER_IS_BETTER' or   'LOWER_IS_BETTER'. If not specified, the default is 'HIGHER_IS_BETTER'. |
| `scoreFormat` | `string` _(optional)_ | Optional input for the formatting of the   scores in the tournament leaderboard. The options are 'NUMERIC' or 'TIME'.   If not specified, the default is 'NUMERIC'. |
| `endTime` | `number` _(optional)_ | Optional input for setting a custom end time   for the tournament. The number passed in represents a unix timestamp.   If not specified, the tournament will end one week after creation. |
| `forceScoreRangeValidation` | `boolean` _(optional)_ | Optional boolean that specifies  if the tournament should use score range validation.  If true, then minimum and/or  maximum scores should be provided; scores falling outside the range will be automatically  rejected.  If either minimum or maximum is null, then that side of the range will be ignored. |
| `minimumScore` | `number` _(optional)_ | Optional input will only be used if forceScoreRangeValidation is true. If it is, scores below this will be automatically rejected.  If null or forceScoreRangeValidation is false, no minimum will be used |
| `maximumScore` | `number` _(optional)_ | Optional input will only be used if forceScoreRangeValidation is true. If it is, scores above this will be automatically rejected.  If null or forceScoreRangeValidation is false, no maximum will be used |

---

#### CreateTournamentPayload

Represents content used to create an Instant Tournament

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `initialScore` | `number` | An integer value representing the player's   score which will be the first score in the tournament. |
| `config` | `@link `[`CreateTournamentConfig`](#createtournamentconfig) | An object holding optional   configurations for the tournament |
| `data` | `Object` _(optional)_ | A blob of data to attach to the update. All game   sessions launched from the update will be able to access this blob through   FBInstant.getEntryPointData(). Must be less than or equal to 1000   characters when stringified. |

---

#### ShareTournamentPayload

Represents content used to reshare an Instant Tournament.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `score` | `number` | An optional integer value representing the player's   latest score. |
| `data` | `Object` _(optional)_ | A blob of data to attach to the update.    Must be less than or equal to 1000 characters when stringified. |

---