Facebook Graph API, drastically simplify the way developers read and write data to Facebook. It presents a simple, consistent view of the Facebook social graph, uniformly representing objects in the graph (e.g., people, photos, events, and pages) and the connections between them (e.g., friend relationships, shared content, and photo tags).
There is a lot of tutorial out there that talking about how to authenticate user using Facebook Graph API. Today I will share with you simple tutorial how to authenticate user using Facebook Graph API in cakephp based on my experience.
CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL auto_increment, `oauth_provider` varchar(10) default NULL, `oauth_uid` varchar(64) default NULL, `access_token` text, `username` text, `created` datetime default NULL, `modified` datetime default NULL, PRIMARY KEY (`id`), KEY `oauth_uid` (`oauth_uid`) ) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=latin1
oauth_provider is from where user registered come from, for example facebook, twitter etc. oauth_uid is the user id given by oauth provider.
Register your application to get an app ID and secret, give it name and click agree, grab the API Key and Application Secret.

Go to website tab, fill Site URL with your application url, for axample http://localhost/fboauth?.
You need to downloade CakePHP Framework. The latest version when im writing this tutorial is 1.3.5 version. On core.php (/app/config/core.php) , change the value of ‘Security.salt’ and ‘Security.cipherSeed’.
Rename database.default.php (/app/config/database.default.php) to database.php, and set the database connection.
class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '127.0.0.1',
'login' => 'root',
'password' => 'root',
'database' => 'fboauth',
'prefix' => '',
);
}
Grab the New Facebook Graph API from GitHub. Copy the facebook.php to /app/vendor/.
Lets simplify the creation of model, view and controller using CakePHP Bake.
After baking, we have all model, controller and view for our app, including for the admin. Then we continue with adding login, callback, logout and home action on users_controller (/app/controller/users_controller.php).
class UsersController extends AppController {
var $name = 'Users';
#once application loaded, we will redirect to this controller
function home(){
}
function login(){
}
function callback(){
}
function logout(){
}
}
On login action, first, we need to import facebook sdk.
function login(){
//import facebook sdk
App::import('Vendor', 'facebook');
$facebook=new Facebook(array(
'appId'=>'ad249ee9b242c34e0921636128cxxxxx',
'secret'=>'12f1df2ddfe9e31085591b522ebxxxxx',
'cookie'=>true
));
#generate facebook session
$session=$facebook->getSession();
# generate login url
$login_url = $facebook->getLoginUrl(array(
'next' => 'http://localhost/fboauth/users/callback',
));
#if session available
if(!empty($session)){
$this->Session->write('uid',$session['uid']);
$this->Session->write('username',$session['name']);
$this->redirect(array('controller'=>'users','action'=>'home'),null,true);
}else{
$this->redirect($login_url);
}
}
Callback is the action we will call or the url we will redirect once user authentication is success. The key is on ‘next’ => ‘http://localhost/fboauth/users/callback’, in login action.
function callback(){
App::import('Vendor', 'facebook');
$facebook=new Facebook(array(
'appId'=>'ad249ee9b242c34e0921636128cxxxxx',
'secret'=>'12f1df2ddfe9e31085591b522ebxxxx',
'cookie'=>true
));
$session=$facebook->getSession();
if(!empty($session)){
try{
$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$session['access_token']));
}catch(FacebookApiException $e){
error_log($e);
}
if(!empty($user)){
//check user on users table by oauth_uid
$user_id=$this->User->findByOauthUid($user->id);
//if empty/ ser not found then insert into table
if(empty($user_id)){
$this->data['User']['oauth_provider']='facebook';
$this->data['User']['oauth_uid']=$user->id;
$this->data['User']['access_token']=$session['access_token'];
$this->data['User']['username']=$user->name;
if($this->User->save($this->data)){
$this->Session->write('uid',$user->id);
$this->Session->write('access_token',$session['access_token']);
$this->Session->write('username',$user->name);
$this->Session->setFlash(__('Your profile has been saved', true));
$this->redirect(array('controller'=>'users','action'=>'home'));
}else{
$this->Session->setFlash(__('Sorry, we could not save your profile. Please, try again.', true));
$this->redirect(array('controller'=>'users','action'=>'home'),null,true);
}
}else{
$this->Session->write('uid',$user_id['User']['oauth_uid']);
$this->Session->write('acces_token',$user_id['User']['access_token']);
$this->Session->write('username',$user_id['User']['username']);
$this->redirect(array('controller'=>'users','action'=>'home'),null,true);
}
}
}else{
$this->Session->setFlash(__('Sorry, we could not authenticate you.', true));
$this->redirect(array('controller'=>'fans','action'=>'home'),null,true);
}
}
The logout action is pretty simple, just destroy all session.
function logout(){
$this->Session->destroy();
$this->Session->setFlash('You have successfully logged out.');
$this->redirect(array('controller'=>'users','action' => 'home'));
}
Once application loaded we will redirect page to home.ctp. You can set this configuration in routes.php.
<?php __('Users Home');?>
<?php $uid=$this->Session->read('uid'); if(!empty($uid)){ echo ""; echo "
Welcome ".$this->Session->read('username')."
"; echo ""; echo ""; echo $this->Html->link('Logout',array('controller'=>'users','action'=>'logout')); echo ""; }else{ echo $this->Html->link('Login',array('controller'=>'users','action'=>'login')); } ?>
Router::connect('/', array('controller' => 'users', 'action' => 'home'));
User Authentication using graph is pretty simple. Just make sure you set the right application setting. Once user authenticated and user data inserted into table, then you can playing arround with other API call. If your application need user email and application able to write on users wall, you can add extended permission by put additional extended permission on your login-url, ex:
$login_url = $facebook->getLoginUrl(array( 'req_perms' => 'email,user_birthday,status_update,publish_stream', 'next' => 'http://localhost/fboauth/users/callback', ));
Because of the demo file grab your access token, dont forget to delete your profile when you finish try the demo file by click here.
<!-- SEO SearchTerms Tagging 2 Plugin -->