Scores & Achievements

Overview

When building a social game, it's common to compare players' progress with that of their friends. This is a great way to encourage social competition, and Facebook offers tools to encourage this competition, in the form of the Scores API and the Achievements API.

The Scores API and Achievements API make it easy to build social leaderboards, persist player scores and award achievements to players in a social and cross-platform format. With the Scores API, you can store and reset a player's high-score and pull back a list of their friends' scores to populate a leaderboard. With the Achievements API, you can define a list of custom achievements that players can complete in your game, along with a score value that can be earned with each achievement.

A leaderboard in Friend Smash!, which uses the Scores API

Both the Scores API and Achievements API are only available for apps that are categorized as Games.

Because these API let developers write information about player game state to the Graph API, they both require publish_actions permissions, which is subject to Login Review. To retrieve Score and Achievement information about a player's friends, both the player and their friends need to grant the user_friends permission.

Scores API

The Graph API for Scores lets game developers build social leaderboards and game-matching by storing players' scores as they play. These scores will appear on players' timelines and in the Games Feed on Facebook. Both the User object and the Application object on the Graph API have a scores connection that allows lets you manage and retrieve scores for players of your game.

Reading a Player's Score

You can read the score for a person playing your game by issuing a HTTP GET request to /USER_ID/scores with a user access_token. If the player has granted your app the user_games_activity permission then this call will give you the latest scores for all supported games for that player. Otherwise it will give you scores only for your games.

The API returns an array of objects containing the following data:

Name Description Type

user

Player associated with the scores

Object containing the name and id for the player

score

Numeric score

integer

application

App associated with the score

Object containing the name and id of the app

type

type of the data which is score

string

Read Scores for Players and Friends

You can read the set of scores for a player and their friends by issuing an HTTP GET request to/APP_ID/scores with the user access_token for that app. The user_friends permission is required in order to view friends' scores. This returns a list of scores for a player and friends who have authorized the app.

The list is sorted by descending score value, so it returns friends with the highest scores first. You can use this call to generate a leader board for a player and friends. The API returns an array of objects containing the following data:

Name Description Type

user

Player associated with the scores

Object containing the name and id for the player

score

Numeric score

integer

application

App associated with the score

Object containing the name and id of the app

type

type of the data which is score

string

Create or Update a Player's Score

You can post a score for a player by issuing an HTTP POST request to /USER_ID/scores with a user access_token, as long as the player has granted the publish_actions permission for your app.

Name Description Type Required

score

Numeric score with value > 0

integer

Yes

Here's the return value:

Description Type

Whether the write succeeded

boolean

Delete Scores for a Player

You can delete the score for a player for your app by issuing an HTTP DELETE request to /USER_ID/scoreswith a user or app access_token as long as the player has granted the publish_actions permission for your app.

The response looks like this:

Description Type

true or error depending on whether the delete was successful

boolean

Delete All Scores for the App

You can delete all the scores for your app by issuing an HTTP DELETE request to /APP_ID/scores with the app access_token for that app. This will reset the scores for your app. Use this if you'd like to periodically reset your game's scores and leader boards.

Here's the response:

Description Type

true or error depending on whether the delete was successful

boolean

Achievements API

The Graph API for Achievements enables you to publish achievements in your game and reward players with scores for completing those achievements.

To award an achievement to a player, it's necessary to define some Open Graph objects of type game.achievement. Your in-game achievements should follow these guidelines:

  • Each achievement has points associated with it.
  • Each game can use a total of 1000 points to distribute across all their achievements.
  • Each game can use a maximum of 1000 achievements.
  • People using a game can achieve a particular achievement for that game only once.

Apps should aim for between 50-100 achievements consisting of a mix of 50- (difficult), 25- (medium), and 10- (easy) point value achievements.

Note: Facebook policy requires that you never delete an achievement, except in the case of testing achievements.

Defining Achievement Types

Each achievement type must possess a unique URL with the appropriate Open Graph protocol metatags. Facebook will scrape the achievement type’s unique URL and can use the information provided in the tags to generate stories in News Feed and on a players' Profile. Clicking these stories will redirect to the achievement type’s unique URL.

When defining an achievement type URL consider that, if it is a child of your Canvas URL, the achievement type URL will automatically be rewritten as child of your Canvas Page alias. See Hosting Games on Facebook for more detail on how this works.

Achievement Type Object Tags

Name Description Required

og:type

The value should be game.achievement.

Yes

title

Title of the achievement type.

Yes

og:url

The unique URL of the achievement type.

Yes

og:description

Description of achievement type. Should explain how the achievement is earned.

Yes

og:image

An image URL which should represent your object within the graph. The image must be at least 200-by-200 pixels and have a maximum aspect ratio of 3:1. PNG, JPEG and GIF formats are supported. You may include multiple og:image tags to associate multiple images with your page.

Yes

game:points

Number of points the achievement type is worth. Total points per game may not exceed 1000 points limit, which we enforce.

Yes

fb:app_id

The App ID that owns this achievement type.

Yes

Creating, Reading and Deleting

You can create new acheivement types, read the existing list of types, and delete types by using the Graph API/{app-id}/achievements edge.

Update

You can update the metatag property values of an achievement type by forcing a re-scrape of its Open Graph URL using the Open Graph Debugger. After a significant number of players have collected this achievement, the property values are locked and cannot be edited.

You can update the custom properties of an achievement type (for example, display_order) by using theGraph API /{app-id}/achievements edge.

Managing Player Achievements

You can publish a new achievement for a player, read the achievements that a player has already collected, or delete an achievement collected by a player using the Graph API /{user-id}/achievements edge.

Publish a New Achievement

To publish a new achievement, make a POST request to /me/achievements while providing the ID of a previsouly defined achievement:

/* Replace {achievement-id} with the ID of your achievement. */
FB.api(
    "/me/achievements",
    "POST",
    {
        "achievement": "{achievement-id}"
    },
    function (response) {
      if (response && !response.error) {
        /* Verify the achievement was published. */
      }
    }
);
POST /me/achievements HTTP/1.1
Host: graph.facebook.com

achievement=%7Bachievement-id%7D
/* PHP SDK v5.0.0 */
/* Replace {achievement-id} with the ID of your achievement. */
$request = new FacebookRequest(
  $session,
  'POST',
  '/me/achievements',
  array (
    'achievement' => '{achievement-id}',
  )
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* Verify the achievement was published. */
Bundle params = new Bundle();
params.putString("achievement", "{achievement-id}");
/* Replace {achievement-id} with the ID of your achievement. */
new GraphRequest(
    AccessToken.getCurrentAccessToken(),
    "/me/achievements",
    params,
    HttpMethod.POST,
    new GraphRequest.Callback() {
        public void onCompleted(GraphResponse response) {
            /* Verify the achievement was published. */
        }
    }
).executeAsync();
// For more complex open graph stories, use `FBSDKShareAPI`
// with `FBSDKShareOpenGraphContent`
NSDictionary *params = @{
  @"achievement": @"{achievement-id}",
};
/* Replace {achievement-id} with the ID of your achievement. */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                               initWithGraphPath:@"/me/achievements"
                                      parameters:params
                                      HTTPMethod:@"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    // Handle the result
}];

Get a Persons's Achievements

To get a list of a person's achievements, simply call the same endpoint using a GET request:

/* make the API call */
FB.api(
    "/me/achievements",
    function (response) {
      if (response && !response.error) {
        /* handle the result */
      }
    }
);
GET /me/achievements HTTP/1.1
Host: graph.facebook.com
/* PHP SDK v5.0.0 */
/* make the API call */
$request = new FacebookRequest(
  $session,
  'GET',
  '/me/achievements'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
/* make the API call */
new GraphRequest(
    AccessToken.getCurrentAccessToken(),
    "/me/achievements",
    null,
    HttpMethod.GET,
    new GraphRequest.Callback() {
        public void onCompleted(GraphResponse response) {
            /* handle the result */
        }
    }
).executeAsync();
// For more complex open graph stories, use `FBSDKShareAPI`
// with `FBSDKShareOpenGraphContent`
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                               initWithGraphPath:@"/me/achievements"
                                      parameters:params
                                      HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    // Handle the result
}];

Remove a Person's Achievement

To remove a previsouly published achievement call /me/achievements using a DELETE request and provide the ID the achievement you want to remove:

/* Replace {achievement-id} with the ID of your achievement. */
FB.api(
    "/me/achievements",
    "DELETE",
    {
        "achievement": "{achievement-id}"
    },
    function (response) {
      if (response && !response.error) {
        /* Verify the achievement was deleted. */
      }
    }
);
DELETE /me/achievements HTTP/1.1
Host: graph.facebook.com

achievement=%7Bachievement-id%7D
/* PHP SDK v5.0.0 */
/* Replace {achievement-id} with the ID of your achievement. */
$request = new FacebookRequest(
  $session,
  'DELETE',
  '/me/achievements',
  array (
    'achievement' => '{achievement-id}',
  )
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* Verify the achievement was deleted. */
Bundle params = new Bundle();
params.putString("achievement", "{achievement-id}");
/* Replace {achievement-id} with the ID of your achievement. */
new GraphRequest(
    AccessToken.getCurrentAccessToken(),
    "/me/achievements",
    params,
    HttpMethod.DELETE,
    new GraphRequest.Callback() {
        public void onCompleted(GraphResponse response) {
            /* Verify the achievement was deleted. */
        }
    }
).executeAsync();
// For more complex open graph stories, use `FBSDKShareAPI`
// with `FBSDKShareOpenGraphContent`
NSDictionary *params = @{
  @"achievement": @"{achievement-id}",
};
/* Replace {achievement-id} with the ID of your achievement. */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                               initWithGraphPath:@"/me/achievements"
                                      parameters:params
                                      HTTPMethod:@"DELETE"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    // Handle the result
}];