Facebook Graph API class not found - facebook-graph-api

I'm using the facebook graph api to get event information from a page.
I installed the Facebook SDK with composer but when I try to use a class in my controller it gives an error : Class 'Facebook\FacebookSession' not found.
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
class HomeController extends BaseController {
public function index()
{
FacebookSession::setDefaultApplication('APP_ID', 'APP_SECRET');
$session = FacebookSession::newAppSession();
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/1531904510362357/'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
dd($graphObject);
}

Make sure you are using the Composer autoloader correctly.
You can see the instructions here https://getcomposer.org/doc/00-intro.md
Then make sure you are reporting on all errors. I would wrap my query in a try/catch block so you can catch any facebook exception as follows:
try {
$query = (new FacebookRequest(
$this->facebook, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className())
return $query;
} catch (FacebookRequestException $e) {
// The Graph API returned an error
return $e;
} catch (\Exception $e) {
// Some other error occurred
return $e;
}
Make sure to include the request exception class and graph user class too as follows:
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

Related

How can I debug the request to detect why my HttpPost never fires?

Having the following HttpPost action
[AllowAnonymous]
[Route("api/Test")]
[ApiController]
public class TestController : ControllerBase
{
[Route("Something")]
[HttpPost]
//[IgnoreAntiforgeryToken]
public async Task<IActionResult> Something()
{
return Ok(new
{
Result = true
});
}
}
If I enable the [IgnoreAntiforgeryToken] tag, it works fine.
Then It seems that my post (from Postman) should sent the CSRF token, in that case:
I configure the __RequestVerificationToken (as a Header or as a Body with x-www-form-urlencoded)
Making sure that the token get updated
But I still get a 400
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "00-4b7d669686a083fbba09be86b6841e42-847918b0b6ca656b-00"
}
I tried to debug the request in order to discover what is happening?
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
var initialBody = context.Request.Body;
using (var bodyReader = new System.IO.StreamReader(context.Request.Body))
{
string body = await bodyReader.ReadToEndAsync();
Console.WriteLine(body);
context.Request.Body = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(body));
await next.Invoke();
context.Request.Body = initialBody;
}
//await next.Invoke();
});
}
But I haven't found anything special.
How can I find out what is generating this 400 Bad Request?
You may misunderstand what is the process of testing endpoints protected with an XSRF token in Postman.
Pre-request script to set the value of the xsrf-token environment variable. And from the script, you need be sure the {url} you called is a view which contains input with name="__RequestVerificationToken".
Then you send post request to the api/test.
Here is my working code:
1.Index.cshtml:
<form method="post">
//if it does not generate the token by default
//you can manually add:
//#Html.AntiForgeryToken()
</form>
2.Set the environment:
VARIABLE
INITIALVALUE
member-url
https://localhost:portNumber
xsrf-token
3.Be sure apply the enviroment:
4.Pre-request script:
5.API:
[Route("Something")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Something()
{
return Ok(new
{
Result = true
});
}
After you get 200 response, you can see the token value in your created environment.

Facebook Graph API SDK v5 - Publishing a picture to a page's Album

I'm trying to publish a picture to an album belonging to a Facebook page, using the Facebook PHP SDK v5.
I've already checked the (many) similar questions, however they are all related to prior versions of the SDK, when publish_actions was still allowed.
My Setup:
My app is properly configured and I was able to retrieve my access token
I was able to run a few test API queries with no issues
I'm the admin of this page and my access token has the following permissions ['manage_pages','publish_pages','user_photos']
The SDK was properly initialized with 'fileUpload' => true as a parameter
Code publishing the picture to the album
It is based on the example provided in the SDK documentation.
<?php
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '123456', 'app_secret' => '123456', 'default_graph_version' => 'v3.3', 'fileUpload' => true]);
$picture = 'https://www.example.com/pic.jpg';
$album_id = '123456';
$access_token = 'mytoken';
try {
$response = $fb->post('/'.$album_id.'/photos', array ('url' => $picture), $access_token);
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$graphNode = $response->getGraphNode();
Here's the error I'm getting
Graph returned an error: (#200) This endpoint is deprecated since the
required permission publish_actions is deprecated
Indeed, changes introduced in April 2018 removed the ability to use publish_actions however it seems the documentation has not been updated accordingly.
What is the new way to publish a picture to a page's album?
Your help is much appreciated!
After several hours of researching alternate solutions, I was able to find a workaround.
Apparently I was using an User Access Token instead of the Page Access Token.
Solution
1 - First, verify if your token is a User/Page Access token
2 - If it is an User Token, you need to request the Page Access Token instead:
$user_access_token = 123456;
$page_id = 123456; // Can be retrieved via right click on your page logo + Copy link address
$response = $fb->get('/'.$page_id.'?fields=access_token', $user_access_token);
$page_access_token = json_decode($response->getBody())->access_token;
echo $page_access_token;
3 - Finally, post the picture on the Page using the Page Access Token
Full code
<?php
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '123456', 'app_secret' => '123456', 'default_graph_version' => 'v3.3', 'fileUpload' => true]);
$picture = 'https://www.example.com/pic.jpg';
$album_id = '123456';
$user_access_token = 'mytoken';
$page_id = 123456;
try {
$response = $fb->get('/'.$page_id.'?fields=access_token', $user_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$page_access_token = json_decode($response->getBody())->access_token;
try {
$response = $fb->post('/'.$album_id.'/photos', array ('url' => $picture), $page_access_token);
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$graphNode = $response->getGraphNode();
I hope this helps!

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?

Facebook PHP / JS Sdk This authorization code has been used error

I am using Facebook php an js sdk.
I am login to facebook with js sdk. Login works perfectly.
and I have php part.
private $helper, $api_id, $app_secret, $session;
....
FacebookSession::setDefaultApplication($this->api_id, $this->app_secret);
$this->helper = new FacebookJavaScriptLoginHelper();
try {
$this->session = $this->helper->getSession();
} catch (FacebookRequestException $ex) {
log_message('error', 'Facebook e1 :' . $ex->getCode());
log_message('error', 'Facebook e1 :' . $ex->getMessage());
} catch (\Exception $ex) {
log_message('error', 'Facebook e2 :' . $ex->getCode());
log_message('error', 'Facebook e2 :' . $ex->getMessage());
}
if ($this->session) {
$request = (new FacebookRequest($this->session, 'GET', '/me'))->execute();
$user = $request->getGraphObject()->asArray();
return $user;
} else {
return false;
}
when page loads normally, I get user data without a problem.
But for example, if I press several times f5, to refresh page, I get and error that "This authorization code has been used." or "This authorization code has expired." and user data is empty.
Idea is to login with js, and to use php part to validate is user logged in into facebook or not.
I am using latest facebook php sdk : https://github.com/facebook/facebook-php-sdk-v4
Thank you.
There are several ways how to fix this.
1) You have to update the access token in the cookie every call, FB does not do this automatically. So, be sure you call the FB.init with status: true param.
FB.init({
appId : window.fbId,
cookie : true,
status : true,
version : 'v2.3'
});
Next, every page refresh you have to call FB.getLoginStatus(); no matter if you are connected to Facebook already.
This does not work if your application needs to do some ajax calls - simply because the access token is not updated when you do ajax (unless you call FB.getLoginStatus(); before every ajax call - and that's overkill).
2) Better may be to store the access token in session once user connect via FB JS SDK. The PHP code might look like this:
try {
$fbToken = isset($_SESSION['fbToken']) ? $_SESSION['fbToken'] : NULL;
if ($fbToken !== NULL) {
$session = new \Facebook\FacebookSession($fbToken);
} else {
$helper = new FacebookJavaScriptLoginHelper();
$session = $helper->getSession();
}
} catch(\Facebook\FacebookRequestException $ex) {
log_message('error', 'Facebook e1 :' . $ex->getCode());
log_message('error', 'Facebook e1 :' . $ex->getMessage());
} catch(\Exception $ex) {
log_message('error', 'Facebook e2 :' . $ex->getCode());
log_message('error', 'Facebook e2 :' . $ex->getMessage());
}
if ($session) {
$accessToken = $session->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
$_SESSION['fbToken'] = $longLivedAccessToken;
$request = (new FacebookRequest($session, 'GET', '/me'))->execute();
$user = $request->getGraphObject()->asArray();
return $user;
} else {
return FALSE;
}
}
Hope I did help...
Cheers.
Delete your Browser history,Cookies it's cause you tested your before then session have some bad values

Graph API v1.0 from Facebook-PHP-SDK v4

I have Facebook-PHP-SDK v4 and Facebook-JavaScript-SDK. User authenticates via JS and I work with his access token via PHP.
I'd like to call Graph API v1.0, but when I try to specify version in FacebookRequest I get the same error as I did calling APIv2. I tried to specify version in JS block but it did not help with my problem, I still get:
The global ID is not allowed. Please use the
application specific ID instead
How can I fix it? I know that API v1.0 will be unavailable soon but now I'm looking for a temporary and fast solution.
Here is Javascript Init Request:
FB.init({
appId : document.getElementById("facebook_appid").value,
cookie : true, // enable cookies to allow the server use the cookies
xfbml : true, // parse social plugins on this page
version : 'v1.0' // use version 1.0
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response); //show login status
});
And this is PHP block with the request:
/**
* Use long-live access token
**/
FacebookSession::setDefaultApplication($appid, $secret);
if (empty($extended_user_access_token)) {
$session = new FacebookSession($user_access_token);
$session = $session->getLongLivedSession();
$extended_user_access_token = $session->getToken();
} else {
$session = new FacebookSession($extended_user_access_token);
}
/**
* Validate facebook session
**/
try {
$session->validate();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
/**
* Call user by global id
**/
if ($session) {
try {
$request = new FacebookRequest(
$session,
'GET',
'/<my-global-id>',
null,
'v1.0'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
} catch (Exception $ex) {
echo "Exception code: " . $ex->getCode();
echo ", with message: " . $ex->getMessage();
}
}
It does not matter if you add the v1.0 tag to your call, if the App was created after end of April 2014 it will not be able to use v1.0 and you will only be able to use App Scoped IDs.
That is why the global ID does not work, use FB.login to authorize the User and use the gained (App Scoped) ID for the call.