My Facebook login works perfectly in my localhost, but when I uploaded it to a web server, it can't fetch any data from the users.
I can only get their facebook id, but the other infos are null or blank.
I think the facebook login works, because they got redirected to the $redirect_url that I initialized.
$app_id = "******";
$app_secret = "*******";
$redirect_url = "localhost/sample/";
try
{
$facebook = FacebookSession::setDefaultApplication($app_id,$app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url);
$sess = $helper -> getSessionFromRedirect();
}
catch(Exception $e)
{
}
if(!isset($sess))
{
//facebook login button
echo '<div class="fb"> <i class="fa fa-facebook"></i>Sign in with Facebook</div>';
}
else
{
$request = new FacebookRequest($sess,'GET','/me');
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::classname());
$fb_id = $graph ->getId(); //this is the only data that i can get
$fname = $graph ->getFirstName();
$lname = $graph ->getLastName();
$gender = $graph ->getGender();
echo 'name: '.$fname.' '.$lname.' gender: '.$gender; // these are null or ''
$_SESSION['fb_session'] = $sess;
}
I already got my permission approved.
This is an fb account that i created.
As it shown above, I think I'm not breaking any rules since I'm only fetching the info from the agreed permission.
It looks like FB requires that you include the Graph version in your request. Also, why not add some checks in the exceptions to see if it's a Graph issue or FB SDK. Also, is the user authenticating and you're just not getting their data, or are they not authenticating either?
Here is a snip that I've used and is on the FB Graph auth docs:
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$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;
}
This will also let it grab it's redirect_url for you from the app that you have registered with them.
Related
login.php codes
if(!session_id()) {
session_start();
}
require_once __DIR__ . '/vendor/autoload.php';
$facebook_appId = '123';
$facebook_appSecret = '123';
$fb = new Facebook\Facebook([
'app_id' => $facebook_appId,
'app_secret' => $facebook_appSecret,
'default_graph_version' => 'v2.11',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://www.123.com/login-callback.php', $permissions);
echo 'Login via Facebook!';
login-callback.php codes
if(!session_id()) {
session_start();
}
require_once __DIR__ . '/vendor/autoload.php';
$facebook_appId = '123';
$facebook_appSecret = '123';
$fb = new \Facebook\Facebook([
'app_id' => $facebook_appId,
'app_secret' => $facebook_appSecret,
'default_graph_version' => 'v2.11',
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$helper = $fb->getRedirectLoginHelper();
$accessToken = $helper->getAccessToken();
$response = $fb->get('/me?fields=id,name', $accessToken );
// $response = $fb->get('/me', $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;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
When I click on the "login.php" output link, it jumps to the "login-callback.php" and prints the following error message. How do I solve this problem?
Graph returned an error: Unable to load URL: The domain name of this URL does not contain the domain name of the application. In order to be able to load the URL, add all domains and subdomains of the application in the App Domain Name field of the app settings.
However, I have added the corresponding url in the facebook developer platform.
Now OAuth is mandatory in strict mode for FB Login:
You have to set the URI of your callback script in the params of FB Login in your app settings board, AND pass the same callback URL as an argument of getAccessToken() method:
try {
$accessToken = $helper->getAccessToken('http://yourdomain.com/login-callback.php');
}// ...
I am trying to make a login page for v2.8 graph api.
I am following all the graph api examples but still getting an error.
This is the error:
Facebook SDK returned an error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
fbaccess.php
session_start();
$app_id = "xxxxxx";
$app_secret = "xxxxx";
$site_url = "http://xxxxxxxxx/";
require_once __DIR__ . '/src/autoload.php';
// Create our application instance
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v2.8',
]);
index.php
session_start();
include("fbaccess.php");
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_likes']; // optional
$loginUrl = $helper->getLoginUrl('http://shortbucks.com/facebook/callback.php', $permissions);
echo 'Log in with Facebook!';
callback.php
session_start();
include("fbaccess.php");
$helper = $fb->getRedirectLoginHelper();
try {
// Returns a `Facebook\FacebookResponse` object
$accessToken = $helper->getAccessToken();
$response = $fb->get('/me?fields=id,name', $accessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
Can someone help me identify the error?
Thanks
Hi I had the same problem, i have downloaded the last version of SDK from Facebook and voila works perfect.. cheers
I use Facebook PHP SDK and trying to send token-id from one page to another. I use this code - http://www.krizna.com/demo/login-with-facebook-using-php/. I use
$helper = new FacebookRedirectLoginHelper('http://www.krizna.com/fbconfig.php' );
I have tried sending value like this :
$helper = new FacebookRedirectLoginHelper('http://www.krizna.com/fbconfig.php?value='.$value );
but I do not get value in fbconfig.php file when I try:
$value = $_GET['value'];
I have also used session for sending values but it does not work. How can I send value to FacebookRedirectLoginHelper (fbconfig.php)?
fbconfig.php
<?php
session_start();
$value = $_GET['value_new'];
$fb = new \Facebook\Facebook([
'app_id' => $config->facebook->app_id,
'app_secret' => $config->facebook->app_secret
]);
$helper = $fb->getRedirectLoginHelper();
try {
if ($access_token = $helper->getAccessToken()) {
try {
// Returns a `Facebook\FacebookResponse` object with the requested fields
$response = $fb->get('/me?fields=name,id,email,picture', $access_token);
$user = $response->getGraphUser();
$fbid = $user->getId(); // To Get Facebook ID
$fbfullname = $user->getName(); // To Get Facebook full name
$femail = $graphObject->getEmail();// To Get Facebook email ID
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
//Then do whatever you want with that data
$value = $_SESSION['value'];
header("Location: index.php?value_new=$value");
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
error_log('Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
}
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
error_log('Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
index.php
<?php if (isset($_SESSION['FBID'])): ?><!-- After user login -->
<div class="container">
<h1>value <?php $value_new = $_GET['value_new']; echo $value_new; ?></h1>
</div>
<? endif ?>
You should not be trying to pass the facebook Access Token via the query string / $_GET[] superglobal. What you should be using is what facebook recommends, which is the $_SESSION[] superglobal.
Since you are trying to pass the access token from one page to another, lets call the access token on the first page $access_token. To pass it to another page do the following:
page 1:
<?php
session_start(); //the very top of your document
// ... other code ...
$_SESSION['access_token'] = $access_token;
// ... other code ...
?>
page 2:
<?php
session_start(); //the very top of your document
// ... other code ...
$access_token = $_SESSION['access_token'];
// ... other code ...
?>
That should work, let me know if it works for you.
This answer is using the Facebook PHP SDK v5.1.2, and is adapted from the method I have working in my own projects. It also assumes composer autoloading is being used.
Login Page
session_start();
$fb = new \Facebook\Facebook([
'app_id' => $config->facebook->app_id, //Change these to yours
'app_secret' => $config->facebook->app_secret
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
$this->view->facebook_url = $helper->getLoginUrl('http://www.krizna.com/fbconfig.php', $permissions);
fbconfig.php (or whatever you want your redirect page to be)
session_start();
$fb = new \Facebook\Facebook([
'app_id' => $config->facebook->app_id,
'app_secret' => $config->facebook->app_secret
]);
$helper = $fb->getRedirectLoginHelper();
try {
if ($access_token = $helper->getAccessToken()) {
try {
// Returns a `Facebook\FacebookResponse` object with the requested fields
$response = $fb->get('/me?fields=name,id,email,picture', $access_token);
$user = $response->getGraphUser();
$fbid = $user->getId(); // To Get Facebook ID
$fbfullname = $user->getName(); // To Get Facebook full name
$femail = $graphObject->getEmail(); // To Get Facebook email ID
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
//Then do whatever you want with that data
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
error_log('Graph returned an error: ' . $e->getMessage());
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
}
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
error_log('Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
error_log('Facebook SDK returned an error: ' . $e->getMessage());
}
Hopefully that gives you a hand up. I don't doubt that my code has been adapted from previous StackOverflow answers or tutorials.
I have created a facebook app and approved the app to access manage_pages.I am looking for php code to get page access from page to get the page information.
For getting reviews and rating I am using the below code
require 'facebook-php-sdk-master/src/facebook.php';
$config = array();
$config['appId'] = '1489047331XXXXX';
$config['secret'] = '6ac210360aad27ab1044e4201XXXX';
$facebook = new Facebook($config);
print_r($facebook);
try {
// 466400200079875 is Facebook id of Fan page https://www.facebook.com/pontikis.net
$ret = $facebook->api("/page_id/ratings?field=open_graph_story", 'GET');
print_r($ret);
} catch(Exception $e) {
echo $e->getMessage();
}
I am getting the below error
(#210) This call requires a Page access token.
Any help will be highly appreciated.
Create new object like this and set access_token if not exists:
$fb = new Facebook([
'app_id' => FB_APP_ID,
'app_secret' => FB_APP_SECRET,
'default_graph_version' => 'v2.5',
'default_access_token' => isset($_SESSION['facebook_access_token']) ?
$_SESSION['facebook_access_token'] : FB_APP_ID . '|'. FB_APP_SECRET
]);
Change FB_APP_ID and FB_APP_SECRET, only with yours. Now you have access token, after that you can make requests and get data that u need access token for it like this (for the example):
$request = $fb->request('GET', '/'.$page_id.'/');
// Send the request to Graph
try {
$response = $fb->getClient()->sendRequest($request);
} 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;
}
$graphNode = $response->getGraphPage();
var_dump($graphNode->all());
Where $page_id is id of some page, where you can find it with its FB page URL .
My requirement: Publish a link in a facebook fan page automatically when a form is submmited in my web application.
So I have the following code (copy/paste from the facebook suggestion )
$appId = "...";
$appSecret = "...";
$fb = new Facebook\Facebook([
'app_id' => $appId,
'app_secret' => $appSecret,
]);
$helper = $fb->getRedirectLoginHelper();
try {
$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 ($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());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here
// $tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (!$accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
But the output is Bad request. I tried with another appId but keeps the error.
According to the Facebook docs:
The FacebookRedirectLoginHelper makes use of sessions to store a CSRF
value. You need to make sure you have sessions enabled before invoking
the getLoginUrl() method. This is usually done automatically in most
web frameworks, but if you're not using a web framework you can add
session_start(); to the top of your login.php & login-callback.php
scripts. You can overwrite the default session handling - see
extensibility points below.
Make sure there is a valid session, or use session_start() at the top of your scripts.
That code is for login with facebook.
for post to a fanpage as an admin try something like:
$appid = 'XXX'; //your app id
$appsecret = 'XXX'; //your app secret
$pageId = 'XXX'; //your page id
use Facebook\FacebookRequest;
require 'your_path/Facebook/autoload.php';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => 'www.test.com' /example
);
$postId = $facebook->api("/$pageId/feed", "post", $args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
I had a problem with access token to. I am not sure if it is the same problem.
My facebook login didn't work cause $accessToken = $helperget->AccessToken();
return on error (code 401).
To correct my code I needed to add at my AccessToken(), my callback url. (The same into my URI configuration in facebook developper website).
$accessToken = $helper->getAccessToken('www.domain.com/callback');