Facebook has recently introduced Graph API and simplified many things. The new Graph API attempts to drastically simplify the way developers read and write data to Facebook.The Graph API uses OAuth 2.0 for authorization. OAuth 2.0 is a simpler version of OAuth that developers used earlier for authorization as $facebook->require_login(). (by the way, old token still works)
In the previous version, RequireLogin was a one line simple way of getting authorization for user. When I upgraded to OAuth 2.0, I had a hard time getting my user authenticated which looked like very simple thing in pre Graph API days.
Here is how I finally manage to put together for my latest facebook app.
To authenticate user in Graph API, first of all, download the Facebook PHP SDK facebook.php and put it inside includes folder. After that, get the Application Id, API key, application secret and canvas url of your facebook app and put it inside following $fbconfig array.
$fbconfig['appid'] = "Application id here";
$fbconfig['api'] = "API Key here";
$fbconfig['secret'] = "App Secret here";
$fbconfig['canvas_url'] = "http://apps.facebook.com/your_app_name/";
try{
include_once 'includes/facebook.php';
}
catch(Exception $o){
print_r($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
'domain' => "Your Canvas Callback URL domain here"
));
$session = $facebook->getSession();
if (!$session) {
echo RequestforPermission();
}
else { //got session
try {
$me = $facebook->api('/me');
if(!IsApplicationUser($me['id'])) {
//InsertApplicationUser($me);
//create a function and insert the user info
//into App DB for later use
}
}
catch (FacebookApiException $e) {
RequestforPermission($fbconfig['canvas_url'] );
}
}
Please add this function “RequestforPermission” as well in this file.
function RequestforPermission($next_url) {
global $facebook;
$loginUrl=$facebook->getLoginUrl(array(
'canvas'=>1,
'fbconnect'=>0,
'display'=>'page',
'next'=>$next_url,
'cancel_url'=>'http://www.facebook.com/',
'req_perms'=>'email,publish_stream',
));
return ' ';
} // end redirect function
Put all this code into a file named “fb-authentication.php” and simply include “fb-authentication.php” in those files in your application where you want Facebook user authentication.
Hope that helps.
Cheers.
hi this code gave me an error because
the function RequestforPermission you declared it with an argument and you called it without an argument can u explaine mee why u did this ?
I did call it with argument like this:
I have above defined $fbconfig[‘canvas_url’] like this:
This canvas url you need to set to your app.
Cheers!
OOOOOOOOORRRRR my god
thank you so much i’ve been looking for three days now and i really mean 3 whole days and this works
woooop wooop beer time now me thinks