Implementing the Facebook Like Gate

In the previous example, the 'Facebook PHP SDK' hosted in the Heroku servers was downloaded and used. Now it will be downloaded from GitHub and be included manually. Download the 'Facebook PHP SDK' from GitHub.

https://github.com/facebook/php-sdk

facebook php sdk on github

Extract it. We need only facebook.php and base_facebook.php files. Copy them to app directory. Delete all other files in .git folder. Now there should be only 4 files. Add new files to the git repository.

git add facebook.php
git add base_facebook.php

facebook app files

Now edit the index.php file to match our simple like gate requirements. First create a 'Facebook Object'.

require 'facebook.php';

$facebook = new Facebook(array(
'appId' => '405567522824849',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true
));

Now 'Facebook Object' exists. Objects have methods. Use 'getSignedRequest' method. It contains a value called 'page-liked'. Use it to check whether visitor has already 'liked' the page.

$signed_request = $facebook->getSignedRequest();

if ( $signed_request['page']['liked'] )

Conditionally check the 'liked' state and take further actions.

if ( $signed_request['page']['liked'] ){
   echo 'A fan.';
}
else
{
   echo 'Not a fan yet.';
}

Now the 'index.php' file should look like this.

require 'facebook.php';

$facebook = new Facebook(array(
'appId' => '405567522824849',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
, 'cookie' => true
));

$signed_request = $facebook->getSignedRequest();

if ( $signed_request['page']['liked'] )
{
   echo 'A fan.';
}
else
{
   echo 'Not a fan yet.';
}

facebook app index file

If one has not liked the page yet, it displays 'Not a fan'.

not a fan yet

After the one liked the page. It displays 'A fan'.

a liked facebook fan

Visit app integrated page tab below.

https://www.facebook.com/pages/PHP-Sri-Lanka/155553284581042?sk=app_405567522824849

Try It Yourself!

Have a look at the other parts of this tutorial.

Part 1: Simple Facebook Like Gate with Heroku Hosting
Part 2: Developing and Deploying with Heroku
Part 3: Implementing the Facebook Like Gate

No comments:

Post a Comment