Error while posting on Facebook using Facebook Graph v5 sdk - facebook-graph-api

I'm using Facebook Graph v5 sdk for login and posting on wall but gets some errors. I've successful login and gets users details like age, birthday etc. successfully but while on posting on facebook using this code
$fb->post('/me/feed', $attachment, $accessToken);
gets some permissions errors as below.
Error:
Fatal error: Uncaught Facebook\Exceptions\FacebookAuthorizationException: (#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission
index.php
<?php
require_once "config.php";
$redirectURL = "http://localhost/fbLogin/fb-callback.php";
$permissions = ['email, user_birthday,user_posts,manage_pages,publish_pages'];
$loginURL = $helper->getLoginUrl($redirectURL, $permissions);
echo $loginURL;
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
window.location = "<?php echo $loginURL; ?>";
}
</script>
</body>
</html>
fb-callback.php
<?php
require_once "config.php";
try {
$accessToken = $helper->getAccessToken();
} catch(\fbLogin\Exceptions\FacebookResponseException $e) {
echo $e->getMessage();
exit();
} catch(\fbLogin\Exceptions\FacebookResponseException $d) {
echo $d->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('371331840061100'); // Replace {app-id} with your 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: " . $e->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$respose = $fb->get("/me?fields=id,name,email,first_name,last_name,address,hometown,gender,birthday,posts", $accessToken);
// Get the base class GraphNode from the response
$graphNode = $respose->getGraphNode();
// Get the response typed as a GraphUser
$user = $respose->getGraphUser();
echo $user->getName();
echo $user->getEmail();
echo $user->getBirthday()->format('m/d/y');
echo $graphNode->getField('country');
echo $user->getHomeTown();
echo $user->getGender();
echo $_SESSION['fb_access_token'];
header('Location: http://localhost/fblogin/home.php');
?>
config.php
<?php
session_start();
require_once "Facebook/autoload.php";
$fb = new \Facebook\Facebook([
'app_id' => '371331840061100',
'app_secret' =>'fc535825bfe084a63c33a6d36648ddff',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
?>
home.php
<?php
require_once "config.php";
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>wlecom</h1>
<?php
$message = "test message";
$attachment = array('message' => $message);
try{
$accessToken = $_SESSION['fb_access_token'];
// Post to Facebook
$fb->post('/me/feed', $attachment, $accessToken);
// Display post submission status
echo 'The post was published successfully to the Facebook timeline.';
}catch(FacebookResponseException $e){
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}catch(FacebookSDKException $e){
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(\fbLogin\Exceptions\FacebookResponseException $e) {
echo $e->getMessage();
exit();
} catch(\fbLogin\Exceptions\FacebookResponseException $d) {
echo $d->getMessage();
exit();
}
?>
</body>
</html>

It seems that you are trying to post on a user wall with a token that does not include the publish_actions permission.
You should read the changelog about publish_actions first though: https://developers.facebook.com/docs/graph-api/changelog/breaking-changes

Related

"The domain of this URL isn't included in the app's domains" when it is

I'm trying to post to a Facebook wall from a PHP script. I've created a FB app, installed the Graph PHP API, and implemented some test scripts as follows:
fbinit.php:
<?php
session_start();
require_once('src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'REDACTED',
'app_secret' => 'REDACTED',
'default_graph_version' => 'v2.9',
]);
?>
fbpost.php:
<?php
include('fbinit.php');
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages','publish_pages']; //'publish_actions'
$loginUrl = $helper->getLoginUrl('https://www.REDACTED.net/fb-callback.php', $permissions);
echo 'Log in with Facebook!';
?>
fb-callback.php:
<?php
include('fbinit.php');
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
try {
$accessToken = $helper->getAccessToken();
} 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)) {
echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.';
exit;
}
try {
$response = $fb->get('me/accounts', $accessToken->getValue());
$response = $response->getDecodedBody();
} 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;
}
echo "<pre>";
print_r($response);
echo "</pre>";
?>
The first time I opened fbpost.php, I was asked to log in to Facebook as expected, and it asked for permission to post on my behalf on the page, which is fine. But then I am redirected to the call back page and presented with the following error:
Graph returned an error: Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.
I have added every combination of the app URL's and callback URL's I can think of, but nothing works. See below for screenshots of the app settings. The App ID and secret are definitely correct.
The value of the redirect_uri parameter needs to be the exact same in your login dialog call, and the subsequent API call that tries to exchange the code for a token.
When you have generation of the login URL and handling of the response spread over different scripts (i.e., called via different URLs), that can easily lead to problems like this. The SDK tries to figure out the value based on the current script URL, if left to its own devices.
In such a case, explicitly specify the callback URL in your getAccessToken method call as well.

Get Facebook Post/Photo Url Using Facebook API

I created an Facebook app that post my webpage photo on my facebook page by clicking on a button.
Now I also want to show my facebook post url on my webpage.
Means when I'll click on the button on my website, it will publish a photo on facebook and then I want to show that published photo url on my page from facebook.
I'm using this code to publish on facebook:-
<?php
require_once("/path-to/facebook_php_sdk/facebook.php"); // set the right path
$config = array();
$config['appId'] = 'your-app-id';
$config['secret'] = 'your-secret-key;
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$params = array(
"access_token" => "your_access_token",
"url" => "http://photo-url",
);
try {
$ret = $fb->api('/fb-page-id/photos', 'POST', $params);
echo 'Successfully posted photo to Facebook Fan Page';
} catch(Exception $e) {
echo $e->getMessage();
}
?>
I have found the answer myself.
You can use this code to get Facebook post/photo url using fb api
try
{
$ret = $fb->api('/fb-page-id/photos', 'POST', $params);
echo 'Successfully posted photo to Facebook Fan Page';
$fbdurl = $ret[post_id];
$url= "https://facebook.com/".$fbdurl;
}
catch(Exception $e) {
echo $e->getMessage();
}

facebook PHP SDK facebookrequest class using facebook\facebookapp

I'm using facebook PHP SDK and GRAPH API to get all the posts of a page (which is I am an admin and It is a public page). I'm stuck by this instruction
$fbApp = new Facebook\FacebookApp('{app-id}', '{app-secret}');
$request = new Facebook\FacebookRequest($fbApp, '{access-token}', 'GET', '/me');
$fb = new Facebook\Facebook(/* . . . */);
$request = $fb->request('GET', '/me');
try {
$response = $fbApp->getClient()->sendRequest($request);
} 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 'User name: ' . $graphNode['name'];
instructions from here https://developers.facebook.com/docs/php/FacebookRequest/5.0.0#overview
it returns an error Call to undefined method Facebook\FacebookApp::getClient()
notice I'm usicng FacebookApp for getclient function so my question is how do I use facebookapp instead of facebook? to send a request to GRAPH and get a response.
also,
$request = new FacebookRequest(
$session,
'GET',
'/myfbpage/posts'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
was recommended to me to be the code for PHP SDK got this from: https://developers.facebook.com/tools/explorer/
I also don't see a method execute(); in Facebookrequest is facebook documentation wrong or am I using the wrong PHP SDK?

Cake PHP drop down list

I would like to know how to add a drop down list for "access control" with value "staff" and "Admin".
This is my add function in employee controller
public function add() {
if ($this->request->is('post')) {
$this->Employee->create();
if ($this->Employee->save($this->request->data)) {
$this->Session->setFlash(__('The employee has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The employee could not be saved. Please, try again.'));
}
}
}
This is the add view code:
<div class="employees form">
<?php echo $this->Form->create('Employee'); ?>
<fieldset>
<legend><?php echo __('Add Employee Details'); ?></legend>
<?php
echo $this->Form->input('employee_name');
echo $this->Form->input('date_hired', array('dateFormat' => 'DMY','minYear'=>date('Y')-100, 'maxYear'=>date('Y')+100));
echo $this->Form->input('employee_phone_number');
echo $this->Form->input('employee_email');
echo $this->Form->input('employee_address');
echo $this->Form->input('employee_dob', array('dateFormat' => 'DMY','minYear'=>date('Y')-100, 'maxYear'=>date('Y')+100));
echo $this->Form->input('access_level');
echo $this->Form->input('employee_username');
echo $this->Form->input('employee_pw');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
To add a drop down list for access control with value staff and Admin.
add this in your employee controller
$customers = $this->Employee->modelname->find('list');
$this->set(compact('customers'));
and in view.ctp
echo $this->Form->input('access_level');
If you are getting access_level data from database then-
echo $this->Form->input('access_level', array('options' => array('admin' => 'Admin', 'staff' => 'Ataff')));

How do I get Permission to post to Facebook Page Wall

After reading the developers.facebook.com for the past few hours I just can't seem to figure out how to get my Facebook Page to allow permission for me to post to its wall from a Django Website?
you must give related permissions to your app(publish_stream,manage pages)
then you can post to page as page
posting to page as page if you have page's access_token can be like this:
include_once ('src/facebook.php');/// include sdk
////// config The sdk
# $facebook = new Facebook(array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXX',
));
try{
$post=$facebook->api('PAGE_ID/feed/','POST',array(
'message' => '$message',
'link'=>'http://apps.facebook.com/xxxxxxx/link.php?link=',
'picture'=> 'XXXXXXXXXX',
'name'=>'XXXXXX',
'description'=>'yes',
'access_token'=>'PAGE ACCESS TOKEN'
));
}
catch(FacebookApiException $e) {
echo $e->getType();
echo '<br />';
echo $e->getMessage();
}
& if you dont have access token (you need above permissions again) i think this can help you
include_once ('src/facebook.php');/// include sdk
////// config The sdk
# $facebook = new Facebook(array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXX',
));
$facebook->destroySession();
try{
$post=$facebook->api('PAGE ID/feed/','POST',array(
'message' => '$message',
'link'=>'http://apps.facebook.com/xxxxxxx/link.php?link=',
'picture'=> 'XXXXXXXXXX',
'name'=>'XXXXXX',
'description'=>'yes',
));
}
catch(FacebookApiException $e) {
echo $e->getType();
echo '<br />';
echo $e->getMessage();
}
to learn how to get page's access_token check this link up:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%2Faccounts