Facebook Developers
DocsToolsSupportNewsApps
Log In
  • Social Plugins
  • Facebook Login
  • Open Graph
  • Facebook APIs
  • Games
  • Media
  • Payments
  • App Center
  • Promote Your App
  • iOS
  • Android
  • Web
  • Technology Partners
  • Getting Started
    • Apps on Facebook Overview
    • Canvas Tutorial
    • Games on Facebook Tutorial
    • 1 - Authenticate
    • 2 - Personalize
    • 3 - Invites and Requests
    • 4 - Bragging and News Feed
    • 5 - Publish Open Graph
  • Best Practices
    • Integrating with Canvas
  • How Tos
    • Fluid Canvas
    • Feed Gaming
    • Using hideFlashCallback
  • Reference
    • fb_source Parameter

5 - Publish Open Graph

Documentation › Games on Facebook Tutorial › 5 - Publish Open Graph

In this tutorial, you'll bring everything together and publish an Open Graph story.

While the previous brag post used the Feed Dialog to submit free-form text, with Open Graph you publish structured content about a player's activity to their Timeline. With this data, Facebook generates aggregation stories which appears on a user's Timeline and in News Feed, giving your game better visibility and distribution on Facebook.

This tutorial walks through these steps:

  1. Publish scores with the Graph API
  2. Publish achievements with the Graph API
  3. Create custom actions and objects

Step 1: Publish scores with the Graph API

The Graph API for Scores allows you to publish scores from your game to Facebook.

The process is simple. Each time a player achieves a score in the game, an HTTP post request is issued to https://graph.facebook.com/PLAYER_ID/scores with a User Access Token. Assuming the player has granted the publish_actions permission, their score will post to the graph

From there, Facebook can automatically generate several interesting stories, including high score stories when the player reaches a new high score, and passing stories when the player overtakes a friend in the game.

Score passing story High-score story

Open up the ui.js file and look for a method named sendScore(). This method executes at the end of each game. Copy and paste in the following code to enable the sending of scores:

if (gScore) {
    console.log("Posting score to Facebook");
    FB.api('/me/scores/', 'post', { score: gScore }, function(response) {
        console.log("Score posted to Facebook");
    });
}

This code first checks to make sure the player has a valid score, then it issues an HTTP POST request to the url https://graph.facebook.com/PLAYER_ID/scores through the convenience method FB.api in the Javascript SDK. We include the score as a parameter in a dictionary with the key as score. You don't need to do anything with the returned response; it just returns 'true'. You can leave the completion callback empty, however, the example shown confirms that the score was posted by logging to the debug console.

Now, Facebook will generate high score and passing stories automatically for Friend Smash. They look great on a player's Timeline and give your game more distribution. For more info, refer to the documentation on the Graph API for Scores.

Step 2: Publish achievements with the Graph API

The Graph API for Achievements works in parallel to the Graph API for Scores and enables achievement stories for players in a game.

As with scores, the publishing process is straightforward and allows Facebook to automatically generate stories with a badge that a player can show off to friends. Achievements can only be earned once per-player, so it's worth making them occur at noteworthy moments in the game. As with the Graph API for Scores, the stories are generated automatically. When coupled with high-quality game art, these stories can really add extra visibility to your game on Facebook.

There are a couple of additional steps required to make achievements work. Let's walk through those now.

Define an achievement

Achievements exist as Open Graph objects on the web (Read more about Open Graph objects here). They follow the same Open Graph markup style as a normal OG object. For full documentation, see the Graph API for Achievements page. Let's start by creating a first achievement, which players win after smashing 50 or more friends.

Create a new html document with this content:

<html>
    <head>
    <meta property="og:type" content="game.achievement"/>
    <meta property="og:title" content="50 Score!"/>
    <meta property="og:description" content="Smash 50 friends in 1 round"/>
    <meta property="og:url" content="http://www.friendsmash.com/opengraph/achievement_50.html"/>
    <meta property="og:image" content="http://www.friendsmash.com/opengraph/images/achievement_50.png"/>
    <meta property="game:points" content="50"/>
    <title>Friend Smash! - Achivement: 50 Score!</title>
</head>
<body>
    <p>Friend Smash! - Achivement: 50 Score!</p>
    <img src="http://www.friendsmash.com/opengraph/images/achievement_50.png" />
</body>
</html>

This contains the definition for our achievement object. Save the file, naming it something appropriate (suggested: achievement_50.html) and upload it to the public web. Be sure to change the og:url parameter to match the name and location of this html file on the web. Also, upload the achievement_50.png image file, which you can find in the friendsmash/images directory of the sample package and update the og:image tag to match the image's location on the web.

Take note of the game:points meta property tag. This tag is specific to achievements and defines the relative worth of that achievement in the game. You're given 1000 points to distribute across all the achievements in your game, so make sure to set the weight for each achievement appropriately based on difficulty or rarity.

Once your changes are complete, save the file and upload it to the web.

You can use the Facebook Open Graph Debug Tool to ensure Facebook can read your achievement correctly. Input your achievement URL into the tool and click debug. The object should lint without errors, and your result should look like this:

Object debugger

Register the achievement

Once the achievement object exists on the web, register it with Facebook so that it can be earned in the game. This is achieved by sending a HTTP POST request to the graph, as follows:

POST https://graph.facebook.com/APP_ID/achievements?achievement=http://www.friendsmash.com/opengraph/achievement_50.html&access_token=APP_ACCESS_TOKEN

Replace APP_ID with the App ID given to you when you set up the app. Replace the achievement=... URL with the location of your achievement on the web. Replace the APP_ACCESS_TOKEN with an App Access Token for your app. An App Access Token is a key, signed with your app's secret that you required to make changes on behalf of your app. Full details as to how to obtain an App Access token are detailed here.

Optionally, make use of the Facebook Graph API Explorer tool, which will assist you to send the HTTP POST request required to register the achievement.

Be aware too, the 1000 point limit for achievements is enforced here, and that achievements can only be registered for apps categorized as Games. If you receive the error message: (#3) Method allowed only for games, make sure you set your app's category to Games in the App Details section of your developer app settings.

Earn the achievement

Once the achievement object is created and registered, a player can achieve it in the game. Further down in the ui.js file, you should see a method named sendAchievement(kAchievement). This method is called in Friend Smash when an achievement should be earned (ex: when the player first scores over 50 points). Copy and paste the following code to enable the achievements to be published to Facebook:

var achievementURLs = Array();
achievementURLs[0] = "http://www.friendsmash.com/achievement_50.html";
achievementURLs[1] = "http://www.friendsmash.com/achievement_100.html";
achievementURLs[2] = "http://www.friendsmash.com/achievement_150.html";
achievementURLs[3] = "http://www.friendsmash.com/achievement_200.html";
achievementURLs[4] = "http://www.friendsmash.com/achievement_x3.html";

FB.api('/me/achievements/', 'post', { achievement: achievementURLs[kAchievement] }, function(response) {
    console.log("Achievement posted");
});

This code follows the same FB.api pattern as you've seen previously in this tutorial. You're essentially doing an HTTP post to https://graph.facebook.com/PLAYER_ID/ with the User Access Token for permission, and the achievement parameter with the URL of our achievement object. Change the URL of the achievement object to be the location of the new object you uploaded to the web and registered in the previous step.

As an additional task, create, upload and register the other achievement OG objects, for when players reach a score of 100, 150, 200, and for when a player smashes 3 friends at once.

Now, once a player achieves a score of 50 or more, the achievement will publish to Facebook and a story like the one below will be automatically generated. Note, if 50 is proving too difficult to achieve, either continue practicing smashing friends, or cheat by altering the code around the call sendAchievement(kAchievements.kACHIEVEMENT_SCORE50); inside game.js.

Achievement

Step 3: Create custom actions and objects

You can further build out the Open Graph implementation for Friend Smash by implementing custom objects and actions that map to specific events in the game. You can map several actions inside Friend Smash, but perhaps the most obvious one to start with is to post to the graph that a player smashed (action) a friend (object).

Actions and objects are first defined in the Open Graph settings section of the App Dashboard. Edit the settings for your app by navigating to your apps on the Facebook Developer site and clicking edit settings for the Friend Smash app you made.

In the left nav, click the 'Open Graph' tab. This brings you to a page with an overview of your Open Graph actions and objects. As you haven't configured anything yet, this should be empty.

Let's start by creating a friend object by clicking the 'Create New Object Type' button in the 'Object Types' subsection of the page. The dialog that pops up prompts you to enter the name of an object that exists in your game. You could enter 'friend' here, but Facebook already has an object to represent a friend in the social graph: 'profile'. If you click in the 'Object Type Name' box, you'll see a drop-down of common objects. Select profile and click the 'Submit' button.

New object

Now that you've defined the object, couple an action with it. Click the 'Create New Action Type' button. Enter that 'People can 'smash' an object and click 'Submit'.

You should see a page showing the setting attached to the 'smash' action. Indicate that players can smash a profile, so under the 'Connected Object Types' box, enter 'profile' to connect this action to the profile object. Click 'Save Changes' to create the action.

That's all you need to get started. For more info, review the documentation on defining Open Graph actions.

New action

Now, let's walk through publishing the story from Friend Smash. Find the sendOG() method within the ui.js file and add the following code:

console.log("Sending custom OG story...");

FB.api('/me/friendsmashsample:smash?profile=' + gFriendID, 'post', {}, function(response) {
    console.log(response);
});

Here, we're constructing another HTTP POST request to the graph, with the endpoint defined by the app's unique namespace. The action, friendsmashsample:smash?, is followed by the profile the player just smashed profile=' + gFriendID. Be sure to replace the friendsmashsample namespace with the namespace you defined when creating your app.

As you already implemented sending a score to the graph at the end of a game, call this method from the same place. Inside game.js, find sendScore() and add sendOG(); to the bottom of the method.

To ensure that the Open Graph story is published, play and finish a new game. Then, check your activity log for something like this:

Activity log

Remember that publishing to Open Graph requires the user to have granted the publish_actions permission to the app.

Next steps:

Congratulations! You've added a range of Facebook features to a simple game, making it more interesting and engaging. As a next step, consider adding more achievements or Open Graph objects to Friend Smash to build its presence on Facebook.

Check the Facebook Samples GitHub account for more updates to Friend Smash.

Updated about a month ago
Facebook © 2013 · English (US)
AboutAdvertisingCareersPlatform PoliciesPrivacy Policy