Friday, June 8, 2012

Facebook OAUTH dialog with new Graph API

Demo Download

You need a PHP enabled real server to test this application.

Login to your Facebook account and add a developer application
Facebook developers
tips : App Domain should be in myDomain.com format
Canvas URL should point to a directory in your server.
eg : http://www.mysite.com/fb/

Get the application id and secret key for your application.
Now we are going to build our application.

Download facebook php sdk from github. Upload files inside 'src' directory to  your server.

You need to enter your app id and secret key in the source code when communicating with Facebook server. They help identify your application uniquely among other applications. Facebook server uses these keys whenever it receives a request  from any application for validation purposes.
From the developer's perspective, it is a good practice to keep those configuration data separate from the general application.
Therefore, create a config.php file and add these data.

config.php

[sourcecode language="php"]
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'SECRET_KEY'
'cookie' => true,
'appBaseUrl' => 'http://apps.facebook.com/fb',
));
?>
[/sourcecode]



appBaseUrl represents the index.php file in your server where you hope to deploy your application.
In my case,  I specified my canvas URL as http://www.mysite.com/fb/
Accordingly, my Base URL should be something like http://apps.facebook.com/fb

We have included php sdk inside config.php. So no need to bother about it later. We only need to include config.php

Create index.php and add the following code.

[sourcecode language="php"]
<?php
require_once('config.php');

$user = $facebook->getUser();
$me = null;
if($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
}
}
if($me) {
echo 'User is logged in and has a valid session';
//header('Location:REDIRECTION_URL');
}
else {
$loginUrl = $facebook->getLoginUrl(array('req_perms' =>
'publish_stream',));

/**Use this code for iframe application*/
//echo '<script> top.location.href="'. $loginUrl .'"; </script>';
/**Use this code for third party application*/
header('Location: '.$loginUrl);
}

$logoutUrl = $facebook->getLogoutUrl(array('next' => 'http://apps.
facebook.com/fb/',));
?>

<br>

<a href ="#" onclick="top.location.href='<?php echo $logoutUrl; ?>';
return false;">Logout</a>


[/sourcecode]

upload both config.php and index.php to the same directory where facebook php sdk resides.
Test your application.
Happy Facebooking!

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...