Check if already logged to facebook with PHP SDK 4.0 - php

I want to check if already logged in to facebook when navigating to index.php so I would automatically redirect to homepage.
However, my code will only check after clicking on the loggin link.
Facebook\FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("myurl");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
header("location:home.php");
} else {
// show login url
echo 'Login';
}
I checked some other thread about Facebook PHP SDK but there is not much about sdk 4.0. And nothing that worked for me..
I tought I could add a token in the session, however it wouldn't work if I would already be logged in to facebook before my first visit... It would also cause problem if I would logout from facebook without logout from my website.

Since I found this question to be frequently asked without answer, I decided to share what I did with the community.
The $session variable in my code contains an access token which can be used for re-instanciating the session anywhere else simply doing a new FacebookSession('token').
Considering that, when logging in for the first time, I retrieve the token from the $sessionand store it in $_SESSION. Then, I created a simple util function which first check if the $_SESSIONvariable is set, then try to instanciate a new FacebookSession using the stored token. If the stoken is invalid, the session won't instanciate then I can detect it in my util function and return wether the user is actually logged in or not.
Note that an access token is invalidated when facebook user logout.
Login url + token storage :
FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("http://localhost/PoubellesDeMerde/PoubellesDeMerde/index.php");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$_SESSION['token'] = $session->getToken();
} else {
// show login url
echo 'Login';
}
Util function :
public static function isLoggedIn()
{
$id=0;
if(isset($_SESSION['token']))
{
$session = new FacebookSession($_SESSION['token']);
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
$id = $graphObject->getProperty("id");
}
return $id!=0;
}

Related

Displaying posts from owned facebook with the PHP SDK

So I admittedly am quite new to the facebook Graph api, but what I want to do feels like it should be doable.
All I want to do is display posts from a facebook page that is owned by me on a website.
Now I should say that I have achieved this with the api and the php sdk already, but its all of the access token stuff that is perplexing me, I just want a permanent access token so that I don't have to renew it in anyway.
Any help would be much appreciated
Just in case anyone landed on this question and was looking for direction on this subject too
$client = array(
"id" => {APP_ID},
"secret" => {APP_SECRET},
"token" => {ACCESS_TOKEN}, // Generated from the graph api explorer, with the 'manage_posts' extended permission ticked
"page" => {PAGE_ID}
);
FacebookSession::setDefaultApplication($client['id'], $client['secret']);
$session = new FacebookSession($client['token']);
try
{
$response = (new FacebookRequest($session, 'GET', '/oauth/access_token?grant_type=fb_exchange_token&client_id='.$client['id'].'&client_secret='.$client['secret'].'&fb_exchange_token='.$client['token']))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
$token = $data['access_token'];
$response = (new FacebookRequest($session, 'GET', '/'.$client['page'].'?fields=access_token'))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
echo "Access Token: ".$data['access_token']; // this is your never expiring access token
}
catch (FacebookRequestException $e) {
print_r($e);
}
catch (\Exception $e) {
print_r($e);
}
Obviously I do not recommend doing this in any form of production environment, but if you are in a local environment and just need the access token, feel free to use this to find out the access token.

Login with Facebook in Laravel 4

All I'm trying to do is have the user connect with facebook, grab his information (email, name, profile_pic) and register him automatically on my site.
the problem is when I visit /user/login/fb/ I get redirected to the fb application to grant permission and then it redirects me to
http://local.serv/user/login/fb/callback?code=AQB7Uf7pcZSY89WYUKofY8bOgBY1qCcWA5p6_G-9MVdczN60C0TNOgFIi9LBRwquagZ6VbC6_kjD9-D0ZevKHyNGw88LuRJcuqdq2RbwCKNlC02_4eMtiNAWxX76XHm1CzU0F7nSVQ4KxENoDPFpKIs1oV-wQTkO7YuuGznL9UuzfK-hqTtZAIRBvQ_N_yh03LsdgaZ9-f6z5yc5FGnJ3sJyrC-3DGrjkSzhPpJHHk5tr7LorzqW9TNcaFpB9eE51wdsEHOa5oNEWycwzXjY-7Me1Uod3KVBGpb8tzeYVHArphMc2n45IF1pfAWMZZZ51Dw&state=f25e8641df013970542b7463b8899ccf#=
and give me this error
Facebook \ FacebookSDKException (700)
You must provide or set a default application id.
Here are my routes
Route::get('user/login/fb', function() {
FacebookSession::setDefaultApplication('', '');
$helper = new FacebookRedirectLoginHelper('user/login/fb/callback');
$loginUrl = $helper->getLoginUrl();
return "<a href='$loginUrl'>facebook</a>";
});
Route::get('user/login/fb/callback', function() {
// A FacebookResponse is returned from an executed FacebookRequest
$helper = new FacebookRedirectLoginHelper('user/login/fb/callback');
$session = $helper->getSessionFromRedirect();
$request = new FacebookRequest($session, 'GET', '/me');
try {
$response = $request->execute();
$me = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
print_r($me);//->getProperty("id"));
$user = new Giftee;
$user->name = $me->getProperty('first_name') . ' ' . $me->getProperty('last_name');
$user->email = $me->getProperty('email');
$user->photo = 'http://graph.facebook.com' . $me->getProperty('id') . '/picture?type=large';
$user->save();
});
PS: if you have a clear tutorial with views and everything on how to integrate fb login with laravel please do share, I've been looking for days, the material is so limited.
Your Facebook API credentials aren't set when you request the user/login/fb/callback, either add the FacebookSession::setDefaultApplication(...) at the beginning of that route as well or use another library that allows you to set these in a global configuration file.
Your route should look like this :
Route::get('user/login/fb/callback', function() {
FacebookSession::setDefaultApplication(); // your API credentials
// here goes the rest of your code
};

facebook SDK 4.0 infinite redirect loop in php

I've a problem with facebook sdk 4.0
After I clear session/cookies it works fine. But sometimes, and I cannot determine when, if I go to the app, it starts an endless redirect loop!
I've put all my code on git, since documentation doesn't provide exact ansswers:
https://github.com/sandrodz/facebook-canvas-app-sample-sdk-4.0/blob/master/index.php
<?php
// Working canvas APP, FB SDK 4.0
session_start();
// Load SDK Assets
// Minimum required
require_once 'Facebook/FacebookSession.php';
require_once 'Facebook/FacebookRequest.php';
require_once 'Facebook/FacebookResponse.php';
require_once 'Facebook/FacebookSDKException.php';
require_once 'Facebook/FacebookCanvasLoginHelper.php';
require_once 'Facebook/GraphObject.php';
require_once 'Facebook/GraphUser.php';
require_once 'Facebook/GraphSessionInfo.php';
require_once 'Facebook/HttpClients/FacebookHttpable.php';
require_once 'Facebook/HttpClients/FacebookCurl.php';
require_once 'Facebook/HttpClients/FacebookCurlHttpClient.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Faceboob\FacebookSDKException;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
// Facebook APP keys
FacebookSession::setDefaultApplication('XXX','XXXXX');
// Helper for fb canvas authentication
$helper = new FacebookCanvasLoginHelper();
// see if $_SESSION exists
if (isset($_SESSION) && isset($_SESSION['fb_token']))
{
// create new fb session from saved fb_token
$session = new FacebookSession($_SESSION['fb_token']);
// validate the fb_token to make sure it's still valid
try
{
if (!$session->validate())
{
$session = null;
}
}
catch (Exception $e)
{
// catch any exceptions
$session = null;
}
}
else
{
// no $_SESSION exists
try
{
// create fb session
$session = $helper->getSession();
}
catch(FacebookRequestException $ex)
{
// When Facebook returns an error
print_r($ex);
}
catch(\Exception $ex)
{
// When validation fails or other local issues
print_r($ex);
}
}
// check if 1 of the 2 methods above set $session
if (isset($session))
{
// Lets save fb_token for later authentication through saved $_SESSION
$_SESSION['fb_token'] = $session->getToken();
// Logged in
$fb_me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject();
// We can get some info about the user
$fb_location_name = $fb_me->getProperty('location')->getProperty('name');
$fb_email = $fb_me->getProperty('email');
$fb_uuid = $fb_me->getProperty('id');
}
else
{
// We use javascript because of facebook bug https://developers.facebook.com/bugs/722275367815777
// Fix from here: http://stackoverflow.com/a/23685616/796443
// IF bug is fixed this line won't be needed, as app will ask for permissions onload without JS redirect.
$oauthJS = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id=1488670511365707&redirect_uri=https://apps.facebook.com/usaidgeorgia/&scope=user_location,email';";
}
?>
I went ahead to debug line by line, and these are my findings:
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token']))
{
echo '$_SESSION and $_SESSION["fb_token"] are set';
// create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
// validate the access_token to make sure it's still valid
try
{
if (!$session->validate())
{
$session = null;
echo 'access_token is not valid';
}
echo 'access_token is valid';
}
catch (Exception $e)
{
// catch any exceptions
$session = null;
echo 'something error happened ' . $e;
}
}
I get error:
$_SESSION and $_SESSION["fb_token"] are setsomething error happened exception 'Facebook\FacebookSDKException' with message 'Session has expired, or is not valid for this app.' in /home2/nakaidze/public_html/mesamoqalaqo_app/Facebook/FacebookSession.php:247 Stack trace: #0 /home2/nakaidze/public_html/mesamoqalaqo_app/Facebook/FacebookSession.php(221): Facebook\FacebookSession::validateSessionInfo(Object(Facebook\GraphSessionInfo), '148867051136570...') #1 /home2/nakaidze/public_html/mesamoqalaqo_app/user-functions.php(56): Facebook\FacebookSession->validate() #2 /home2/nakaidze/public_html/mesamoqalaqo_app/index.php(2): require('/home2/nakaidze...') #3 {main}
The access token you're using in $_SESSION['fb_token'] has expired. By default the access token returned by Facebook lasts for 2 hours and then it expires.
After you get the FacebookSession for the first time, you need to extend the access token it returned and save it in your $_SESSION['fb_token']:
$session = $helper->getSession();
$accessToken = $helper->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
$_SESSION['fb_token'] = (string) $longLivedAccessToken;
Also, when you validate the access token with validate(), it will throw if it's not valid:
// validate the access_token to make sure it's still valid
try
{
$session->validate();
echo 'access_token is valid';
}
catch (FacebookSDKException $e)
{
$session = null;
echo 'Access token is no longer valid, need to get a new token';
}
This might help clarify info about Facebook access tokens.

Facebook SDK 4 for PHP - no login grab some events

I try to use the Facebook SDK 4 for PHP,
but there is one thing that i don't understand : use it with an app access token!
i tried different tokens to initialize FaceBookSession, but i don't understand how it works... :/
with this sample code for example :
$request = new FacebookRequest(
$session,
'/480602392011337/events?fields=id,end_time,description,is_date_only,location,name,start_time&since='.date('Y-m-d',strtotime('-1 year')).'&until='.date('Y-m-d',strtotime('+1 year')).'&limit=500',
//'/480602392011337/events',
'GET'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
Thanks for the help! :)
I finally found the solution (thx Google), simply use FacebookSession::newAppSession();
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('xxxxxx','xxxxxxx');
// Get the access token for this app
$session = FacebookSession::newAppSession();
// make the API call, $datas contains the events for the facebook fan page BDE Polytech Marseille
try {
$request = new FacebookRequest(
$session,
'GET',
'/{page-id}/events?fields=id,end_time,description,is_date_only,location,name,start_time&since='.strtotime('-1 year').'&until='.strtotime('+1 year').'&limit=500'
);
$response = $request->execute();
$datas = $response->getGraphObject()->asArray();
}catch (FacebookRequestException $e) {
echo $e->getMessage();
}catch (\Exception $e) {
echo $e->getMessage();
}

facebook api blank response and no exception

$facebook = new Facebook(array(
'appId' =>Yii::app()->params['FBappId'],
'secret' =>Yii::app()->params['secret'] ,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
echo $accessToken=$facebook->getAccessToken();
echo '<br/>';
$user_profile = $facebook->api('/me');
print_r($user_profile); echo "normal sdk"; exit;
} catch (FacebookApiException $e) {
echo $e; exit;
$user = null;
}
}
echo "normal sdk end";exit;
i tried with php sdk 3.3.2 and user login by facebook it prints the token and user info untill token expire. after about one hour i check by token debugger session expired and it give exception once and then blank response.but in another tab facebook is being accessed .
my question is
1.When token expired, is there any inbuild method to get valid token again ?
2.Why blank response? everytime it should throw exception
You can use Facebook's Debug Tool to check the validity of your access token.
The normal access token expires in 2 hours, and the extended token lasts for 2 months.
If you want the extended token, go though this: How to extend access token validity since offline_access deprecation
Well, If you are getting blank for $facebook->api('/me'); this simply means that the user have not authorized the app yet. Try something like this-
$user_id = $facebook->getUser();
echo $uid;
if($user_id){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
}
}else{
$login_url = $facebook->getLoginUrl();
echo("<br>login url=".$login_url);
};

Categories