Thursday, June 28, 2012

Facebook Chat API


You can integrate Facebook Chat into your Web-based, desktop, or mobile instant messaging products. Your instant messaging client connects to Facebook Chat via the Jabber/XMPP service. This document describes the features and limitations of Facebook Chat's XMPP protocol for the developer who intends to implement a Facebook Chat client.
Before reading this document, you should be familiar with the terms and concepts involved in XMPP chat clients and servers.
Please do not use this API to send spammy messages to users. Facebook takes user experience and spam extremely seriously and if users report your app as using the Chat API to spam them, we will disable your app.



Features and Limitations

Facebook Chat currently supports the following features:
  • Facebook Platform authentication using the X-FACEBOOK-PLATFORM SASL authentication mechanism
  • Username/password authentication using the DIGEST-MD5 authentication mechanism
  • Sending and receiving plain-text messages (not HTML messages)
  • Sending and receiving typing notifications using the XEP-0085 protocol extension (not the XEP-0022 extension)
  • Setting the user idle using a show element in presence stanzas (there will be a delay before the user appears idle)
  • Receiving vCards using the XEP-0054 extension
  • Retrieving friends' photos (either with vCard or XMPP presence)

Limitations

Facebook Chat should be compatible with every XMPP client, but is not a full XMPP server. It should be thought of as a proxy into the world of Facebook Chat on www.facebook.com. As a result, it has several behaviors that differ slightly from what you would expect from a traditional XMPP service:
  • Your client cannot send or receive HTML messages
  • Because roster items and presence subscriptions are based on the user's Facebook friends, they cannot be created or deleted using the standard XMPP mechanisms.
  • Facebook Chat is terse when sending updates for new friends, because the negotiation happens outside of XMPP. Future versions of Facebook Chat may be more conformant.
  • The user's own Jabber ID (JID) is different from the Jabber ID that their contacts will see because the translation is done internally.
  • Arbitrary IQ stanzas cannot be passed between clients.
  • Presence probes do not currently work.
  • Non-SASL authentication with the jabber:iq:auth namespace as described in XEP-0078 is not currently supported.
  • The XML parser does not yet fully handle XML namespaces. Please stick to the same style as the examples in XMPP RFCs 3920 and 3921 when using XML namespaces.

Configuring Chat Authentication

You can authenticate your chat client users with one of two authentication mechanisms: X-FACEBOOK-PLATFORM (Facebook Platform) and DIGEST-MD5 (username/password). Facebook recommends you use the X-FACEBOOK-PLATFORM mechanism to connect to Facebook Chat whenever possible, because it provides a better user experience using simple Facebook Platform authentication.

Authenticating with Facebook Platform

We support a custom SASL mechanism called X-FACEBOOK-PLATFORM that allows clients to connect to chat using Facebook authentication. This mechanism is preferred for any application that is oriented toward social media in general or Facebook in particular, especially applications that are already integrated with Facebook Platform.
In order to connect using this mechanism, the user must first log in to your application and grant the xmpp_login extended permission. Follow the client side flow to get a valid access_token for the user with the xmpp_login extended permission.
Your application may now log in to Facebook Chat via Jabber using the X-FACEBOOK-PLATFORM mechanism. The user's Jabber ID will be assigned during the resource binding step of XMPP. Please keep in mind that while all of the messages defined by the X-FACEBOOK-PLATFORM mechanism are UTF-8 strings, XMPP specifies that they should be Base64-encoded before being sent over the wire.
The mechanism starts with a server challenge, in the form of a common HTTP query string: an ampersand-separated sequence of equals-sign-delimited key/value pairs. The keys and values are UTF-8-encoded and URL-encoded. The query string contains two items: method and nonce.
The client's reply should be a similarly-encoded query string prepared as if it were going to call a method against the Facebook API. The call should contain the following parameters:
  • string method: Should be the same as the method specified by the server.
  • string api_key: The application key associated with the calling application.
  • string access_token: The access_token obtained in the above step.
  • float call_id: The request's sequence number.
  • string v: This must be set to 1.0 to use this version of the API.
  • string format: Optional - Ignored.
  • string cnonce: Optional - Client-selected nonce. Ignored.
  • string nonce: Should be the same as the nonce specified by the server.
The server will then respond with a success or failure message. Note that this needs to be over TLS or you'll get an error.

Authenticating with Username/Password

The DIGEST-MD5 SASL mechanism is available to support traditional XMPP or multi-protocol IM clients that are not customized for (or even aware of) Facebook. This mechanism requires prompting the user for his or her password; therefore, it should only be used when necessary. In particular, it MUST NOT be used for any client that:
  • Proxies the XMPP connection (the connection must be directly from the user's computer to Facebook).
  • Reports messages or any other information about user activity to a third party (including the client developer).
  • Integrates with Facebook, or has a Facebook Application ID.
If your application does any of the above, you must use Facebook Platform authentication instead.
The user's Jabber ID is simply his or her Facebook user name with @chat.facebook.com appended. A user must have a Facebook username to use DIGEST-MD5. After the user gets his or her username, he or she must log out of and into Facebook once for us to store the special hash of the password.
Clients should retrieve their user's vCard from the server according to XEP-0054 in order to be able to display a more natural name to the user. For example:
<iq id='1' type='get'><vCard xmlns='vcard-temp'/></iq>

Best Practices

In order to provide the best user experience, we recommend your chat integration do the following:
  • Your Facebook Chat integration should only be used for applications facilitating real time conversation or interaction between users. Links or advertisements should not be sent via chat, unless the sending user types in this message.
  • Your Facebook Chat integration should only be used for sessions that are expected to be long-lived. Clients should not rapidly churn on and off.
  • vCards retrieved through Facebook Chat will contain profile pictures if available. Clients should cache these pictures using the content hash, not the user ID, as the key. vCards should only be fetched if the client does not already have that user's picture cached.
  • Clients should not automatically reconnect if they receive a stream-error of type conflict.
  • Clients should be able to handle a single contact with multiple group elements.
  • Incoming messages from the JIDs chat.facebook.com or facebook.com should be displayed as administrative messages.

Sample code

Below is a sample code that shows you how to authenticate a user and connect with XMPP.
<?php
// Copyright 2004-present Facebook. All Rights Reserved.

$STREAM_XML = '<stream:stream '.
  'xmlns:stream="http://etherx.jabber.org/streams" '.
  'version="1.0" xmlns="jabber:client" to="chat.facebook.com" '.
  'xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';

$AUTH_XML = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" '.
  'mechanism="X-FACEBOOK-PLATFORM"></auth>';

$CLOSE_XML = '</stream:stream>';

$RESOURCE_XML = '<iq type="set" id="3">'.
  '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'.
  '<resource>fb_xmpp_script</resource></bind></iq>';

$SESSION_XML = '<iq type="set" id="4" to="chat.facebook.com">'.
  '<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></iq>';

$START_TLS = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';


function open_connection($server) {
  print "[INFO] Opening connection... ";

  $fp = fsockopen($server, 5222, $errno, $errstr);
  if (!$fp) {
    print "$errstr ($errno)<br>";
  } else {
    print "connnection open<br>";
  }

  return $fp;
}

function send_xml($fp, $xml) {
  fwrite($fp, $xml);
}

function recv_xml($fp,  $size=4096) {
  $xml = fread($fp, $size);
  if ($xml === "") {
     return null;
  }

  // parses xml
  $xml_parser = xml_parser_create();
  xml_parse_into_struct($xml_parser, $xml, $val, $index);
  xml_parser_free($xml_parser);

  return array($val, $index);
}

function find_xmpp($fp,  $tag, $value=null, &$ret=null) {
  static $val = null, $index = null;

  do {
    if ($val === null && $index === null) {
      list($val, $index) = recv_xml($fp);
      if ($val === null || $index === null) {
        return false;
      }
    }

    foreach ($index as $tag_key => $tag_array) {
      if ($tag_key === $tag) {
        if ($value === null) {
          if (isset($val[$tag_array[0]]['value'])) {
            $ret = $val[$tag_array[0]]['value'];
          }
          return true;
        }
        foreach ($tag_array as $i => $pos) {
          if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) &&
            $val[$pos]['value'] === $value) {
              $ret = $val[$pos]['value'];
              return true;
          }
        }
      }
    }
    $val = $index = null;
  } while (!feof($fp));

  return false;
}


function xmpp_connect($options, $access_token) {
  global $STREAM_XML, $AUTH_XML, $RESOURCE_XML, $SESSION_XML, $CLOSE_XML, $START_TLS;

  $fp = open_connection($options['server']);
  if (!$fp) {
    return false;
  }
 
  // initiates auth process (using X-FACEBOOK_PLATFORM)
  send_xml($fp,  $STREAM_XML);
  if (!find_xmpp($fp, 'STREAM:STREAM')) {
    return false;
  }
  if (!find_xmpp($fp,  'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
    return false;
  }

  // starting tls - MANDATORY TO USE OAUTH TOKEN!!!!
  send_xml($fp,  $START_TLS);
  if (!find_xmpp($fp, 'PROCEED', null, $proceed)) {
    return false;
  }
  stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

  send_xml($fp, $STREAM_XML);
  if (!find_xmpp($fp, 'STREAM:STREAM')) {
    return false;
  }
  if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
    return false;
  }

  // gets challenge from server and decode it
  send_xml($fp, $AUTH_XML);
  if (!find_xmpp($fp,  'CHALLENGE', null, $challenge)) {
    return false;
  }
  $challenge = base64_decode($challenge);
  $challenge = urldecode($challenge);
  parse_str($challenge, $challenge_array);

  // creates the response array
  $resp_array = array(
    'method' => $challenge_array['method'],
    'nonce' => $challenge_array['nonce'],
    'access_token' => $access_token,
    'api_key' => $options['app_id'],
    'call_id' => 0,
    'v' => '1.0',
  );
  // creates signature
  $response = http_build_query($resp_array);

  // sends the response and waits for success
  $xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">'.
    base64_encode($response).'</response>';
  send_xml($fp, $xml);
  if (!find_xmpp($fp, 'SUCCESS')) {
    return false;
  }
  
  // finishes auth process
  send_xml($fp, $STREAM_XML);
  if (!find_xmpp($fp,'STREAM:STREAM')) {
    return false;
  }
  if (!find_xmpp($fp, 'STREAM:FEATURES')) {
    return false;
  }
 send_xml($fp, $RESOURCE_XML);
  if (!find_xmpp($fp, 'JID')) {
    return false;
  }
  send_xml($fp, $SESSION_XML);
  if (!find_xmpp($fp, 'SESSION')) {
    return false;
  }

  // we made it!
  send_xml($fp, $CLOSE_XML);
  print ("Authentication complete<br>");
  fclose($fp);

  return true;
}



//Gets access_token with xmpp_login permission
function get_access_token($app_id, $app_secret, $my_url){ 
    
  $code = $_REQUEST["code"];

  if(empty($code)) {
    $dialog_url = "https://www.facebook.com/dialog/oauth?scope=xmpp_login".
     "&client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) ;
    echo("<script>top.location.href='" . $dialog_url . "'</script>");
  }
   $token_url = "https://graph.facebook.com/oauth/access_token?client_id="
    . $app_id . "&redirect_uri=" . urlencode($my_url) 
    . "&client_secret=" . $app_secret 
    . "&code=" . $code;
   $access_token = file_get_contents($token_url);
    parse_str($access_token, $output);
    
    return($output['access_token']);
}

function _main() {
  print "Test platform connect for XMPP<br>";
  $app_id='YOUR_APP_ID';
  $app_secret='YOUR-APP_SECRET';
  $my_url = "YOUR_APP_URL";
  $uid = 'USER_ID';
  $access_token = get_access_token($app_id,$app_secret,$my_url);
  print "access_token: ".$access_token."<br>";

  $options = array(
    'uid' => $uid,
    'app_id' => $app_id,
    'server' => 'chat.facebook.com',
   );

  // prints options used
  print "server: ".$options['server']."<br>";
  print "uid: ".$options['uid']."<br>";
  print "app id: ".$options['app_id']."<br>";

  if (xmpp_connect($options, $access_token)) {
    print "Done<br>";
  } else {
    print "An error ocurred<br>";
  }

}

_main();


Facebook Credits

Facebook Credits

The most effective way for developers to generate revenue in games and apps on Facebook

Facebook Credits is a payment system that offers a safe, easy and fast way to pay for digital and virtual goods in games and apps across Facebook.
  • Facebook users trust the Facebook brand and feel comfortable storing their payment information with Facebook and buying with their Facebook credentials.
  • Facebook Credits is avaialable internationally and supports 80+ payment methods in 50+ countries around the world and we continue to actively expand our footprint.
  • Finally Facebook credits provides a consistent way for users to buy on Facebook across mobile, desktop, games as well as non-game apps.
Developers already building on Facebook Platform can use the Graph API and Dialogs to integrate with our payments APIs and get the integration up and running quickly. This enables developers to focus on building their Apps and let us take care of all payments overhead!

Credits Payment Flows

Facebook offers two different payment flows for developers:
  1. Credits as a Payment Method
    This flow enables you to use Facebook Credits as a payment platform where you can charge users directly for items in your app (including your own in-app currency).
  2. Credits as a Currency
    This flow enables you to use Facebook Credits as an in-app currency (instead of having to manage your own in-app currency) where users will see and directly access their Credits balance.

Credits as a Payment Method

NOTE: To simplify the purchase experience for users, give you more flexibility, and make it easier for you to reach a global audience of Facebook users, we are updating our payments product to support pricing in local currency (ex: US dollar, British pound and Japanese yen) instead of Credits. We’ll release local currency support for in-app payments in Q3. Any apps or games that sell virtual items will be required to use local currency by the end of the year. For now, we will continue to support Credits as a payment method. Learn more about local currency pricing, and sign up for the latest information about the transition.
Facebook offers a payments platform that enables developers to leverage our payments services to charge their users on Apps on Facebook as well as their Mobile web Applications.
You can use Facebook Credits as a payments platform to buy in game virtual currency for your app or game. The user experience looks like below. A user places an order by clicking a button in the application.

In response, the app invokes the Pay dialog along with the order information which provide Facebook the item details. One of the following happens depending on the order and the user's credit balance and credentials on file.
  • If the user has sufficient credits balance then the user sees a confirmation dialog where they need to confirm the transaction before the order will get fulfilled.

  • If the user does not have sufficient balance then the user is asked to pick the payment method to pay for the required number of credits. There are several payment methods available to users depending on locale, so this screen will vary for users based on their locale.

When the user does not have payment credentials on file, the user may get redirected to a new page for entering credentials or may stay within the dialog, depending on the payment type. For example if the user chooses to enter their credit card information then they are redirected to a new page like below, but if they choose to do a mobile payment then it can be processed in the dialog itself.

Once the user confirms their willingness to pay and provides the credentials, Facebook calls the application backend to let the app owner's system settle the order. Once the app responds, Facebook completes the transaction appropriately and shows the result to the user. If the payment was done in the dialog, the user can click continue to close the payment dialog. If the payment was completed on the full page, the user can click continue to go to a destination url set by the app.

Credits as a Currency

NOTE: To simplify the purchase experience for users, give you more flexibility, and make it easier for you to reach a global audience of Facebook users, we are updating our payments product to support pricing in local currency (ex: US dollar, British pound and Japanese yen) instead of Credits. We’ll release local currency support for in-app payments in Q3. Any apps or games that sell virtual items will be required to use local currency by the end of the year. By that time, all developers who use Credits as a currency will need to replace Credits with their own virtual currency. Learn more.
Some applications might benefit from a flow where credits is used as an in-game currency and help users bulk up on credits for later use in your apps. In this case your application can invoke appropriate payment dialog to enable users to buy credits which is a stored currency on Facebook that they users can use to pay for good across our various apps and games on Facebook.

Credits on Mobile

The pay dialog can also be rendered in a mobile environment in the same way as it can for Apps on Facebook on desktop. Users have the option to pay with their existing payment credentials, their mobile phone, or our 80+ payment methods. For more information on mobile platform, please see our mobile documentation.

Here is what the payment flow looks like in a mobile browser:


Accepting payments are different on iOS since Facebook Credits are not supported within iOS native apps.
  • On the mobile web (including mobile web apps linked from Android), you must use Facebook Credits.
  • On iOS, you must build a native app and use iTunes payments.
On Mobile Web, the only additional step to get up and running with payments is to select the 'Enable payments on the mobile web' checkbox, as seen below.

On iOS, you can quickly build a native app from your web app by using a tool like PhoneGap.

Earning Credits via Offers

Using the Facebook Credits API, you can directly link users to Facebook’s Offers flow, in partnership with TrialPay:
  1. Direct Access to Offers: Adding this functionality to your app will give users the chance to earn Facebook Credits by completing offers that matter to them, boosting both engagement and revenue.
  2. DealSpot: DealSpot allows users to access exclusive deals via an in-app icon. From buying flowers for Valentine’s Day to watching trailers for the latest movies, users will be matched to an intelligent rotation of deals, creating an additional revenue stream for credits developers.
Read here for more information.

Get Started

For integration details and best practices, please refer to the following resources:
Facebook Credits Getting started Tutorial
NOTE: Per the Facebook Credits Terms, all games on the Facebook Platform (including mobile web apps) must exclusively process payments through Facebook Credits. Games that have not integrated Facebook Credits will be subject to enforcement.

Ads on the Graph API

Accessing the Ads API
The Ads API is a restricted platform which may only be accessed by whitelisted Apps. You can learn more about the program and apply online. You need to apply separately for each app.
The Ads API allows you to create, manage and measure all of your Facebook Marketplace ads via an API. You can use the Ads API if you match one of the following profiles:
  • You manage your own ad spend, and have many accounts and/or many ads. You can use the Ads API as a scalable alternative to the Facebook Advertising Manager tool.
  • You are an advertising tool vendor who sells advertising management solutions to small- and medium-sized businesses, and you manage ads from multiple sources (like Facebook and other online advertisers).
  • You are an ad agency managing budgets and campaigns for multiple clients.
If you do not want to build your own tool, you can work with a vendor who has.
If you're interested in getting access to the Ads API, you can now learn more about the program and apply online.

Ads API Overview

The following Graph API objects are available:
The following Graph API queries are also available:
The objects and queries are inter-related as depicted in the following diagram.

For information on the overall Graph API architecture, please see:
  • Graph API, an introduction to objects on the social graph, e.g. User, and the connections between the objects, e.g. friend relationships
  • Authentication, which describes the available OAuth flows

Getting Started

To get started with the Ads API, complete the following steps.

Configure your Facebook Application

To get started, you need to configure some basic settings of a Facebook application.
  1. Log in to Facebook using the account you'll use to create the application. This must be a real Facebook account, not an advertising-only "gray account."
  2. Go to the App Dashboard and create a new application.
  3. Note the Application ID provided. You'll use the API Key to call the Ads API and to grant the application permission for your user account (see below).

Using the Ads API with business accounts

Business account users must have a user account. Although business accounts are useful for billing and other purposes, please note the following:
  • You need a user account for Ads API access.
  • Add the user account to the business account as a general user.

Provide authentication

For an app to do ad management, a user (including an app developer) must give the app permission. This permission is called the ads_management extended permission.
An Ads API app is like other Facebook apps, although the Ads API is built on the Graph API. Therefore, please review Facebook for websites and the entire authentication guide to become familiar with the Facebook platform. Please also note the following values from your app summary, which are referred to in the examples below:
  • App ID: referred to below as YOUR_APP_ID
  • App secret (keep this value secret): referred to below as YOUR_APP_SECRET
  • Site URL (a redirect URL): referred to below as YOUR_URL
Prompt the user for extended permission
To enable your app to manage ads for a user, you use the scope parameter to prompt the user for the extended permission of ads_management. Also prompt the user for the extended permission of offline_access if your app makes API calls while the user isn’t logged into your app. For token expiration, see the authentication guide.
The following example uses the scope parameter to prompt the user for ads_management and offline_access. Access is granted when the user clicks the Allow button:
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
scope=ads_management,offline_access
Obtain the access token
If the user clicks the Allow button when you prompt for the extended permissions, the user is redirected to a URL that contains the value of the redirect_uri parameter and an authorization code:
http://YOUR_URL?code=AUTHORIZATION_CODE
Build a URL that includes the endpoint for getting a token, your app ID, your site URL, your app secret, and the authorization code you just received. The URL will be similar to the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&code=AUTHORIZATION_CODE
The response should contain the access token for the user. For additional information, see the authentication guide.
Store the access token
The token should be stored in your database for subsequent API calls.
You should regularly check for validity of the token, and if necessary prompt the user for permission. Even a token that works for offline access can become invalid in a few cases including the following:
  • The user’s password changes
  • The user revokes permissions
As the token can be reset anytime, we request that the developers who use persistent tokens always account for an invalidated token. When a user starts your web application, check for the validity of the token. If necessary, prompt the user for permissions. If this is not possible for your application (e.g., API calls are not based on a user-interface flow, or there’s as script failure), a different way to prompt the user may be necessary. For example, your app could email instructions to the user.

Testing the Ads API

Once Facebook has whitelisted your application, you can test the API calls using the Graph API Explorer tool. The Graph API Explorer enables you to test almost any query you would like to make to the Ads API; read the blog post for all the functionality provided. Please be sure to select your whitelisted application from the "Application" drop down as well as the ads_management permission in the pop-up dialog (under extended permissions) when generating your access token.
The API is live, so Facebook does not provide a sandbox where you can test your code.

Working with Ads objects on the Graph API

You can access a Graph object’s properties with its unique ID, e.g. for the User object:
  • https://graph.facebook.com/UserID
Similarly, accounts and campaigns have unique IDs and you can access specific adAccount and adCampaign objects with URLs like these:
  • https://graph.facebook.com/act_adAccountID
  • https://graph.facebook.com/adCampaignID
All Graph API objects work in a similar way. After you have an access token, try some calls with the adCampaign object.

Paging the response data

For paging the response data in the Graph API, see How-To: Paging with the Graph API and FQL.

Ads API Best Practices

Keep these best practices in mind as you work with the Ads API.

Create New Ads, Don't Edit Existing Ones

You shouldn't change the targeting, title, or body for an ad for purposes of using the ad in slightly modified form elsewhere; you should create a new ad.

Storing User Information

Facebook recommends storing user IDs, session keys, and the Ads Account ID in a manner that makes it easy to programmatically access them and keep them together. This is important because any calls made with an account ID belonging to one user and the session key for another user will fail with a permissions error.

Watch for Changes in Suggested Bids

It's a good idea to run frequent reports on your campaigns, as suggested bids change dynamically in response to bidding by competitors using similar targeting. Bid suggestions get updated within a few hours, depending upon the bidding of competitors.

Use Batch Requests for improved throughput

Batch requests allow you to make multiple requests to the Graph API using a single http call. For more information on Graph API Batch Requests please review the following:

Check if data has changed between calls using ETags.

ETags allow you to quickly check if the response to a Graph API request has changed since you last made it. For more information on ETags please review the following

Use the Power Editor source code

The Power Editor is a HTML 5 based application which uses the Ads API to manage Ads. The source code for the Power Editor is available on GitHub here. Reviewing the source code of the Power is a great way of getting to grips with the Ads API and seeing how an existing application calls the API.

Join the Marketing API Program Facebook Group

If your company has been whitelisted to use the Ads API you may request access to the Marketing API Program group on Facebook. This group is an excellent source of news and help on using the Ads API.

REST API

The Ads API is no longer available on the REST API, For details on migrating to the Graph API please see Migrating from the REST API to Graph API

References


Best Practices

Using batch requests on the Ads API.
ETags support on the Facebook Platform can help you reduce bandwidth consumption and client-side overhead by suppressing output when making Graph API calls.

Reference

Ads API supports all of the currencies supported by Ad Accounts. Those currencies are are follows:
Intro to Action Spec
Intro to Sponsored Stories
Optimized CPM

Specs

An overview of Conversion Specs for the Ads API.
Description of creative specs.
Starting with Action Specs
Overview of Targeting Specs

Advanced Targeting

How to target ad groups at users based on actions taken on the Open Graph.
Topic targeting
Using ZIP codes for location based ad targeting

Queries

How to use the Action Estimate method to query expected activity of an action spec.
Overview on using the Ads API Preview feature.
Details about Stats in the Ads API.
You can retrieve several types of autocomplete data for ad targeting.
An object representing the broad category targeting for an ad account.
An object representing the Facebook objects the user is connected to.
conversion stats
Keyword stats for an adgroup
An object representing the reach estimate for a specific targeting.
Object representing the human-readable description of a targeting spec

Objects

An ad account
An ad account group
An ad campaign
An ad creative
An ad group
Using ad images on the ads API.
Details about users in the Ads API.

Internationalization

Facebook is currently available in over 70 languages, thanks to a framework that allows our user community to translate the text on Facebook. By integrating with Facebook, you can take advantage of our Translations framework immediately, so you can enjoy the benefits that translation can bring to your Platform application or website. If you are interested in Open Graph localization, please refer to Open Graph Internationalization.


Understanding Locales

The locales that Facebook supports are available in an XML file.
Facebook locales follow ISO language and country codes respectively, concatenated by an underscore.
The basic format is ''ll_CC'', where ''ll'' is a two-letter language code, and ''CC'' is a two-letter country code. For instance, 'en_US' represents US English.
There are two exceptions that do not follow the ISO standard: ar_AR and es_LA. We use these to denote umbrella locales for Arabic and Spanish, despite in the latter case having a few more specialized localizations of Spanish.
You can determine this information about a user by examining the locale field of the User Graph API object.

Support Locales in Social Plugins and the JavaScript SDK

If you're rendering a social plugin in an IFrame, Facebook automatically translates the text because it's based on the viewing user's locale.
If you're using XFBML, you need to load the JavaScript SDK in the appropriate locale for your site. For example, if your site is in Spanish, reference this script:
//connect.facebook.net/es_LA/all.js

Internationalizing your Application

The following steps assume you have created an application and have an application ID.

Preparing Your Application for Translation

In order to opt into the Facebook Translations framework, you need to set the native language for your application, then you need to decide into which languages you want your application translated.

Selecting Your Native Language

  1. Go to the My Applications page in the App Dashboard, where you initially configured your application.
  2. Select the application you want translated, then click Edit Settings.
  3. On the Advanced tab, under Contact Info select the Language in which your application is currently written, then save your selection. This selection determines the native language from which translations will occur. If your application is using "English (US)" as the native language you will not see the option and will not be able to change it, as the Open Graph translations need English as the native app language. See this blog post for details.

Choosing Languages for Translation

Once you configure your application's native language, you need to specify into which languages you want your application translated.
  1. Visit the Translations admin panel for your application. Select which application you want to translate from the dropdown menu in the upper right corner.
  2. Enable a language for translation. To enable translation of your application into a particular locale, select the row for the appropriate Language, then check the On check box for that locale. After checking it, users can see any strings that you mark as translatable, and can provide translations for them.
    Note: If this check box is NOT checked, the only people who can translate your application into this language are the application's developers (listed in the App Dashboard) and those designated as the language managers for this language in the Language Managers column.
Once you initiate the translation process, you'll return to the Translations dashboard when you need to do more administration. For now, these steps are the ones necessary to get started.

Registering the Text You Want Translated

Text can come from a lot of places, and it's important that if your application is available in a language that everything is translatable. The following is an exhaustive list of all places that you may find content you need to prepare for the translation process.

Text that gets rendered within your application or website.

Use FBML (for FBML applications) or XFBML (for Facebook websites or IFrame applications) markup tags for this text.

Text entered on facebook.com.

There is a list of static text about your application that you may enter on facebook.com which you may want to have translated. Each of these fields, when submitted or updated on Facebook, will automatically be registered on the Translations application on behalf of your application.
  • Application Name
  • Application Description
  • Tab Name
  • Attachment Text
  • Description (from the Application Profile)
  • About the Developers (from the Application Profile)
  • Text related to the Open Graph action types and aggregations
Once a translation is ready for any of these fields from the Translations application, it will automatically get used on Facebook without any further effort on the part of the developer.

Text sent through Facebook communication channels (like stream attachments).

Wrap the text using the FBML internationalization markup tags. Then, use intl.uploadNativeStrings if you want to register the text to be translatable by users before actually sending it.

Text contained within your databases.

You may have content that isn't rendered directly. For instance, if your application is an online store, you might store a list of item names of your inventory. In order for this text to be registered for translation, use intl.uploadNativeStrings to register all variations of the text that include each item from your database.
Note: This technique should not apply to strings that change frequently, or are user-generated. Each application has a static limit for the number of strings that may be registered at any given time, so it's important to avoid submitting dynamic content for translation.

Text contained within images or other non-text-based representations.

This content cannot be translated directly using Facebook Translations. If you want to serve internationalized images, you need to generate an image for each language you wish to support, and determine the user's locale (for example, via users.getInfo) to decide which image to serve them.

Marking Up Text for Translation

In order for you to submit structured text for use with Facebook Translations, there are a number of FBML and XFBML tags that have been added to accomplish this.
  • fb:intl -- The principal tag for making a string of text translatable.
  • fb:intl-token -- Replaces a token contained within fb:intl with its content.
  • fb:tag -- Renders an HTML tag. Only useful in conjunction with fb:tag-attribute.
  • fb:tag-attribute -- Contains the value of an HTML attribute specified by fb:tag that needs to be translatable.
  • fb:tag-body -- Contains the contents of an HTML tag specified by fb:tag. Only useful when fb:tag-attribute is needed.
  • fb:date -- Renders a date, adjusting the format correctly depending on the locale settings of the viewing user.
  • fb:fbml-attribute -- Similar to fb:tag-attribute, this contains the value of an attribute of an FBML tag, allowing the value to be translated. (FBML only)
  • fb:window-title -- Including this allows the window title of the current IFrame to be translatable. Note that this tag is only useful for Facebook Connect websites. (XFBML only)

Example Code

Let's say you have the following FBML in your application (or XFBML on your site):
Give <fb:name uid="4800348" useyou="false" firstnameonly=true/> 
a copy of "Catcher In the Rye"?
When Facebook renders the FBML, this would yield the proper English sentence 'Give James a copy of "Catcher In the Rye"?'. However, in order to render it in a way that is translatable, this line must be converted to the following:
<fb:intl desc="Asking whether user wants to give a book to someone">
  Give <fb:name uid="4800348" useyou="false"/> a copy of "{book-title}"?
  <fb:intl-token name="book-title">
      Catcher In the Rye
  </fb:intl-token>
</fb:intl>
Some things to note about this code:
  • The variable text (the book title) is a token formatted in curly brackets, since you don't want the actual book title to be part of the translatable text. This string, including the token, is what translators will need to be able to translate, using only the description as context. Wrapping the text in fb:intl-token places the variable text into the string at render time. The name attribute must be the string in the token(s) it is meant to replace. While these components generally can be ordered in any way, you should do something similar to the above, for the sake of readability and to prevent forgetting tokens.
  • The translatable message still contains the fb:name tag. This tag gets displayed as a token when the string is presented to translators, but the token is inserted by Facebook's translation system. You do not need to put it inside curly braces manually. The translator will be presented with the string, "Give {name} a copy of "{book-title}"?" in this case.
Once your FBML text uses these tags, it will be uploaded to the Translations application on the first canvas page load containing this FBML. After that initial page load, it will be translatable both in the Translations application as well as inline by Facebook users. Once the text is translated in, say, Spanish, it will appear to users browsing in the Spanish locale.

Best Practices

Much of this may become clearer after reading the best practices for advice on how to best prepare your applications. We strongly encourage you to do so.

Getting Your Application Translated

Now that you prepared your application or site for translation and registered all the text you want translated, you can start getting the text translated. Any Facebook user can translate your application, but it's much easier for people who have already authorized your application.
Users can translate text in two ways:
  • Inline while using your application.
  • Translating in bulk from the Translations application itself, which is an easy way to translate many strings of text at once.

Inline Translations

Users can translate strings inline if they've enabled this mode of translation. The screenshot below shows what inline translation mode looks like to a user. Underlined strings are available for translation (and voting) simply by right-clicking on the underlined text.

Users can enable inline translating by clicking the link in the Translations dialog on the status bar.

Bulk Translation

The Translations application has a user interface that allows translators to quickly and efficiently translate many strings. To direct a user to translate your application's strings in bulk, link them to https://www.facebook.com/translations/index.php?translate?app=<YOUR_APP_ID>, specifying your application ID.

Learn More

The best way to learn how your application can be translated is to actually try it out. The Facebook Translations application has a help guide for getting started with translating. This may help you better understand the process.

Managing the Translation Process

Use the Translations admin panel to manage the translation process for your applications.
  1. Visit the Translations admin panel for your application. If the default selection is not the application you wish to translate, select the right one from the dropdown in the upper right corner.

  2. Enable it for translation: To enable translation of your application into a particular locale, select the row for the appropriate Language, then check the On check box for that locale. After checking it, users can see any strings that you mark as translatable, and can provide translations for them.
    Note: If this check box is NOT checked, the only people who can translate your application into this language are the application's developers (listed in the App Dashboard) and those designated as the language managers for this language (see the Language Managers column).
  3. Review translated strings: Click the link for the language in the Language column. You are taken to the Browse Phrases tab for text in this language.
  4. Check the progress of the translation effort: The progress bar in the Translation/Approval Progress column gives you a high level idea of what percentage of your text is translated and/or been approved.
  5. Specify language managers: In the Language Managers column, specify which Facebook users can administer translations in the given language. These individuals may view, add, and remove translations regardless whether the application is open to all translators.
  6. Publish in that language: When you decide that the existing translations are sufficient, click the blue Publish link. It turns green and changes to ''Published'', which indicates that all users that view your text while viewing Facebook in this locale will see the translations.

Accessing Your Translations

Facebook Translations has multiple ways for you to view and access the text you've registered for translation, as well as the translations provided by Facebook users. The translation data retrieved from these methods may be used or stored however you choose.
You can always view and edit your text and translations from the Translations admin console. However, you can't export translations from the console currently. You can get the translations programmatically.
There are two programmatic ways for accessing translation data:
  • Calling the intl.getTranslations API method. Call this method to easily query all of your translations for a particular language.
  • Querying the translation FQL table. Query this table for a very select set of translation data.

Best Practices

We may make many assumptions when working with text in code, which may not always hold true in other languages. To help you prepare your application for most languages and quirks, we offer these best practices and lessons learned by the Facebook internationalization team. Unless otherwise indicated, these examples apply to both FBML and XFBML markup.

Be Descriptive

In general, text under 20 characters should have a description (use the desc attribute). A word like "Poke" can vary if it is used as a noun or a verb. Facebook Translations works by creating a hash value from the text and description of the phrase. That means that even a slight change to the original text or description will cause your string to be counted as a completely new one. So err on the side of starting off with a complete description you won't have to clarify later. For example, do this:
<fb:intl desc="Label for name of photo album">Name:</fb:intl>
In some languages, the word for "name" is different depending on whether it's the name of a person, a place, or an object. A description here allows a translator to choose the correct word for this label.
Descriptions should usually indicate context as well as meaning. This is especially important for things like link text that are presented as part of a larger grammatical structure like a sentence.
So do this:
<fb:intl desc="In, 'X's photos are ready to view.'">{name}'s photos</fb:intl>
In languages where nouns change depending on whether they're used as the subject or object of a sentence, this description will allow translators to use the correct form.

Don't Translate Markup

Don't include HTML markup in a translatable string; split the text into multiple translatable strings. Otherwise, translators will be able to modify your markup. Never put tags with behavior such as <a> inside a translatable string, since a translator would be able to make changes to the tag's contents. This is a better way to render an anchor:
<fb:intl>Click {=here} to continue.
  <fb:intl-token name="=here">
<a href="xyzzy">
  <fb:intl desc="In 'Click here to continue'">here</fb:intl>
</a>
  </fb:intl-token>
</fb:intl>

Use CSS instead of Markup

Use CSS rather than markup to confine text to particular parts of the page or to style your text. For example, if you have the text "Next Page" and you want each word on a separate line, put it in a <div> with a maximum width rather than putting a <br> tag in between the two words. Don't split the text into separately translatable units since it will prevent translators from changing word order if needed.
Don't do either of these:
<fb:intl>Next<br/>Page</fb:intl>

<fb:intl>Next</fb:intl><br/><fb:intl>Page</fb:intl>
If a language needs the word for "Page" to come before the word for "Next", it is impossible to translate correctly.
Rather, do this:
<div class="limited-width-box"><fb:intl>Next Page</fb:intl></div>
With appropriate CSS, the browser will word wrap the string appropriately.

Translating Attributes of HTML Tags

There are some HTML tags that have attributes that can take on text values, like the "value" attribute of an <input> tag or the "alt" text of an image. To make situations like these translatable, use fb:tag-attribute. You would format markup for a form like this:
<input type="submit"> 
  <fb:tag-attribute name="value"> 
    <fb:intl desc="Button action: Submit a form">Click here</fb:intl> 
  </fb:tag-attribute> 
</input>

Avoid Layouts Relying on Precise Sizing

Try not to use layouts that depend on the precise onscreen sizes of pieces of text in the original language. For any piece of text, in some languages it is likely to be shorter and in some it will be longer (sometimes significantly so in either direction.) If you have sized your user interface elements such that your text just barely fits, your application will probably not work well in a language with longer words.

Assume Word Order Will Change

Assume that a translator will have to change the word order of every sentence. In particular, don't try to assemble sentences from smaller separately-translatable fragments, because even if you provide excellent descriptions, it's likely you will make it impossible for a translator to come up with a grammatically correct translation. Instead, expand all the possible cases out into separate translatable sentences and choose a complete sentence in your code.
Here's a simple example to avoid:
<fb:intl>You are eating</fb:intl> <fb:intl>at home.</fb:intl>
<fb:intl>You are eating</fb:intl> <fb:intl>at a restaurant.</fb:intl>
Here the code is printing the beginning of the sentence, which doesn't change in English, then choosing one of two possible endings. This is impossible to translate correctly to Chinese, where the phrases for "at home" and "at a restaurant" need to come before the word for "eating".
In this case, use separate phrases:
<fb:intl>You are eating at home.</fb:intl>
<fb:intl>You are eating at a restaurant.</fb:intl>
Here the code chooses one of two complete sentences. The translator can adjust the word order of both sentences as needed, and these can be correctly translated into every language.
Or, say you have a phrase like "You have {number} photos." where you use the word "photo" when the number is 1, expand this out into separate complete sentences line, "You have one photo." and "You have {number} photos.", like this:
<fb:intl>You have one photo.</fb:intl>

<fb:intl>You have {number} photos.
    <fb:intl-token name="number">5</fb:intl-token>
</fb:intl>

Don't Hardcode Punctuation

Different languages use different punctuation symbols; for example, Chinese has two different comma characters that are used in different contexts. And Japanese uses its own end-of-sentence character, which is not an English-style period. In general if you allow translators to translate complete sentences (including periods and commas) this won't be as big an issue for you. So you should include punctuation within the fb:intl tags:
<fb:intl>You have mail.</fb:intl>

<fb:intl>Favorite color:</fb:intl> &lt;input ...>
Including the colon as part of the translatable string means translators can substitute another punctuation mark if applicable, or can insert whitespace between the text and the colon (as is done in French, for example.)

Messing with Your <head> (XFBML Only)

Generally speaking, XFBML will work anywhere in the <body> tag of your page. However, this doesn't account for the title of the window. You can set a window title using the fb:window-title tag, placing it anywhere in your document where normal XFBML can be parsed. It will take the rendered contents of the tag as your document's title. You could now enable a translated window title with the following:
<fb:window-title> 
  <fb:intl desc="Title of a Web page">Welcome!</fb:intl> 
</fb:window-title>

Facebook Query Language (FQL)

The FQL object enables running FQL queries using the Graph API. Facebook Query Language, or FQL, enables you to use a SQL-style interface to query the data exposed by the Graph API. It provides for some advanced features not available in the Graph API, including batching multiple queries into a single call.

Example

Runs the query "SELECT uid2 FROM friend WHERE uid1=me()"
GET /fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=me()&access_token=...

Read

You can issue a HTTP GET request to /fql?q=query where query can be a single fql query or a JSON-encoded dictionary of queries.

Query

Queries are of the form SELECT [fields] FROM [table] WHERE [conditions]. Unlike SQL, the FQL FROM clause can contain only a single table. You can use the IN keyword in SELECT or WHERE clauses to do subqueries, but the subqueries cannot reference variables in the outer query's scope. Your query must also be indexable, meaning that it queries properties that are marked as indexable in the documentation below.
FQL can handle simple math, basic boolean operators, AND or NOT logical operators, and ORDER BY and LIMIT clauses.
For any query that takes a uid, you can pass me() to return the logged-in user. For example:
SELECT name FROM user WHERE uid = me() 
Other functions that are available are now(), strlen(), substr() and strpos().
Here's an example of a subquery that fetches all user information for the active user and friends:
SELECT uid, name, pic_square FROM user WHERE uid = me()
OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())

Multi-query

Evaluates a series of FQL (Facebook Query Language) queries in one call and returns the data at one time.
This method takes a JSON-encoded dictionary called ''queries'' where the individual queries use the exact same syntax as a simple query. However, this method allows for more complex queries to be made. You can fetch data from one query and use it in another query within the same call. The WHERE clause is optional in the latter query, since it references data that’s already been fetched. To reference the results of one query in another query within the same call, specify its name in the FROM clause, preceded by #.
For example, say you want to get some data about a user attending an event. Normally, you’d have to perform two queries in a row, waiting for the results of the first query before running the second query, since the second query depends on data from the first one. But with fql.multiquery, you can run them at the same time, and get all the results you need, giving you better performance than running a series of fql.query calls. First, you need to get the user ID and RSVP status of each attendee, so you’d formulate the first query – query1 – like this:
"query1":"SELECT uid, rsvp_status FROM event_member WHERE eid=12345678"
Then to get each attendee’s profile data (name, URL, and picture in this instance), you’d make a second query – query2 – which references the results from query1. You formulate query2 like this:
"query2":"SELECT name, url, pic FROM profile WHERE id IN (SELECT uid FROM #query1)"
This method also has better performance than running a series of fql.query calls with batch.run.

Sample

Here's a sample for running fql query
<?php
  $app_id = 'YOUR_APP_ID';
  $app_secret = 'YOUR_APP_SECRET';
  $my_url = 'POST_AUTH_URL';

  $code = $_REQUEST["code"];
 
 //auth user
 if(empty($code)) {
    $dialog_url = 'https://www.facebook.com/dialog/oauth?client_id=' 
    . $app_id . '&redirect_uri=' . urlencode($my_url) ;
    echo("<script>top.location.href='" . $dialog_url . "'</script>");
  }

  //get user access_token
  $token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
    . $app_id . '&redirect_uri=' . urlencode($my_url) 
    . '&client_secret=' . $app_secret 
    . '&code=' . $code;
  $access_token = file_get_contents($token_url);
 
  // Run fql query
  $fql_query_url = 'https://graph.facebook.com/'
    . '/fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=me()'
    . '&' . $access_token;
  $fql_query_result = file_get_contents($fql_query_url);
  $fql_query_obj = json_decode($fql_query_result, true);

  //display results of fql query
  echo '<pre>';
  print_r("query results:");
  print_r($fql_query_obj);
  echo '</pre>';

  // Run fql multiquery
  $fql_multiquery_url = 'https://graph.facebook.com/'
    . 'fql?q={"all+friends":"SELECT+uid2+FROM+friend+WHERE+uid1=me()",'
    . '"my+name":"SELECT+name+FROM+user+WHERE+uid=me()"}'
    . '&' . $access_token;
  $fql_multiquery_result = file_get_contents($fql_multiquery_url);
  $fql_multiquery_obj = json_decode($fql_multiquery_result, true);

  //display results of fql multiquery
  echo '<pre>';
  print_r("multi query results:");
  print_r($fql_multiquery_obj);
  echo '</pre>';
?>

Tables

Query this table to return information about a photo album.
Query this table to return read-only properties about an application.
An FQL table containing the requests sent via an app to a user.
Query this table to return information about a checkin. By default, this query returns the last 20 checkins and returns a maximum of 500 checkins.
Query this table to obtain comments associated with one or more [fb:comments]
The comments_info FQL table. Query this table to obtain XIDs for fb:comments objects associated with an application ID.
Query this table to return a user's friends and the Facebook Pages to which the user is connected.
Query this table to return information about a cookie.
Query this table to return the application IDs for which the specified user is listed as a developer in the Developer application.
The domain table provides a read-only mapping between domain names and ids.
Query this table to return information about the admin of a domain.
Query this table to return information about an event.
Query this table to return information about a user's status for an event or see a list of events for a user.
Query this table to return detailed information about a user's family.
Query this table to determine whether two users are linked together as friends.
Query this table either to determine which users have sent friend requests to the logged-in user or to query whether a friend request has been sent from the logged-in user to a specific user.
Query this table to return any friend lists owned by the specified user.
Query this table to determine which users are members of a friend list.
Query this table to return information about a group.
Query this table to return information about the members of a group, or retrieve a list of groups of which a user is a member
The insights table contains statistics about Applications, Pages and Domains
Query this table to return the user IDs of users who like a given Facebook object (video, note, link, photo, or album).
Query this table to return the links a user has posted.
The link_stat table contains counts that show how users on Facebook are interacting with a given link.
An FQL table representing posts that are tagged with a location.
The mailbox_folder table contains information about a user's mailbox folders.
Query this table to return information about messages in a thread.
Query this table to return the notes the current user has written or to return details for a particular note.
Query this table to get the notifications for the current session user, that is, any notification that appears on http://www.facebook.com/notifications.php.
Query this table to return information about a URL in the Open Graph
Query this table to return information about an offer.
Query this table to return information about a Facebook Page.
Query this table to return information about which Facebook Pages the user Admins.
An FQL table that can be used to return a list of a users that are blocked from a Facebook Page.
Query this table to return information about the user who likes a Facebook Page.
Query this table to return information about a Page's milestones.
Query this table to return the permissions the current user has granted to the app.
Query this table to return more descriptive information about extended permissions.
Query this table to return information about a photo.
Query this table to return information about photo source url.
Query this table to return information about a photo tag.
Query this table to return information about a place.
Query this table to return a user's privacy setting for a given object_id.
Query default privacy settings for a user for a particular app
Query this table to return certain (typically publicly) viewable information for a profile.
Query this table to return information a Page's apps.
A Question as represented in FQL.
An option for a question, as represented in FQL.
The votes on a particular option for a question, as represented in FQL.
Query this table to obtain reviews associated with an application, a user or both.
Query this table to determine whether two users are linked together as friends.
Query this table to return standard information about a user, for use when you need analytic information only.
Query this table to return one or more of a user's statuses.
Query this table to return posts from a user's stream or the user's profile.
Query this table to return a filter_key that can be used to query the stream FQL table, as seen through any content filters the user has available on Facebook.
Query this table to return associations between users or Facebook Pages and the items they tag in status posts.
Query this table to determine whether two users are linked together in a subscriber/subscribee relationship and to retrieve a list of users another user subscribes to or is subscribed to by.
Query this table to return information about message threads in a user's Inbox.
Query this table to return the native strings (original, untranslated text in your application interface) and the translated strings for your application.
This table can be used to access information about messages in the new Facebook messaging system.
This table can be used to access information about threads in the new Facebook messaging system.
This table should be used to access information about subscribe and unsubscribe actions performed on a thread in the new Facebook messaging system.
This table should be used to access information about the number of threads in a folder in the new Facebook messaging system.
An FQL table containing the Open Graph URLs that the current session user has Liked.
Query this table to return detailed information from a user's profile.
The video table contains information about videos.
The video_tag table contains information about users tagged in videos.

Dialogs Overview

Dialogs provide a simple, consistent interface to provide social functionality to your users. Dialogs do not require any additional permissions because they require user interaction. Dialogs can be used by your application in every context: within a Canvas Page, in a Page Tab, in a website or mobile web app, and within native iOS and native Android applications.
There are currently 7 Dialogs available for you to use:
  • The Feed Dialog allows a user to post a story to their Timeline and to their friends' News Feeds
  • The OAuth Dialog allows a user to authorize an application as part of an authentication flow.
  • The Add Page Tab Dialog allows a user to add an application to a Facebook Page which they administer.
  • The Friends Dialog allows a user to send a friend request to another user.
  • The Pay Dialog allows a user to make a purchase using Facebook Credits.
  • The Requests Dialog allows a user to send a request to one or more of their friends
  • The Send Dialog allows a user to send a Facebook Message to one or more of their friends.
You can integrate Dialogs into your application by constructing the URLs documented below, or by using a helper method in one of the Facebook SDKs:

Invoking a Dialog directly with a URL

If you're not using one of the Facebook SDK's, you can invoke a Dialog by redirecting the user's browser to a URL. Every dialog has a method name and parameters. The URL to a dialog always starts with
      https://www.facebook.com/dialog/
followed by the name of the dialog and parameters. For example, to ask a user to post a story to their Wall, send them to the Feed Dialog with required parameters:
https://www.facebook.com/dialog/feed?
    app_id=YOUR_APP_ID&
    redirect_uri=YOUR_REDIRECT_URI
Because Dialogs enable simple social interactions, the user must be logged into Facebook to see a dialog. If the user is not already logged in, Facebook will prompt them to login before showing the the Dialog you invoked.
Feed dialog

Common Dialog Parameters

All Dialogs share a few common parameters:
Name Required? Description
app_id Yes Your App ID as shows in your app's settings.
redirect_uri Yes The URL to redirect to after the user clicks a button on the Dialog.
display No. Default is page Display mode in which to render the Dialog. Can be page, popup, iframe, or touch. If you specify iframe, you must have a valid access_token. To get a valid access_token, please see the Authentication guide
show_error No If this is set to true, the error code and error description will be displayed in the event of an error.

Display Modes

Platform Dialogs are all built to seamlessly run in a variety of display contexts on both the web and mobile web. If you're invoking a Dialog using the JS, iOS or Android SDKs, the display mode will be automatically chosen for you based on the platform and the device being used by the user. However, you can force a particular display mode by setting the display parameter to one of the following values:
  • page: By default, dialogs run in full-page mode with a Facebook header and footer. This is appropriate for apps that do a full-page redirect in a normal desktop/laptop web browser.
  • popup: For use in a browser popup no bigger than 400px by 580px. Use this display type to maintain context for the user without needing to perform a full-page redirect.
  • touch: For use on smartphones, mobile devices and small tablets (such as those with screens under 7 inches).
  • iframe: For use by apps when running inside an iframe within a Canvas page on Facebook. Displays the dialog within a lightbox-style overlay. Because of the risk of clickjacking, this is only allowed for some certain dialogs, and requires you to pass a valid access_token. This mode is not supported by the OAuth Dialog.

Dialogs

The Add Page Tab Dialog prompts the user to add an app to a Facebook Page that the user admins. This does not require any extended permissions.
Prompt the user to publish an individual story to a profile's feed
Prompt the user to add a friend.
Prompt the user to authorize and grant your app permissions
Prompt a payment
Requests Dialog
Prompt the user to send a message to a friend, group or email address