Exception occured, code: 200 with message: (#200) Permissions error - php

I have a problem with FB PHP SDK.
Here is my code:
require_once("autoload.php"); // set the right path
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphObject;
use Facebook\FacebookRequestException;
$APP_ID = 'APP_ID';
$APP_SECRET = 'APPSECRET';
$TOKEN = "TOKEN";
$ID = "PAGE_ID"; // your id or facebook page id
FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);
$session = new FacebookSession($TOKEN);
$params = array(
"message" => "Xoşbəxt olmamaq haqsızlıq deyilmi özümüzə qarşı?!"
);
if ($session) {
try {
$response = (new FacebookRequest(
$session, 'POST', '/' . $ID . '/feed', $params
))->execute()->getGraphObject();
echo "Posted with id: " . $response->getProperty('id');
} catch (FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
But when i try to run this code it returns an error:
Exception occured, code: 200 with message: (#200) Permissions error
in some forums i read that may be i need to approve premissons/ but when i submited premissions to FB they answered that if i am using it only for my purpose (as app admin) premisson approval is not requred.
What can be problem?

Debug your Access Token: https://developers.facebook.com/tools/debug/
Make sure it includes the manage_pages and publish_pages permission. And make sure you are using a Page Token. More information about the different Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

Related

Facebook PHP SDK v4 manage_pages permission for non developer account

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>";

Facebook api doesn't return the access token

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');

When I try post a message on my fb page using PHP SDK i see "Graph returned an error: Invalid parameter"

I try to post simple message on my facebook post wall, I try to use PHP SDK v5. The documentation about sdk witch is on Facebook Developers is not so clear for me, and I don't understand what I'm doing wrong.
When i try run this script with posting a message a get an error message " Graph returned an error: Invalid parameter"
This is my code:
<?php
session_start();
require_once __DIR__ . '/vendor/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
//use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\Authentication\AccessToken;
//use Facebook\GraphUser;
//use Facebook\FacebookRequestException;
$fb = new Facebook\Facebook([
'app_id' => '************',
'app_secret' => '****************************',
'default_graph_version' => 'v2.4',
]);
$page_id = '****************';
// HERE IS LONG LIVED ACCESS TOKEN WITCH I GENERATED MANUALY
$access_token = '*********************************';
// HERE IS A CODE WITH GET A POSTS FROM MY WALL AND PRINT IT IN A MY WEBSITE
$object = $fb->get('.$page_id.'/feed', $access_token);
$posts_array = $object->getDecodedBody();
print_r($posts_array['data']);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'User provided message',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.$page_id.'/feed', $linkData, $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;
}
$graphNode = $response->getGraphNode();
echo 'Posted with id: ' . $graphNode['id'];
Thank you for your help !
I found the problem. In the $linkData array the link parameter is a problem. When i deleted it, every think works. Topic to close.

Retrieving email from Facebook GraphObject

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/

SDK 4.0 Facebook, no dialog to request permission publish_actions

I created an app on facebook and via PHP SDK 4.0 I created the login and I need to have write permissions on the feed, but even we have added the permissions, when I do not log apparre the more window box to approve and grant permissions .
this is the code used:
<?php session_start();
require 'Facebook/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphObject;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('XXXXXXXXXX XXXXXXXX','XXXXXXXXXXXXXXXXXX');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'XXXXXXXXXXXXX' );
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();
// print data
echo print_r( $graphObject, 1 );
if($session) {
try {
$response = (new FacebookRequest(
$session, 'POST', '/me/feed', array(
'link' => 'www.example.com',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
} else {
$params = array(
scope => 'publish_actions'
//redirect_uri => $url
);
// show login url
echo 'Login';
}
?>
publish_actions should be approved by facebook for your application if you have already submitted for approval facebook might take upto a week till then you can't publish stories on facebook user's timeline.

Categories