Wednesday, August 22, 2012

Facebook Registration Plugin (With Custom Fields and Examples)

Facebook Registration Plugin (With Custom Fields and Examples)

In this post, I will show you how to implement facebook registration plugin, and I will create some examples, with custom fields, with both the iframe version and XFBML.

You can check the examples directly in here: Facebook Registration Plugin Examples

Scroll down for the entire source code.

The facebook social plugin can be used for users with a facebook account, or users without a facebook account.
If the user does not have a facebook account, or if the user is not logged in to their facebook account, the below subscription form will be displayed.
Facebook Registration Plugin

If the user has a facebook account and is logged in, the registration form will be pre-filled to save the user time. This is very useful to register the user quickly with one mouse click.
Facebook Registration Plugin Pre-filled

Sometimes you might only want users with a facebook account to be able to register on your site. This can be specified with a parameter that will be explained later on. The following registration form will be displayed if the user is not logged in to facebook.
Facebook Registration Plugin Force Login


I will not go in the already explained details on facebook. In this post, I will assume that you have already read this: http://developers.facebook.com/docs/plugins/registration/

For this plugin to work, you will need a facebook app id and a facebook app secret, if you havne't created a facebook app yet, I suggest you read this tutorial first to create an app: Facebook App Tutorial - The Basics

You will also need to set the redirect URI, in my case, I'm going to set it to the same file location of the subscription form in order to display the output.

 

 

Facebook registration plugin (iframe) without custom fields:

In the first example, I'm going to build the registration plugin using iframe and without any custom fields. Simply the code will be as follows:

<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>Without Custom Fields</h2>
<iframe src="http://www.facebook.com/plugins/registration?
         client_id=<?php echo $API_KEY; ?>&
         redirect_uri=<?php echo $redirect_URI; ?>&
         fb_only=false&
         fields=name,birthday,gender,location,email"
    scrolling="auto"
    frameborder="no"
    style="border:none"
    allowTransparency="true"
    width="530"
    height="330"
>
</iframe>

<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

    }
}
?>


<?php
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, '-_', '+/'));
}
?>



Facebook registration plugin (iframe) with custom fields:

In this example, I'm going to build the registration plugin using iframe and with custom fields
To use custom fields, we will need to use JSON arrays 
The below example is an array from facebook tutorial, you can define checkbox, date, select, captcha to be filled...

[
 {'name':'name'},
 {'name':'email'},
 {'name':'location'},
 {'name':'gender'},
 {'name':'birthday'},
 {'name':'password'},
 {'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'}
]

The code will be as follows:

<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>With Custom Fields</h2>
<iframe src="http://www.facebook.com/plugins/registration?
         client_id=<?php echo $API_KEY; ?>&
         redirect_uri=<?php echo $redirect_URI; ?>&
         fb_only=false&
         fields=[
    {'name':'name'},
    {'name':'birthday'},
    {'name':'gender'},
    {'name':'location'},
    {'name':'email'},
    {'name':'favoriteFood', 'description':'Favorite Food', 'type':'select', 'options':{'0':'Pizza','1':'Burger','2':'Hot Dog','3':'Tuna'}},
    {'name':'graduated', 'description':'Graduation Date', 'type':'date'},
]"
    scrolling="auto"
    frameborder="no"
    style="border:none"
    allowTransparency="true"
    width="530"
    height="400"
>
</iframe>
<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //custom fields
        $favoriteFood = $response['registration']['favoriteFood'];
        $graduated = $response['registration']['graduated'];


        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

        //print custom fields
        echo '<h3>Custom Fields Values</h3>';
        echo 'Favorite Food: ' . $favoriteFood . '<br />';
        echo 'Graduated: ' . $graduated . '<br />';
    }
}
?>


<?php
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, '-_', '+/'));
}
?>

Facebook registration plugin (iframe) without custom fields and only for facebook users:

Sometimes you might only want to allow facebook users to register on your website, you can use the attribute fb_only=true to achieve this.


<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>Without Custom Fields - Only Facebook users allowed.</h2>
<iframe src="http://www.facebook.com/plugins/registration?
         client_id=<?php echo $API_KEY; ?>&
         redirect_uri=<?php echo $redirect_URI; ?>&
         fb_only=true&
         fields=name,birthday,gender,location,email"
    scrolling="auto"
    frameborder="no"
    style="border:none"
    allowTransparency="true"
    width="530"
    height="330"
>
</iframe>


<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

    }
}
?>


<?php
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, '-_', '+/'));
}
?>



Facebook registration plugin (XFBML) with custom fields: 

If you wish to use XFBML instead of iframe, with custom fields, you can use the below example:


<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>With Custom Fields - XFBML</h2>
<fb:registration
fields="[
    {'name':'name'},
    {'name':'birthday'},
    {'name':'gender'},
    {'name':'location'},
    {'name':'email'},
    {'name':'favoriteFood', 'description':'Favorite Food', 'type':'select', 'options':{'0':'Pizza','1':'Burger','2':'Hot Dog','3':'Tuna'}},
    {'name':'graduated', 'description':'Graduation Date', 'type':'date'},
]"
  redirect-uri="<?php echo $redirect_URI; ?>"
  width="530">
</fb:registration>
<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //custom fields
        $favoriteFood = $response['registration']['favoriteFood'];
        $graduated = $response['registration']['graduated'];


        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

        //print custom fields
        echo '<h3>Custom Fields Values</h3>';
        echo 'Favorite Food: ' . $favoriteFood . '<br />';
        echo 'Graduated: ' . $graduated . '<br />';
    }
}
?>


<?php
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, '-_', '+/'));
}
?>



More info about the facebook registration plugin can be found in here: http://developers.facebook.com/docs/plugins/registration/
Examples can be found in here: Facebook Registration Social Plugin Examples

Any questions or suggestions, please post them below!