BenTyler
BenTyler

Reputation: 43

Define token for single call without app id+secret with Facebook SDK 4, Graph API 2.X

With the previous graph api and facebook's SDK, I could define a single token as

'access_token => $token'

and that's it.

But now, with the new SDK, I don't know how to do it and if it's even possible.

This is my new code (which doesn't work):

<?php

require_once 'autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;


$request = new FacebookRequest(
$session,
  'POST',
  '/post_id/comments',
  array (
'access_token' => 'CAALXXXXXXXXXXXXXXXXXXXXXXXXXX',
'message' => 'this is a test',
  )
);

?>

(Of course when i'm running the code i'm changing the values of the access token & post id)

And this is my previous code which works:

<?php

require_once('dir/src/facebook.php');


  $config = array(
    'fileUpload' => true,
    'allowSignedRequest' => false
  );

  $facebook = new Facebook($config);

$comment = $facebook->api('/post_id/comments', 'POST', array(
'access_token' => 'CASDASDASDASDASDASDSDSD',
'message' => 'this is a test message',
)
);


?>

The error which is being shown is:

Catchable fatal error: Argument 1 passed to Facebook\FacebookRequest::__construct() must be an instance of Facebook\FacebookSession, string given, called in /home//public_html/post_comment.php on line 27 and defined in /home/public_html/src/Facebook/FacebookRequest.php on line 187

Please help me to understand how to comment with a single token without the need to login to any app through facebook's new sdk.

Thanks alot.

Upvotes: 0

Views: 666

Answers (1)

user1958555
user1958555

Reputation: 26

First set up a new Facebook application which you can find here.

Follow the prompts and save the App ID and App Secret.

Start a session:

session_start();
FacebookSession::setDefaultApplication($app_id,$secret);
FacebookSession::enableAppSecretProof(false);

But now you want an access token, so let's request one (so we don't have to manually get one every time it expires):

$session = FacebookSession::newAppSession();
$response = new FacebookRequest($session, 'GET', '/oauth/access_token?client_id='.($app_id.'&client_secret='.$secret.'&grant_type=client_credentials'))->execute();
$token = $response->getGraphObject()->asArray()['access_token'];

Now start a session with the new $token and submit a request:

$session = new FacebookSession($token);
$request = new FacebookRequest(
    $session,
    'GET',
    '/'.$post_id.'/comments'
);

Upvotes: 1

Related Questions