User login

Facebook Registration Plugin

Introduction

The registration plugin allows users to easily sign up for your website with their Facebook account. The plugin is a simple iframe that you can drop into your page. When logged into Facebook, users see a form that is pre-filled with their Facebook information where appropriate.
The registration plugin gives you the flexibility to ask for additional information which is not available through the Facebook API (e.g. favorite movie). The plugin also allows users who do not have a Facebook account, or do not wish to sign up for your site using Facebook to use the same form as those who are connecting with Facebook. This eliminates the need to provide two separate login experiences.

Example


<iframe src="http://www.facebook.com/plugins/registration.php?
             client_id=113869198637480&
             redirect_uri=http%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fecho%2F&
             fields=name,birthday,gender,location,email"
        scrolling="auto"
        frameborder="no"
        style="border:none"
        allowTransparency="true"
        width="100%"
        height="330">
</iframe>

Attributes

Attribute Description
client_id Your App ID.
redirect_uri The URI that will process the signed_request. It must be prefixed by your Site URL.
fields Comma separated list of Named Fields, or JSON of Custom Fields.
fb_only Optional. (boolean) Only allow users to register by linking their Facebook profile. Use this if you do not have your own registration system. Default: false.
width Optional. (int) The width of the iframe in pixels. If the width is < 520 the plugin will render in a small layout.

Named Fields

Specify these in the order you want them to appear in the form. The name field must always be the first field.

Field type Description
name Full name of the user
birthday Returned as mm/dd/yyyy
email Email address of user (if the user registers with her Facebook account, this will be a verified email address)
gender Gender of user
location Name and ID of the user's current city
password A newly created password (not their Facebook password)
captcha A test to stop automatic registration

Less common fields:

Field type Description
first_name The first name of the user. Useful with view=not_prefilled.
last_name The last name of the user.

Custom Fields

You may also request data from users that isn't present on Facebook. To do this, you can use a JSON string in the fields attribute instead of the CSV. For example:

Which has fields set to

[
 {"name":"name"},
 {"name":"email"},
 {"name":"location"},
 {"name":"gender"},
 {"name":"birthday"},
 {"name":"password",   "view":"not_prefilled"},
 {"name":"like",       "description":"Do you like this plugin?", "type":"checkbox",  "default":"checked"},
 {"name":"phone",      "description":"Phone Number",             "type":"text"},
 {"name":"anniversary","description":"Anniversary",              "type":"date"},
 {"name":"captain",    "description":"Best Captain",             "type":"select",    "options":{"P":"Jean-Luc Picard","K":"James T. Kirk"}},
 {"name":"force",      "description":"Which side?",              "type":"select",    "options":{"jedi":"Jedi","sith":"Sith"}, "default":"sith"},
 {"name":"live",       "description":"Best Place to Live",       "type":"typeahead", "categories":["city","country","state_province"]},
 {"name":"captcha"}
]

fields is a JSON Array of Objects. Any built in fields only have a name field. Custom fields have:

Name Description
name The name on the HTML <input> element. This will be the name of the attribute when you decode the signed_request.
description The label to show the user.
type The field type. Supported values are text, date, select, checkbox and typeahead.
view When to show this field. There are two views: prefilled and not_prefilled. prefilled means the user is registering using her Facebook account, not_prefilled means the user is not registering with her Facebook account. This parameter is useful if, for example, you only require a password for users not registering using their Facebook account. Default: Display this field in both views.

Some attributes only apply to fields of a certain type:

Name Description
options For type:select. An object of "submit value" to "user description ".
categories For type:typeahead. An array of Open Graph protocol types that are valid for this field.
default For type:select and type:checkbox. Contains the key to select by default instead of showing "Select on" for type:select. Contains the word checked to make a type:checkbox checked by default.

XFBML

There is also an XFBML tag for use with the Javascript SDK. It will resize the iframe fluidly as its size changes.

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#appId={YOUR_APP_ID}&xfbml=1"></script>
 
<fb:registration 
  fields="name,birthday,gender,location,email" 
  redirect-uri="http://developers.facebook.com/tools/echo/"
  width="530">
</fb:registration>

Login + Registration Flows

When prompting your users to login or register, there is an XFBML button that you will probably find useful.

<fb:login-button
registration-url="http://developers.facebook.com/docs/plugins/registration" />

If the user arrives at your site logged out of Facebook, the button will say Login. When the user clicks it, she will be prompted to enter her Facebook username and password. If she has not registered for your site, she will be redirected to the URL you specify in the registration-url parameter. If she has already registered for your site, the button will fire an onlogin() Javascript event. When this event is fired you should login the user to your site.
If the user arrives logged into Facebook, but has not registered for your site, the button will say Register and clicking it will take the user to your registration-url.
Lastly, if the user is logged into Facebook and already connected to your application, the button will say Login and won't do anything when clicked (but your application should detect this state using the getLoginStatus method and not show the button).
See our best practices and diagrams of how all of this fits together, for an overview of how to structure your application.

Reading the data

The data is passed to your application as a signed request. The signed_request parameter is a simple way to make sure that the data you're receiving is the actual data sent by Facebook. It is signed using your application secret which is only known by you and Facebook. If someone were to make a change to the data, the signature would no longer validate as they wouldn't know your application secret to also update the signature.

Read more about signed requests on the canvas authentication documentation.

The result of decoding the signed_request will be a JSON Object with the following format:

{
   "oauth_token": "...big long string...",
   "algorithm": "HMAC-SHA256",
   "expires": 1291840400,
   "issued_at": 1291836800,
   "registration": {
      "name": "Paul Tarjan",
      "email": "fb@paulisageek.com",
      "location": {
         "name": "San Francisco, California",
         "id": 114952118516947
      },
      "gender": "male",
      "birthday": "12/16/1985",
      "like": true,
      "phone": "555-123-4567",
      "anniversary": "2/14/1998",
      "captain": "K",
      "force": "jedi",
      "live": {
         "name": "Denver, Colorado",
         "id": 115590505119035
      }
   },
   "registration_metadata": {
      "fields": "[\n {'name':'name'},\n {'name':'email'},\n {'name':'location'},\n {'name':'gender'},\n {'name':'birthday'},\n {'name':'password',   'view':'not_prefilled'},\n {'name':'like',       'description':'Do you like this plugin?', 'type':'checkbox',  'default':'checked'},\n {'name':'phone',      'description':'Phone Number',             'type':'text'},\n {'name':'anniversary','description':'Anniversary',              'type':'date'},\n {'name':'captain',    'description':'Best Captain',             'type':'select',    'options':{'P':'Jean-Luc Picard','K':'James T. Kirk'}},\n {'name':'force',      'description':'Which side?',              'type':'select',    'options':{'jedi':'Jedi','sith':'Sith'}, 'default':'sith'},\n {'name':'live',       'description':'Best Place to Live',       'type':'typeahead', 'categories':['city','country','state_province']},\n {'name':'captcha'}\n]"
   },
   "user_id": "218471"
}

This format is designed to very closely resemble the output of the Graph API. The signed request includes a registration_metadata field. You should verify this field exactly matches the field param you specified in the registration plugin to ensure the data is from your registration form.

If the user chooses to register without using her Facebook account, the oauth_token, user_id, and expires parameters will not be included in the signed request.

PHP Example reading signed_request

Note: Replace your_app_id with your own application id and your_app_secret with your own application secret key

<?php
define('FACEBOOK_APP_ID', 'your_app_id');
define('FACEBOOK_SECRET', 'your_app_secret');
 
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, '-_', '+/'));
}
 
if ($_REQUEST) {
  echo '<p>signed_request contents:</p>';
  $response = parse_signed_request($_REQUEST['signed_request'], 
                                   FACEBOOK_SECRET);
  echo '<pre>';
  print_r($response);
  echo '</pre>';
} else {
  echo '$_REQUEST is empty';
}
?>

original page can be found here: http://developers.facebook.com/docs/user_registration