We are trying to create an app to pull in facebook reviews which requires the manage_page permission. This is not an app which we would like to submit for review as we are only using this for our clients.
We are currently able to get the access token for all pages when logging in as the administration developers.facebook.com account using the following code below which gives us the data array with all access_tokens as expected.
However the problem we have is when we try to login with the clients facebook account the array is empty.
So we tried to add them as an admin for the app which is not ideal as they are not developers so would not be happy with this approach.
I believe this is not working due to manage_page permission.
Does anyone know a way around this without having to submit the app for review?
$app_id = '1234567890';
$app_secret = 'ABCDEFGHIJKM';
$facebook = FacebookSession::setDefaultApplication($app_id, $app_secret);
$session = FacebookSession::newAppSession();
$callback_url = 'http://'. $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$helper = new FacebookRedirectLoginHelper($callback_url, $app_id, $app_secret);
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookSDKException $e) {
echo 'FacebookSDKException Error: ' . $e->getMessage();
$session = null;
} catch(\Exception $ex) {
echo 'Exception Error: ' . $e->getMessage();
}
print "<pre>"; print_r($session); print "</pre>";
if ($session) {
// User logged in, get the AccessToken entity.
$accessToken = $session->getAccessToken();
// Exchange the short-lived token for a long-lived token.
$longLivedAccessToken = $accessToken->extend();
// Make calls to Graph with the long-lived token.
} else {
echo 'Login with Facebook';
}
FacebookSession::enableAppSecretProof(false);
try {
$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=name,access_token,perms');
$pageList = $request->execute()
->getGraphObject()
->asArray();
} catch(FacebookRequestException $e) {
echo 'FacebookRequestException Error: ' . $e->getMessage();
} catch(\Exception $ex) {
echo 'Exception Error: ' . $e->getMessage();
}
print "<pre>"; print_r($pageList); print "</pre>";
Related
I have a problem with the Facebook API, I try to test fairly regularly ids facebook pages liked by the user who uses my API. But soon enough I got this message: (# 4) Application request limit reached. (in php)
Here's how I connect to the API and get pages:
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXX',
'app_secret' => 'XXXXXXXXXX',
'default_graph_version' => 'v3.1',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = []; // optional
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 {
// getting short-lived access token
$_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;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,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();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// printing $profile array on the screen which holds the basic info about user
print_r($profile);
$res = $fb->get('/me/likes?limit=1000', $_SESSION['token']);
$res = $res->getGraphEdge()->asArray();
foreach($res as $page) {
$pages[] = $page['id'];
}
} else {
// replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here
$loginUrl = $helper->getLoginUrl('http://localhost/index.php', $permissions);
echo 'Log in with Facebook!';
}
I'm looking for a way to keep the page consultation but every time after a while, 4/5 times I have the error message.
If not before it works. Do you have an idea to keep the $ fb object without necessarily making the call? In $ _SESSION it's the same thing.
Thanks
I'm using the code below on my website to try and post a message on a Facebook page that I manage. I'm using the Facebook PHP SDK v5. Whenever I run the code I get directed to Facebook with an error window that says,
"URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs."
However, if I go to the Graph API Explorer and request a User Access Token, then hard code the access token into the script it works just fine. I added Facebook Login to the products tab on my app setting, since that's the only place you can add in the "Valid OAuth redirect URIs". I'm pretty sure the problem is coming from the "Valid OAuth redirect URIs" field in the setting area. I'm not sure what to put in that field or if that is even the problem at all. Currently, I've tried putting the following in the "Valid OAuth redirect URIs" field with no luck;
just my domain i.e. www.my-domain.com
the full path the the calling script i.e. www.my-domain.com/calling-script.php
the full path to a blank page on my server i.e. www.my-domain.com/blank.html
None are working. This is my first go at trying to use the Facebook PHP SDK so I'm sure I'm doing it all wrong... Wondering if anyone is able to give me some guidance on this?
UPDATE:
See answer posted below with fix. My original post was not very clear regarding my intentions. My goal was to successfully post a message to a Facebook Page as the Page, not as an individual user. Hope this helps someone down the road.
Here are my app settings:
Here is the PHP script I am using:
session_start();
$path = "path-to-Facebook-autoloader-on-my-server";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-from-app-settings',
'app_secret' => 'app-secret-number-from-app-settings',
'default_graph_version' => 'v2.7',
]);
/////////////////////////////////////////////////////////////////////////
// If I uncomment the below line the script works fine, but the token expires often
// and I do not want to have to keep updating it
// $_SESSION['facebook_access_token'] = "access-token-obtained-from-Graph-API-Explorer";
/////////////////////////////////////////////////////////////////////////
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // optional
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/austintestingapp/', $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;
}
try{
// message must come from the user-end
$data = ['message' => 'test message...'];
$request = $fb->post('/me/feed', $data);
$response = $request->getGraphNode();
}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;
}
echo $response['id'];
}else{
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
i checked your script. all looks fine except one thing. can u try after changing
$helper = $fb->getCanvasHelper();
to
$helper = $fb->getRedirectLoginHelper();
and see what error it throws if any?
also u can refer to the shared gist. do let us know your error.
https://gist.github.com/gunnrryy/c2c828fc2a77124cc1bed57af5e216df
So I ended up figuring it out. I played around with the script I originally posted and finally got it to work...sort of. No matter how I ran the script messages were always being sent to the page I manage as a notification. They would not show up on the wall. The end goal I was looking for was to post on to a page that I manage as the page, not as myself. Just in case anyone else comes across this the code below works perfect. Also, it does not require you to submit privileges for approval with Facebook.
The answer to my original question in regards to the "Valid OAuth redirect URIs" field. I ended up putting the path to the calling script in that field and it worked fine.
session_start();
$path = "server-path-to-Facebook-autoloader.php";
$permissions = ['manage_pages', 'publish_pages'];
$callback = "full-path-to-the-calling-script(this-script).php";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-number-here',
'app_secret' => 'app-secret-here',
'default_graph_version' => 'v2.7',
]);
$helper = $fb->getRedirectLoginHelper();
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
$res['myresponse'] = 'Error: Graph returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_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;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$res['myresponse'] = 'Error: Graph returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach ($pages as $key) {
if ($key['name'] == 'name-of-page-to-post-to') {
$post = $fb->post('/' . $key['id'] . '/feed', array('message' => 'this is an automated test message from Affordable HomeCare...'), $key['access_token']);
$post = $post->getGraphNode()->asArray();
if($post['id'] <> ''){
$res['myresponse'] = "Successfully Posted to Facebook";
}else{
$res['myresponse'] = "Error: Unable to verify post ID";
}
echo $res['myresponse'];
}
}
} else {
$loginUrl = $helper->getLoginUrl($callback, $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
Note: Before I start, I checked all the other questions on this site which pertain to the same exception and none of the answers worked for me.
I've been having trouble with the facebook sdk and facebook login for a few days now. My website had to change domain (from benotes.com to notepit.com). Since I've changed this, I can no longer use facebook login and get the error "This authorization code has been used".
I changed everything in my facebook app to the new domain, and even tried creating a new facebook app from scratch for the new domain. However, I am still getting the error. Here is my code:
/facebook-login.php
<?php
$fb = new Facebook\Facebook([
'app_id' => '{APP ID}',
'app_secret' => '{APP SECRET}',
'default_graph_version' => 'v2.1',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$fbLink = $helper->getLoginUrl('http://{domain}/facebook-callback.php', $permissions);
?>
This gives me a URL ($fbLink) which I put in an a's href. When the user clicks the link, he/she is redirected to facebook login and then redirected to this page:
/facebook-callback.php
<?php
session_start();
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '{APP ID}',
'app_secret' => '{APP SECRET}',
'default_graph_version' => 'v2.1',
]);
$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({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>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name', $_SESSION['fb_access_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();
echo 'Name: ' . $user['name'];
?>
All that this page returns is "Graph returned an error: This authorization code has been used.", meaning it's from the very first "try" if that helps.
I would also post screenshots of the facebook app but as I said it was working before the domain change and now it's not anymore and I have a new facebook app.
Whoever finds me an answer I will respect forever.
I just resolved the same issue. Turned out I had to match the timezone in php.ini (date.timezone) and restart httpd. The error logs is a very helpful source of information :)
Worked like a charm after I did that. No more errors.
How can i get the group id from facebook API
<?php
session_start();
require_once __DIR__ . '/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.4',
]);
$helper = $fb->getCanvasHelper();
$permissions = ['email']; // optionnal
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/APP_NAMESPACE/', $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=name,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/APP_NAMESPACE/'</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
print_r($profile);
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/APP_NAMESPACE/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
I had codes wherein i am getting
Array ( [name] => xxxx [first_name] => xxxx [last_name] => xxxx [email] => xxxx [id] => xxxxx)
Now I want group ids how can it possible please assist
How to get a list of all the groups you manage is explained very well in the docs, including example code: https://developers.facebook.com/docs/graph-api/reference/user/groups/
You need to authorize with the user_managed_groups permisssion and call the /me/groups endpoint. Do not use the User ID for that endpoint, just use /me - it points to the current User anyway:
$groups_request = $fb->get('/me/groups');
$groups = $groups_request->getGraphNode()->asArray();
Be aware that you can only get groups you manage, you can NOT get access to groups you are just a member of. The user_groups permission to get ALL groups has been removed: https://developers.facebook.com/docs/apps/changelog#v2_4 (search for "90-day deprecations")
To access the groups of a user, you need to use the User Groups endpoint
To read the Facebook groups of a user you need to do yet another API call with:
/{user-id}/groups
Since you've retrieved the ID in your "/me" call, you're almost there.
You can change your code slightly for this:
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$profile = $profile_request->getGraphNode()->asArray();
$groups_request = $fb->get("{$profile['id']}/groups");
$groups = $groups_request->getGraphNode()->asArray();
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');