Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Monday, July 22, 2013

Facebook Canvas Tutorial

Creating your App

Start by visiting the App Dashboard. If you haven't created an application before you will be prompted to register. Note that you have to verify your Facebook account to create apps on Facebook.

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 person using your app requests the Canvas Page, we load the Canvas URL within an iframe 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 //www.example.com/canvas. This is your Canvas URL. When you set up your app on Facebook, you must specify a Canvas Page name that is appended to //apps.facebook.com/. You can specify this by entering a unique name in the App Namespace field through the App Dashboard. In this example, we'll useyour_app as the Canvas Page name. When someone using your app navigates to //apps.facebook.com/your_app, they'll see the contents of www.example.com/canvas loaded inside of Facebook.com.
Note that www.example.com/canvas cannot forward to another URL via HTTP redirect responses, for example response code 301, but has to return the response directly.
Once you've created a Facebook app, go to 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 on Facebook 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.setAutoGrow() to enable Auto-grow functionality where you poll for the height of your content and grow the height of the parent iframe to match accordingly. Note these methods only work with Canvas height set to Settable.

Configuring for App Center

Once you have configured your app for Canvas, the next step is to configure the App Center settings. App Center is the central location for people to discover and try out new apps and a primary source of installs. Configuring these settings will allow you to customize your App Detail page to display your app description, icons, screenshots and other relevant promotional materials in the Facebook App Center. For more information on this step, see the App Center docs.

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 someone first accesses your app, the signed_request parameter contains a limited amount of user data:
NameDescription
userA 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 person using the app.
algorithmA JSON string containing the mechanism used to sign the request.
issued_atA JSON number containing the Unix timestamp when the request was signed.
In order for you to gain access to all the information available to your app by default (like Facebook ID), people must authorize your app. We recommend that you use the Login Dialog for apps on Facebook.com. You invoke this dialog by redirecting the browser to the following URL (replacing the YOUR_APP_ID and YOUR_CANVAS_PAGE with the correct values found in the App Dashboard):
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
 
Because of the way iframes are currently loaded for apps on Facebook.com, it's important that you navigate the top window of the browser to the Login dialog. Many apps do this by sending a script fragment to the browser setting the top.location.hrefproperty to the dialog URL. Please see the PHP example at the end of this section for an example.
By default, people using your app are asked to authorize the app to access their public profile. If your app needs more than this information to work correctly, you must request specific permissions from people. This is accomplished by adding a scope parameter to the Login dialog request followed by comma separated list of the required permissions. The following example shows how to ask for access to someone's email address and 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 people press click Don't Allow, your app is not authorized. The Login dialog redirects (via HTTP 302) 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 people click Allow, your app is authorized. The Login dialog redirects (via HTTP 302) to the URL you passed in the redirect_uriparameter. After the app has been authorized, the signed_request parameter will contain the following information on subsequent requests:
NameDescription
userA JSON array containing the locale string, country string and the age object (containing the min and maxnumbers of the age range).
algorithmA JSON string containing the mechanism used to sign the request.
issued_atA JSON number containing the Unix timestamp when the request was signed.
user_idA JSON string containing the person's Facebook user identifier (UID).
oauth_tokenA JSON string that you can pass to the Graph API.
expiresA JSON number containing the Unix timestamp when the oauth_token expires.
The following PHP example demonstrates how to access the signed_request parameter and prompt the user to authorize your app:
     $app_id = "YOUR_APP_ID";

     $canvas_page = "YOUR_CANVAS_PAGE_URL";

     $auth_url = "//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 Referenceguide. Several of our SDKs, such as the JavaScript SDK and the PHP SDK make authentication and authorization straightforward.
Once someone has authorized your application, you can start using the Graph API to access that person's profile information as well as friend data.

Social channels

Facebook provides a number of different ways for people to share with their friends from your app. We call these social channels. Your app can publish directly to a person's News Feed, send Requests to their friends and leverage our automatic channels.

Feed

The News Feed is shown immediately to people when they go to Facebook, making it core to the Facebook experience. Your app can post to the News Feed, that is, share something with other people, by using the Feed dialog. The following example shows how to display this dialog within your Canvas Page:
$app_id = "YOUR_APP_ID";

         $canvas_page = "YOUR_CANVAS_PAGE_URL";

         $message = "Apps on Facebook.com are cool!";

         $feed_url = "//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 people to invite their friends to your app or to take specific action like accept 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:
$app_id = "YOUR_APP_ID";

         $canvas_page = "YOUR_CANVAS_PAGE_URL";

         $message = "Would you like to join me in this great app?";

         $requests_url = "//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 people 
(that is, to make an app-generated request), you post a request to 
the apprequest connection of the User Graph object:
 $app_id = YOUR_APP_ID;
  $app_secret = YOUR_APP_SECRET;

  $token_url = "//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 ="//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 that describes the request. The data parameter is a string that the app can use to store any relevant data in order to process the request.
Once a new request is sent to someone, they see it as a counter on the app bookmark, and it also increments the counter next to the appropriate Dashboard.
If you would like to send an app-generated request to more than one person, you can use the ids parameter (see Selection in the Graph API) and enter a comma delimited string of people's IDs:
POST https://graph.facebook.com/apprequests?ids=user_id1,user_id2<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&message=Hello&access_token=APP ACCESS TOKEN
For more details about our channels, see the Social Channels core concept document.

Samples and next steps

If you're interested in building Facebook games, see our Games Tutorial, which walks you through implementing authorization, invites, feed stories, scores and achievements. It's a great place to get started.
This was a quick survey of the major integration points available to Facebook apps. Beyond these features, you can leverage all the different pieces of Facebook Platform including social plugins and the Graph API within your app. See Overview of the Facebook Platform for a complete summary of Facebook developer tools.
Please see our Integrating with Canvas for additional advanced best practices when integrating with Canvas.