# "Instant Games SDK v8.0: FBInstant.player"


See [Instant Games SDK v8.0](https://developers.facebook.com/documentation/games/sdk-reference/v8.0) for the SDK overview, changelog, and root `FBInstant` reference.

## 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()

NOTE: This function will only return ASIDs for users migrating over from your canvas app or for users that had previously accepted Terms of Service for you game. You should rely on player ID for all of your use cases.

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);
);
```

---

### getAgeCategoryAsync()

Returns the age category of the current player.
The age category is determined by the player's date of birth and can be
used to enable age-appropriate content and features in your game.

**Returns:** `Promise<string>` — A promise that resolves with the age category string:   - 'TN' (Teen): Player is 13-17 years old   - 'AD' (Adult): Player is 18+ years old   - 'UNKNOWN': Age information is not available

**Throws:**

- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.player.getAgeCategoryAsync()
  .then(function(ageCategory) {
    if (ageCategory === 'TN') {
      disableAdultContent();
    }
  });
```

---

### getSignedASIDAsync()

NOTE: This function will only return ASIDs for users migrating over from your canvas app or for users that had previously accepted Terms of Service for you game. You should rely on player ID for all of your use * cases.
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();
  });
```

---

### getSignedAssociatedAppsASIDAsync()

Returns a list of associated apps and their corresponding ASIDs with
signatures for the current player. Associated apps are pre-approved
Instant Games, native apps, or Canvas Games linked to the current game.
Each entry includes a cryptographic signature so your server can verify
that the ASID came from Facebook and was not tampered with.

**Returns:** `Promise<?Array<`[`SignedAssociatedAppASID`](#signedassociatedappasid)`>>` — A promise that resolves with an array of [`SignedAssociatedAppASID`](#signedassociatedappasid) objects, or `null` if no associated apps exist.

**Throws:**

- `NETWORK_FAILURE`
- `CLIENT_UNSUPPORTED_OPERATION`

**Example:**

```javascript
FBInstant.player.getSignedAssociatedAppsASIDAsync()
  .then(function(associatedApps) {
    if (associatedApps) {
      associatedApps.forEach(function(app) {
        console.log('App ID: ' + app.getAppID());
        console.log('ASID: ' + app.getASID());
        console.log('Signature: ' + app.getSignature());
      });
    }
  });
```

---

### 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'
```

---

### isSubscribedBotAsync()

Returns a promise that resolves with whether the player is already
subscribed to the game bot or not.

**Returns:** `Promise<boolean>` — Whether a player is already subscribed to the game bot or not. This is to perform custom logic for players who are subscribed to the game bot. To check whether to prompt the user to subscribe, canSubscribeBotAsync should be used instead.

**Example:**

```javascript
FBInstant.player.isSubscribedBotAsync()
  .then(function (isSubscribed) {
    // Custom logic
  })
)
```

---

### 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
});
```

---

### 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 player IDs of active
players (people who played the game in the last 90 days) that are connected
to the current player.

**Returns:** `Promise<Array<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(),
      }
    }));
  });
// [{id: '123456789'}, {id: '987654321'}]
```

---

### createNEZPNotificationContentAsync()

Creates notification content for use in a Network Enabled Zero Permissions (NEZP) environment. The content includes an image overlay rendered from XML/CSS, a title, an optional subtitle, and optional initial data. The generated image and text are stored on Meta servers and can be referenced later when sending notifications via the A2U Graph API. See more details in the [A2U API](https://developers.facebook.com/documentation/games/retain/notifications/a2u-api).

This function should not be called until `FBInstant.initializeAsync()` has resolved.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `payload` | `CreateNEZPNotificationContentPayload` | The notification content payload object. See properties below. |

**Payload properties:**

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `imageOverlayPath` | `string` | Yes | Path to the XML overlay view file that defines the notification image layout. |
| `pathToCSS` | `string` | Yes | Path to the CSS file for styling the overlay view. |
| `notificationTitle` | `string` | Yes | The notification title. Supports template tokens such as `{{FBInstant.player.name}}`. |
| `notificationSubtitle` | `string` | No | An optional subtitle for the notification. |
| `initialData` | `Object` | No | Optional developer-defined data passed to the overlay view for rendering. |
| `recipients` | `Array<string>` | No | Player IDs of valid recipients. Recipients must be part of the current game context. |

**Returns:** `Promise<string>` — A promise that resolves with a `notification_content_id` string. Use this ID with the notifications Graph API to send the notification to the specified recipients.

**Throws:**

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

**Example:**

```javascript
await FBInstant.player.createNEZPNotificationContentAsync({
  imageOverlayPath: 'ig_views/profile_view.xml',
  pathToCSS: 'ig_views/styles.css',
  initialData: {wordSubmitted: 'APPLE'},
  notificationTitle: '{{FBInstant.player.name}} just took their turn!',
  notificationSubtitle: 'It is your turn now!',
  recipients: ['6719542978151885'],
}).then((notificationContentId) =>
  console.log('Notification content created with ID: ' + notificationContentId)
).catch((error) =>
  console.error('Failed to create notification:', error.code, error.message)
);
```

---

## Types

### SignedPlayerInfo

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

#### 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
  });
```

---

### 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. |

---

### SignedASID

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

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

---

#### 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.
asid - the app-scoped user id of the player.
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.getSignedASIDAsync()
  .then(function (result) {
    result.getSignature();
  });
```

---

### 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. |

---

### SignedAssociatedAppASID

Represents an associated app ID and ASID for the current player along with
a signature to verify that the data indeed comes from Facebook.

#### getAppID()

Get the associated app ID.

**Returns:** `string` — The associated app ID

**Example:**

```javascript
FBInstant.player.getSignedAssociatedAppsASIDAsync()
  .then(function(associatedApps) {
    if (associatedApps) {
      associatedApps.forEach(function(app) {
        console.log('App ID: ' + app.getAppID());
      });
    }
  });
```

---

#### getASID()

Get the app-scoped user ID for the associated app.

**Returns:** `string` — The ASID for the associated app

---

#### getSignature()

Get the signature to verify the associated app ASID information.

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

---

### SignedAssociatedAppASIDData

Data structure containing associated app ID, app-scoped user ID, and
signature.

**Properties:**

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

---