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 .
Related
Last week i installed facebook SDK via composer on CODEIGNITER 3 ,it work fine and return name email and token until this day , When I try login the page loads for 1 minute and then an empty page apears with the error:
Empty Error
Facebook SDK returned an error:
and Return This URI
https://www.mywebsite.com/en/fbcallback?code=AQCCasdfSAD35L-3iABFbT5zntYQ4jJHVcko9ekG-6k-jn5aERodXoasdf7jHWEgSxxqze_K-nyAYSmcASDFaskde6wPasdfD8WHBEFUEO5gNpgLU0RJqnvVGCdYKNfT2Qm5U1pcWCvVE_YkJ6sQyUL0RrcONrqMbb7bpPv0KDUQjaO_XMAwvKEo2Jasdf31PCjxoHBGoogupX8VF5Gx6WaT4b7ZlsYkPhbQPTCdJaWrzwvfJ1So27Wsdt1Ub9WPUO07io3vxmX-P-rmzsxnk3qDSKCPJX9ks0eBtNwXA-83&state=8cbe21da648d832fcd2b34aceb8dfe62#=
im using 2 action in my controller for login :
function fblogin(){
$fb = new Facebook\Facebook([
'app_id' => 'my app id ',
'app_secret' => 'my app secret',
'default_graph_version' => 'v3.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
// For more permissions like user location etc you need to send your application for review
$loginUrl = $helper->getLoginUrl('https://www.example.com/en/fbcallback', $permissions);
header("location: ".$loginUrl);
}
this where it should return token info :
function fbcallback(){
$fb = new Facebook\Facebook([
'app_id' => 'myid',
'app_secret' => 'myscretapp',
'default_graph_version' => 'v3.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;
}
try {
// Get the Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me?fields=id,name,email,first_name,last_name',$accessToken);
// print_r($response);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'ERROR: Graph ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'ERROR: validation fails ' . $e->getMessage();
exit;
}
// User Information Retrival begins................................................
$me = $response->getGraphUser();
echo "First Name: ".$me->getProperty('first_name')."<br>";
echo "Last Name: ".$me->getProperty('last_name')."<br>";
echo "Email: ".$me->getProperty('email')."<br>";
echo "Facebook ID: <a href='https://www.facebook.com/".$me->getProperty('id')."' target='_blank'>".$me->getProperty('id')."</a>"."<br>";
$profileid = $me->getProperty('id');
echo "</br><img src='//graph.facebook.com/$profileid/picture?type=large'> ";
echo "</br></br>Access Token : </br>".$accessToken;
}
the same question was asked 2 years ago but no answers :
link
My problem was on server side :
This feature allows you to specify certain IPs or IP ranges to which you will be able to open outgoing connections.
Just go to your server and check if it block outgoing connections....
I added it to white list and work fine ! ... hope that can save your time .
Hi Sir Am Using Fb Php Sdk 4 & Graph 2.8 I Know Its Little Outdated But I Want Continue On It. Only Authorized Problem Fixed Can Make My Project Done
I Used Configured & Login Data Page Below But Its Return Me
Graph returned an error: This authorization code has been used.
below my code
config.php
<?php
session_start();
$_IM=array(
"sitename" => "AppsFunny",
"siteurl" => "http://appsfunny.com",
"sitelogo" => "AppsFunny.Com",
"fb_page" => "/appsfunny",
"aurl" => "appsfunny.com"
);
include "ifunc.php";
include "db.php";
include "Unicode2Bijoy.class.php";
$app_id='423436984657946';
require_once __DIR__ . '/vendor/autoload.php';
use Facebook\FacebookRequest;
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => 'c82ff16cec2f6a055302c5c632c0129b',
'default_graph_version' => 'v2.8',
]);
if (isset($_SESSION['access_token'])) {
$token = $session->getToken();
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me', $token);
} 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();
$_SESSION['FBID'] = $user['id'];
$_SESSION['FULLNAME'] = $user['name'];
$_SESSION['propic']="https://graph.facebook.com/".$_SESSION['FBID']."/picture?height=200&width=200";
}
?>
and login.php
<?php
require_once __DIR__ . '/config.php';
$p=$_GET["p"];
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
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)) {
$access_token = $session->getToken();
$_SESSION['access_token'] = (string) $accessToken;
header("location:".$p);
}
Cause
This problem is there because you are trying to request access_token on every page load or reload. When you request a token, a unique code is get passed along with the URL. When you request again and again with the same token, this error occurs.
Solution
So after getting access_token, keep it in db. And request for new token only and only if either you don't have access_token or its not valid anymore.
when I publish a post to my page, it's working fine, but when I post to page through set page ID instead of "me",
the response as the following:
Graph returned an error: (#200) Permissions error
the source code as the following:
require_once 'src/Facebook/autoload.php';
//*
$config = array();
$config['appId'] = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
$config['app_id'] = $config['appId'];
$config['secret'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$config['app_secret'] = $config['secret'];
define('APP_ID', $config['appId']);
define('APP_SECRET', $config['secret']);
//$config['fileUpload'] = false; // optional
$config['default_graph_version'] = 'v2.5';
$config['page_id'] = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$config['facebook']['permissions'] = array(
'email',
'user_location',
'user_birthday',
'publish_actions',
'publish_pages',
'manage_pages',
'public_profile',
);
$fb = new Facebook\Facebook($config);
if(isset($_SESSION['fb_access_token'])) {
$accessToken = $_SESSION['fb_access_token'];
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
if(isset($accessToken)) {
$oAuth2Client = $fb->getOAuth2Client();
// longlived access token
if (!$accessToken->isLongLived()) {
$accessToken = $oAuth2Client->getLongLivedAccessToken($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;
}
}
if(isset($accessToken)) {
// Logged in!
$_SESSION['fb_access_token'] = (string) $accessToken;
try {
$response = $fb->get('/'.$config['page_id'].'/feed', $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;
}
} else {
$helper = $fb->getRedirectLoginHelper();
$redirect_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$loginUrl = $helper->getLoginUrl($redirect_url, [ 'manage_pages', 'publish_pages', 'publish_actions' ]);
echo 'Log in with Facebook!';
}
on other action in same page
$page_access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// instance
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.4',
]);
$linkData = [
'link' => encodeurl(array('page'=>'page','lang'=>'ar','id'=>$_id,'beg'=>0,'unuse'=>$xtitlex)),
'message' => $xtitlex,
'source' => $publish,//$fb->fileToUpload($publish),
'caption' => DOMAIN_,
"picture" => $publish,
"name" => $xtitlex,
"description" => $xdescriptionx
];
try {
//
$response = $fb->post('/'.$config['page_id'].'/feed', $linkData, $page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//print_r($linkData);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
?>
Most likely, you are not using a Page Token with the correct permissions. Make sure you are using a Page Token instead of a User Token and make sure it includes publish_pages. You can test your Token in the debugger: https://developers.facebook.com/tools/debug/
Make sure the Page ID shows up, and the publish_pages permission.
First check if the Access Token you used is generated as "Page Access Token" not "User Token". It is a bit tricky and took me a moment.
go to "https://developers.facebook.com/tools/explorer/"
drop down "User Token" menu
pick "Page Access Token"
blue button "Generate Access Token"
copy and use new token
Every time you add or remove Permissions, token changes!
Screenshot
My app types was business and I just added all the permissions from the given list and after I added all permissions, Facebook asked me to review permissions, I simply kept clicking on OK and everything worked, the error went
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');
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.