<?php
session_start();
//included file and use
$app_id = 'xxx';
$app_secret = 'xxx';
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper("`http://example/facebook4.0`/", $app_id, $app_secret);
try
{
$session = $helper->getSessionFromRedirect();
}
catch(FacebookRequestException $ex) { }
catch(Exception $ex) { }
$loggedIn = false;
if (isset($session))
{
if ($session)
{
$loggedIn = true;
try { //logged here and get data
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
print_r($user_profile); //print data
}
catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
if(!$loggedIn) //if user is not online // get link and add scope
{
$loginUrl = $helper->getLoginUrl(array('public_profile','email'));
echo "<a href='$loginUrl'>Login With Facebook</a>";
}
else
{
print_r($user_profile); //logout link is generated here
echo '<br><br>Logout'; //print to sceen
// i dont have more comment to write stack over flow please update it without eating my head to write comments here
}
?>
It was working from last week but not working today at all, after redirecting it display nothing
It can be that your appID and app Secret have changed. Try confirming that .
Related
I am creating a facebook quiz, but i had stuck with the following problem a couple of days. When user starts the game and after click "continue as" (the screen where facebook asks to get a couple of users information) i want to check whether that user who enters in the game is admin or not. So far, when user allow to share his informations, he enters in the game as user. I've tried a couple of different solutions, i have tried with sending a couple of different api's, i have read a tons of examples but so far i don't have any luck. At developers.facebook.com where my app is i have set the manage_pages and my user profile is select as a "administrator". This is my login.php script (the commented out code are my checked solutions). Any help will be much appreciated.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
include_once ('fb_sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => '*******',
'app_secret' => '*******',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getCanvasHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
/*try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}*/
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=first_name, last_name, email');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
echo "<script>window.top.location.href='https://apps.facebook.com/facebookquiz/'</script>";
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// priting basic info about user on the screen
$first_name = $profile['first_name'];
$last_name = $profile['last_name'];
$email = $profile['email'];
$fbUserId = $profile['id'];
print_r ($profile);
include_once('database/dbInsert.inc');
include_once('database/db_select.inc');
$fbUser = getUserByFBID($fbUserId);
if($fbUser == false){
$userID = insertUserInfo($fbUserId,$first_name, $last_name, $email);
$_SESSION['user_id'] = $userID;
}else{
$_SESSION['user_id'] = $fbUser->Id;
}
header("Location: index.php");
//redirect if is administrator
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile', 'publish_actions', 'manage_pages']; // optionnal 'user_managed_groups'
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/login.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
?><?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
include_once ('fb_sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'app-if',
'app_secret' => 'app-secret',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getCanvasHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
/*try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}*/
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=first_name, last_name, email');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
echo "<script>window.top.location.href='https://apps.facebook.com/facebookquiz/'</script>";
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// priting basic info about user on the screen
$first_name = $profile['first_name'];
$last_name = $profile['last_name'];
$email = $profile['email'];
$fbUserId = $profile['id'];
print_r ($profile);
include_once('database/dbInsert.inc');
include_once('database/db_select.inc');
$fbUser = getUserByFBID($fbUserId);
if($fbUser == false){
$userID = insertUserInfo($fbUserId,$first_name, $last_name, $email);
$_SESSION['user_id'] = $userID;
}else{
$_SESSION['user_id'] = $fbUser->Id;
}
/*$getPages = (new Facebook\FacebookRequest(
$session,
'GET',
'/me/accounts'
))->execute()->getGraphObject()->asArray();
$pageID = $getPages['data'][0]->id;
$pageAccessToken = $getPages['data'][0]->accessToken;
(new FacebookRequest(
$session,
'POST',
'/' . $pageID . '/feed',
array(
'accessToken' => $pageAccessToken;
'message' => 'Facebook app';
)
))->execute();*/
//foreach ($getPages['data'] as $key) {
//print_r($getPages);
/*echo $key->id;
echo "<br>";
echo $key->name;
echo "<br>";*/
//}
/*$response = $request->execute();
$graphObject = $response->getGraphObject();*/
/*$request = new FacebookRequest(
$_SESSION,
'POST',
'/883093058488924/roles',
array (
'user' => '123456789',
'role' => 'administrators',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
var_dump($graphObject);*/
header("Location: index.php");
//redirect if is administrator
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile', 'publish_actions', 'manage_pages']; // optionnal 'user_managed_groups'
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/login.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
?>
Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
ok.I have try all the way that I find on the stackoverflow about the same question,but unfortunately,the same question has occured all the time,I am crazy now.Please help me!
this is the login.php:
<?php
require_once __DIR__ . '\Facebook\autoload.php';
if(!session_id()) {
session_start();
}
$fb = new Facebook\Facebook([
'app_id' => 'my_app_id',
'app_secret' => 'and_my_app_secret',
'default_graph_version' => 'v2.5',
// 'persistent_data_handler'=>'session',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://my_ip/facebook/login-callback.php', $permissions);
foreach ($_SESSION as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
if(!setcookie($k, $v)) {
echo "there is no cookie";
exit;
} else {
$_COOKIE[$k]=$v;
}
}
}
var_dump($_COOKIE);
echo 'Log in with Facebook! ';
?>
and this is the login-callback.php:
<?php
require_once __DIR__ . '\Facebook\autoload.php';
if(!session_id()) {
session_start();
}
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
$fb = new Facebook\Facebook([
'app_id' => 'my_app_id',
'app_secret' => 'my_app_secret',
'default_graph_version' => 'v2.5',
// 'persistent_data_handler'=>'session',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
var_dump($accessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$_SESSION['fb_access_token'] = (string) $accessToken;
?>
hello correct your permission variable like
FacebookSession::setDefaultApplication( 'app_id','app_secreat' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('redirect url' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
$session = null;
// 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
$accessToken = $session->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
if (isset($longLivedAccessToken)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
}
$request = new FacebookRequest($session, 'GET', '/me',
array(
'fields' => 'id,name,email'
) );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
//print_r($graphObject);die();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email');
//checkuser($fbid,$fbfullname,$femail);
$request1 = new FacebookRequest($session, 'GET', '/me/accounts',
array(
'fields' => 'id,access_token,name'
) );
$pageList= $request1->execute()
->getGraphObject()
->asArray();
use this code and get request
Please Go to the file
src/Facebook/PersistentData/PersistentDataFactory.php
In Your Facebook SDK
find this Code
if ('session' === $handler) {
new FacebookSessionPersistentDataHandler();
}
and Replace With
if ('session' === $handler) {
return new FacebookSessionPersistentDataHandler();
}
I am not able to retrieve the email from the Graph Object. I see on my app that I have permission for it. Here is my current code:
FacebookSession::setDefaultApplication('xxx','xx');
$helper = new FacebookRedirectLoginHelper('xxx');
$session = null;
try {
$session = $helper->getSessionFromRedirect();
Core::session('FacebookAuthSession')->sessionObject = $session;
} catch(FacebookRequestException $ex) {
} catch(\Exception $ex) {
}
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
You can use following code to execute:
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
if($session) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Email: " . $user_profile->getEmail();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
To test results, you can also use explorer: https://developers.facebook.com/tools/explorer
The permissions are just listed as "approved without review" in your App settings, but you still have to authorize a user with them by using the "scope" parameter in the login process: https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
I am trying to integrate facebook for my canvas app. When i run app from facebook with following code
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('xx','xx');
$helper = new FacebookCanvasLoginHelper();
try {
$data = array('oauth_token' => 'token');
$data['algorithm'] = 'HMAC-SHA256';
$data['issued_at'] = time();
$base64data = base64_encode(json_encode($data));
$rawSig = hash_hmac('sha256', $base64data, 'app_Secret', true);
$sig = base64_encode($rawSig);
$signedRequest = $sig.'.'.$base64data;
$_GET['signed_request'] = $signedRequest;
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
echo $ex;
} catch(\Exception $ex) {
echo $ex;
}
The entire page just turns blank white because of $_GET['signed_request'] = $signedRequest;.
What should I do to get login. If i just do $session = $helper->getSession(); instead of Get i get invalid signed paramters oAuth data missing.
Your PHP should be:
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
if($session){
try {
$facebook_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo $facebook_profile->getName;
} catch(FacebookRequestException $e) {
}
}
} catch(FacebookRequestException $ex) {
echo $ex;
} catch(\Exception $ex) {
$facebookLoginHtml = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id={your_app_id}&redirect_uri={your_app_canvas_url}';";
}
And then somewhere in your HTML:
<script>
<?php if(isset($facebookLoginHtml)){ echo $facebookLoginHtml; } ?>
</script>
If you want to ask for extra permission, add the scope parameter in the URL like this:
$facebookLoginHtml = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id={your_app_id}&redirect_uri={your_app_canvas_url}&scope=publish_actions';";
That will redirect the page to the login page, and then come back to your canvas app with the proper permission.
This shouldn't work like this as it's using Javascript with the PHP SDK. It's a bug that is being addressed by Facebook which you can follow here:
https://developers.facebook.com/bugs/722275367815777
I'll edit the answer if that bug ever gets resolved.
Thanks guys!
My approach:
<?php
session_start();
require ({your_php_sdk_path} . 'autoload.php');
use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
FacebookSession::setDefaultApplication({your_app_id},{your_app_secret});
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
}catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if (!is_null($session)) {
// Logged in
try {
//Get user name
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
$user_profile_name = $user_profile->getName();
//Get user picture
$request = new FacebookRequest(
$session,
'GET',
'/me/picture',
array (
'redirect' => false,
'height' => '135',
'width' => '135',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
$user_profile_picture = $graphObject->getProperty('url');
} catch(FacebookRequestException $e) {
// When Facebook returns an error
} catch(Exception $e) {
// When validation fails or other local issues
}
}else{
//First time -> ask for authorization
$helper = new FacebookRedirectLoginHelper({your_canvas_url});
$login_url = $helper->getLoginUrl();
}
?>
And in your html put a javascript:
<script type="text/javascript">
if($login_url != null){
top.location.href = $login_url;
}
</script>
<?php
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('*********','*********' );
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(Exception $ex) {
// When validation fails or other local issues
}
if($session) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
}
else {
// show login url
echo 'Login';
}
?>
Hello I am using the below code section. For back ground, last time was working I was getting Curl Exception 77 due to ssl related issues. Still HTTPS is not enabled at my domain yet. With this little info. I am pasting the code section below. There are some prints that I am using for my debugging. (I am new to PHP, kindly bear with me)
<?php
include_once('./php-sdk/facebook.php');
include_once('./php-sdk/fbhelper.php');
$config = array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
);
try {
$facebook = new Facebook($config);
}
catch (FacebookApiException $e) {
echo 'Excetption is' . $e->__toString();
}
?>
<?php
$user_id = $facebook->getUser();
if ($user_id) {
echo "user exists and is: " .$user_id;
} else {
echo "user DONT exists";
}
// If i comment out this next try catch block for $session, then my page renders
// fine, but when I am using this code block, then my page doesn't render beyond
// this code section. This is very strange. Why not an exception is thrown if there
// are any issues? Can anybody help me understand this?
try {
$session = $facebook->getSession();
if ($session) {
echo "user exists and is: " . $session;
} else {
echo "user DONT exists";
}
} catch (FacebookApiException $e) {
print_r($e);
}
// now when I comment out above $session related part, then page renders fine, but
// no where any prints show me anything. Why the name is not getting reflected?
if ($user_id) {
try {
$user_profile = $facebook->api('/727850431', 'GET');
echo 'Name: ' . $user_profile['name'];
} catch (FacebookApiException $e) {
print_r($e);
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
try {
$url = 'https://graph.facebook.com/oauth/access_token?client_id=FACEBOOK_APP_ID&client_secret=FACEBOOK_SECRET& grant_type=client_credentials';
$app_access_token = json_decode(file_get_contents($url));
$graph_url = "https://graph.facebook.com/me?access_token=" . $app_access_token;
$result = json_decode(file_get_contents($graph_url));
print_r($result);
} catch (FacebookApiException $e) {
print_r($e);
}
?>