After that you'll be able to create a new app.
Please note you must have verified your Facebook account to create apps on Facebook. Click here for more information on verifying your account.
Configuring your App
Apps on Facebook are loaded into the Canvas section of the Canvas Page. The Canvas is quite literally a blank canvas within Facebook on which to run your app. You populate the Canvas by providing a Canvas URL that contains the HTML, JavaScript and CSS that make up your app. When a user requests the Canvas Page, we load the Canvas URL within aniframe
on that page. This results in your app being displayed within the standard Facebook chrome.For example, suppose that you have a web app available at
http://www.example.com/canvas
. This is your Canvas URL. When you setup your app on Facebook, you must specify a Canvas Page name that is appended to https://apps.facebook.com/. In this example, we will use your_app
as the Canvas Page name. When the user navigates to https://apps.facebook.com/your_app
in their browser, they will see the contents of http://www.example.com/canvas
loaded inside of Facebook.com.Note that
http://www.example.com/canvas
cannot forward to another URL via HTTP redirect responses, e.g. response code 301, but has to return the response directly.Once you've created a Facebook app, select the "App on Facebook" section and specify a Canvas and Secure Canvas URL:
Because your app is loaded in the context of Facebook, you must be aware of certain size constraints when designing your user interface. You can manage settings for the size of your iframe in the Dev App, in the Advanced Tab under Canvas settings.
Canvas Width
You can set your Canvas Width to "Fixed (760px)", the default setting, which makes your app have a fixed width of 760 pixels. You can also set your width to "Fluid" which means that we set the iframe width to 100%. Your content will then be left-aligned and resize to fill the page as the user changes the width of their browser.Canvas Height
You can set the Canvas Height to Fluid, the default setting, in which case the iframe height is set to 100% which means that it grows the fill the page and shows scroll-bars if your content exceeds the height of the page.You can also set the Height to ‘Settable’ in which case the height of the Canvas defaults to 800 pixels. You can change the height of the iframe by calling the FB.Canvas.setSize() method to fit your content. You can also call FB.Canvas.setAutoResize() to enable the ‘Auto-resize’ functionality where we will poll for the height of your content and adjust the height of the parent iframe to match accordingly. Note these method only work with Canvas Height set to Settable.
Here is a How-To to implement Fluid Canvas for your app.
Authorization
In order to create a personalized user experience, Facebook sends your app information about the user. This information is passed to your Canvas URL using HTTP POST within a single signed_request parameter which contains a base64url encoded JSON object.When a user first accesses your app, the signed_request parameter contains a limited amount of user data:
Name | Description |
---|---|
user | A JSON array containing the locale string, country string and the age object (containing the min and max numbers of the age range) for the current user. |
algorithm | A JSON string containing the mechanism used to sign the request. |
issued_at | A JSON number containing the Unix timestamp when the request was signed. |
https://www.facebook.com/dialog/oauth? client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
Because of the way that we currently load iframes for Apps on Facebook.com, it is important that you navigate the top window of the user's browser to the OAuth Dialog. Many apps do this by sending a
script
fragment to the user's browser setting the top.location.href
property to the dialog URL. Please see the PHP example at the end of this section for an example.By default, the user is asked to authorize the app to access basic information that is available publicly or by default on Facebook. If your app needs more than this basic information to function, you must request specific permissions from the user. This is accomplished by adding a scope parameter to the OAuth Dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to user's email address and their news feed:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID &redirect_uri=YOUR_CANVAS_PAGE&scope=email,read_stream
A full list of permissions is available in our permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; so we recommend that you only request the permissions you absolutely need for your app.
If the user presses Don't Allow, your app is not authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with the following error information:
http://YOUR_CANVAS_PAGE?error_reason=user_denied& error=access_denied&error_description=The+user+denied+your+request.If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter. After the user has authorized your app, the signed_request parameter will contain the following information on subsequent requests:
Name | Description |
---|---|
user | A JSON array containing the locale string, country string and the age object (containing the min and max numbers of the age range) for the current user. |
algorithm | A JSON string containing the mechanism used to sign the request. |
issued_at | A JSON number containing the Unix timestamp when the request was signed. |
user_id | A JSON string containing the Facebook user identifier (UID) of the current user. |
oauth_token | A JSON string that you can pass to the Graph API or the Legacy REST API. |
expires | A JSON number containing the Unix timestamp when the oauth_token expires. |
signed_request
parameter and prompt the user to authorize your app: <?php
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
?>
You can learn more about the signed_request
parameter including how to validate the signature in our Signed Request Reference guide. Several of our SDKs, such as the JavaScript SDK and the PHP SDK make authentication and authorization straightforward.Once the user has authorized your application, you can start using the Graph API to access user profile information as well as friend data.
Social Channels
Facebook Platform provides a number of different ways for users to share with their friends from your app. We call these Social Channels. Your app can publish directly to a user's News Feed, send Requests to their friends and leverage our automatic channels.Feed
The News Feed is shown immediately to users upon logging into Facebook, making it core to the Facebook experience. Your app can post to the user's news feed by using the Feed Dialog. The following example shows how to display this dialog within your canvas page:<?php
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$message = "Apps on Facebook.com are cool!";
$feed_url = "https://www.facebook.com/dialog/feed?app_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)
. "&message=" . $message;
if (empty($_REQUEST["post_id"])) {
echo("<script> top.location.href='" . $feed_url . "'</script>");
} else {
echo ("Feed Post Id: " . $_REQUEST["post_id"]);
}
?>
Requests
Requests are a great way to enable users to invite their friends to your app or to take specific action like accepting a gift or help complete a task. Your app can send requests by using the Request Dialog. The following example shows how to display this dialog within your canvas page:<?php
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$message = "Would you like to join me in this great app?";
$requests_url = "https://www.facebook.com/dialog/apprequests?app_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)
. "&message=" . $message;
if (empty($_REQUEST["request_ids"])) {
echo("<script> top.location.href='" . $requests_url . "'</script>");
} else {
echo "Request Ids: ";
print_r($_REQUEST["request_ids"]);
}
?>
If you prefer to have your app send requests directly to the user (an App-generated request), you post a request to the
apprequest
connection of the User
Graph object:<?php
$app_id = YOUR_APP_ID;
$app_secret = YOUR_APP_SECRET;
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $app_id .
"&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$app_access_token = file_get_contents($token_url);
$user_id = THE_CURRENT_USER_ID;
$apprequest_url ="https://graph.facebook.com/" .
$user_id .
"/apprequests?message='INSERT_UT8_STRING_MSG'" .
"&data='INSERT_STRING_DATA'&" .
$app_access_token . "&method=post";
$result = file_get_contents($apprequest_url);
echo("App Request sent?", $result);
?>
The message parameter is a UTF-8 string which describes the request. The data parameter is a string which the app can use to store any relevant data in order to process the request.Once sent, new requests a user has received are visible as a counter on your application's bookmark and it also increments the counter next to the appropriate Dashboard.
If you would like to send an App-generated request to multiple users you can use the
ids
parameter (see Selection in the Graph API) and enter a comma delimited string of user IDs:POST https://graph.facebook.com/apprequests?ids=user_id1,user_id2 &message=Hello&access_token=APP ACCESS TOKENFor more details about our channels, see our Social Channels core concept document.
Publishing game stories
Game developers can publish stories for user’s achievements, users passing their friends’ scores, or leaderboard for user and their friends to make game play much more competitive, social and exciting for their users.Here’s a simple html code snippet that you can use to set up your achievement.
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#"> <head> <title>ACHIEVEMENT_TITLE <meta property="og:type" content="game.achievement"/> <meta property="og:url" content="URL_FOR_THIS_PAGE"/> <meta property="og:title" content="ACHIEVEMENT_TITLE"/> <meta property="og:description" content="ACHIEVEMENT_DESCRIPTON"/> <meta property="og:image" content="URL_FOR_ACHIEVEMENT_IMAGE"/> <meta property="game:points" content="POINTS_FOR_ACHIEVEMENT"/> <meta property="fb:app_id" content="YOUR_APP_ID"/> </head> <body> Promotional content for the Achievement. This is the landing page where a user will be directed after clicking on the achievement story. </body> </html>The code below allows you to register the above achievement for your app and then publish it for a user as well as publish a score for the user.
<?php $app_id = 'YOUR_APP_ID'; $app_secret = 'YOUR_APP_SECRET'; $app_url = 'YOUR_APP_URL'; // The Achievement URL $achievement = 'YOUR_ACHIEVEMENT_URL'; $achievement_display_order = 1; // The Score $score = 'YOUR_SCORE'; // Authenticate the user session_start(); if(isset($_REQUEST["code"])) { $code = $_REQUEST["code"]; } if(empty($code) && !isset($_REQUEST['error'])) { $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection $dialog_url = 'https://www.facebook.com/dialog/oauth?' . 'client_id=' . $app_id . '&redirect_uri=' . urlencode($app_url) . '&state=' . $_SESSION['state'] . '&scope=publish_actions'; print(''); exit; } else if(isset($_REQUEST['error'])) { // The user did not authorize the app print($_REQUEST['error_description']); exit; }; // Get the User ID $signed_request = parse_signed_request($_POST['signed_request'], $app_secret); $uid = $signed_request['user_id']; // Get an App Access Token $token_url = 'https://graph.facebook.com/oauth/access_token?' . 'client_id=' . $app_id . '&client_secret=' . $app_secret . '&grant_type=client_credentials'; $token_response = file_get_contents($token_url); $params = null; parse_str($token_response, $params); $app_access_token = $params['access_token']; // Register an Achievement for the app print('Register Achievement: '); $achievement_registration_URL = 'https://graph.facebook.com/' . $app_id . '/achievements'; $display_order = '1'; $achievement_registration_result = https_post($achievement_registration_URL, 'achievement=' . $achievement . '&display_order=' . $achievement_display_order . '&access_token=' . $app_access_token ); print(' '); // POST a user achievement print('Publish a User Achievement '); $achievement_URL = 'https://graph.facebook.com/' . $uid . '/achievements'; $achievement_result = https_post($achievement_URL, 'achievement=' . $achievement . '&access_token=' . $app_access_token ); print(' '); // POST a user score print('Publish a User Score '); $score_URL = 'https://graph.facebook.com/' . $uid . '/scores'; $score_result = https_post($score_URL, 'score=' . $score . '&access_token=' . $app_access_token ); print(' '); function https_post($uri, $postdata) { $ch = curl_init($uri); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); $result = curl_exec($ch); curl_close($ch); return $result; } function parse_signed_request($signed_request, $secret) { list($encoded_sig, $payload) = explode('.', $signed_request, 2); // decode the data $sig = base64_url_decode($encoded_sig); $data = json_decode(base64_url_decode($payload), true); if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') { error_log('Unknown algorithm. Expected HMAC-SHA256'); return null; } // check sig $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true); if ($sig !== $expected_sig) { error_log('Bad Signed JSON signature!'); return null; } return $data; } function base64_url_decode($input) { return base64_decode(strtr($input, '-_', '+/')); } ?>Learn more about how to publish scores and achievements. Here is a more detailed How-To for publishing scores and achievements for your app.
Canvas Performance
In order to improve the performance of your Canvas page, Facebook attempts to automatically determine which static resources are important to your application load time, and fetches them to the browser before contacting your server to get the contents of the iframe. Currently, it does this for Microsoft Internet Explorer versions 8-9 and Google Chrome, although we expect to add more browsers in the future.Facebook's automatic systems will provide a modest performance improvement, but you may be able to further improve page load times by explicitly specifying which resources should be prefetched. For best results, we recommend that you specify the largest static resources that are related to the execution of your app (CSS, JS, and SWF files).
To see what resources are being prefetched, you can retrieve the
staticresources
connection on the Graph API Application object. You can also find this information on the HTML source of the canvas page, although the Graph API method returns much more information.To influence what is prefetched, you can include the Javascript SDK and call these methods on each page load: FB.Canvas.Prefetcher.addStaticResource and FB.Canvas.Prefetcher.setCollectionMode.
It's important that your static resources have the appropriate HTTP headers, otherwise Facebook will ignore them. See FB.Canvas.Prefetcher.addStaticResource for details.
Finally, you can measure the page load performance using FB.Canvas.setDoneLoading. This data will be available in the Insights tool.
Special Considerations for Adobe Flash developers
For developers creating Adobe Flash based apps within Canvas, it is recommended that you set thewmode
of the Flash object to "opaque"
:<object type="application/x-shockwave-flash" data="http://roflgamez.com/emote.swf"
width="640" height="360">
<param name="wmode" value="opaque">
...
</object>
This will allow Facebook Dialogs, Chat tabs, Notifications and Ticket Flyouts to display correctly, over the Flash content. Other modes (including the default mode, wmode="window"
, wmode="direct"
, and wmode="gpu"
) require us to hide your flash object when Dialogs, Notifications, Chat tabs, and Ticker Flyouts occur. This can be unpleasant or confusing experience for users.We understand that for some apps which require a high frame rate it may not be possible to use
wmode="opaque"
. If your app does require using wmode="window"
or wmode="direct"
it will be automatically hidden when a Facebook Dialog, etc. is opened. Before launching your app confirm that this functionality is working as intended, in particular do not host your flash game within an additional iframe; otherwise Dialogs, Notifications, Chat tabs and Ticker Flyouts will not display correctly and negatively impact your user's experience.For developers that would prefer to provided a customized and more pleasing user experience the JavaScript SDK supports a parameter hideFlashCallback, that allows developers to define a JavaScript function which will be invoked whenever their Flash content is hidden and displayed due to Dialogs, Chat tabs, Notifications and Ticker Flyouts. Flash content can be manually hidden and displayed via FB.Canvas.hideFlashElement and FB.Canvas.showFlashElement.
Samples and Next Steps
If you are looking for a real world example to help you get started building Apps on Facebook.com, please see our Run with Friends sample app. This sample uses most of the pieces of Facebook Platform and even some advanced features like Real-time Updates.This was a quick survey of the major integration points available to Apps on Facebook.com. Beyond these features only available to Apps on Facebook.com, you can leverage all the different pieces of Facebook Platform including Social Plugins and the Graph API within your app.
0 Comments:
Post a Comment