10

The following code is inside a file called facebook_posts.php which I call from my index file like so: <?php require_once("http://www.example.com/design/php/facebook_posts.php"); ?>. However, where this code is put, there is no response. So neither success, nor the catch errors return an error (as I see it). I tried absolute URLs, but that didn't work either. (I hid the api and page information.) Apparently the content that follows the require_once (footer and scripts) aren't loaded. Something seems to go wrong when including the SDK.

I'm not using composer, do I need to require the Facebook\ files or use them? And which ones do I need for retrieving posts from a page?

<?php
// Defining FB SDK with absolute paths
define('FACEBOOK_SDK_V4_SRC_DIR', 'http://example.com/design/Facebook/');
require 'http://example.com/design/php/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

FacebookSession::setDefaultApplication('{my-app-id}','{my-app-secret}');

$session = new FacebookSession('{my-long-lived-access-token}');

// Get the GraphUser object for the current user:

try {
$request = new FacebookRequest(
  $session,
  'GET',
  '/{my-page-id}/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();

var_dump($graphObject);
echo graphObject;
echo "banana";

} catch (FacebookRequestException $e) {
  echo "API ERROR";
} catch (\Exception $e) {
  echo "other error";
}

?>

EDIT: so I just required in all the FB files, and that seems to work. However, I don't know how to traverse/iterate the object that is returned. I.e. how to loop through the different posts (the four latest posts by the page) and echo them in HTML. A base structure would look like this:

<time>{publish date}</time>
<p>{post message}</p>
<a href="{link to included url}">{title to included url}</a>
Community
  • 1
  • 1
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
  • According to https://developers.facebook.com/docs/graph-api/reference/v2.2/page/feed/#read you need an access token, even to read public posts. Without having a user log in to your app, you have no access token though. You could use a page access token – but then you should use a server-side app, because it would not be a good idea to expose that in client-side code. – CBroe Jan 26 '15 at 13:52
  • @CBroe So it seems I'd have to provide permissions through one of the admins of the page. It isn't completely clear to me how this is done though. How do I *give* permission for this? – Bram Vanroy Jan 27 '15 at 06:03
  • https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens – CBroe Jan 27 '15 at 09:12

4 Answers4

22

You need to use a long-lived page access-token.

Page Access Token

These access tokens are similar to user access tokens, except that they provide permission to APIs that read, write or modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token and asking for the manage_pages permission. Once you have the user access token you then get the page access token via the Graph API.

As @CBroe said, you should not use that access token in client-side code as it is secret/private and you don't want anyone to get it.

So for what you want to do, Javascript is not the right choice. You will have to use some server-side code, like PHP, Python or Ruby to get the posts. If that is clear, here is how you can create it.


  1. Create a Facebook app:

    • keep the app id (1) and app secret (2) aside,
    • in the "advanced" settings, activate OAuth in order to avoid The application has disabled OAuth client flow.
  2. You need to create a user access token.

    • go on the Graph API Explorer and select the application you just created,
    • generate an access token: click "Get access token" and tick manage_pages in the "Extended Permissions" tab.
  3. Get your short-lived page access token.

    • still in the Graph API explorer, query me/accounts (GET),
    • find your page and get its access token (3).
  4. Get your long-lived page access token.

    • in your browser, paste https://graph.facebook.com/oauth/access_token?client_id=(1)&client_secret=(2)&grant_type=fb_exchange_token&fb_exchange_token=(3) in the address bar,
    • replace (1), (2) and (3) by your app id, your app secret and your page access token,
    • get your new long-lived access token from the result: access_token=FAKECAALBygJ4juoBAJyb8Cbq9bvwPYQwIaX53fLTMAWZCmDan1netI30khjITZAqcw9uE0lRT4ayWGm2ZCS7s7aZCVhF3ei6m0fuy2AkTkwmzUiJI4NUOZAyZAzuL,
    • use the Access Token Debugger to verify that your access token will never expire.

Now you can use that new access token to retrieve the posts of your page:

$session = new FacebookSession('FAKECAALBygJ4juoBAJyb8Cbq9bvwPYQwIaX53fLTMAWZCmDan1netI30khjITZAqcw9uE0lRT4ayWGm2ZCS7s7aZCVhF3ei6m0fuy2AkTkwmzUiJI4NUOZAyZAzuL');

try {
    $data = (new FacebookRequest(
        $session, 'GET', '/me/posts'
    ))->execute()->getGraphObject()->getPropertyAsArray("data");

    foreach ($data as $post){
        $postId = $post->getProperty('id');
        $postMessage = $post->getProperty('message');
        print "$postId - $postMessage <br />";
    }
} catch (FacebookRequestException $e) {
    // The Graph API returned an error
} catch (\Exception $e) {
    // Some other error occurred
}
Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
  • 1
    this works great, however the long-lived token it returns in the last step for me is only good for 2 months when I check in access token debugger, not forever? – Dan Feb 27 '16 at 15:06
  • I make two files for api just like this link: https://developers.facebook.com/docs/php/howto/example_facebook_login ... So please tell me in which file i put this code – deemi-D-nadeem Apr 07 '16 at 09:37
  • because i got this error: "Fatal error: Class 'FacebookSession' not found in /mounted-storage/home117a/sub009/sc47323-PUDP/www/siteurl.com/fb-test/fb-callback.php on line 37" – deemi-D-nadeem Apr 07 '16 at 09:45
19

I've found that the most voted solution is way too complicated and only lasts 2 months.

For me, this is the best solution using an App with Graph API 2.5:

1.- Create an App.

2.- Go to: https://developers.facebook.com/tools/explorer/

  • Select your new created app on the right top.
  • Select "Get App Token"

3.- Copy this "{ACCESS-TOKEN}" (is in the form: number|hash)

IMPORTANT: (This are not app_id|app_secret!!!)

4.- Query the URL with CURL:

(5).- Equivalent URL:

I've put all of this together in a very simple gist:

https://gist.github.com/biojazzard/740551af0455c528f8a9

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
biojazzard
  • 563
  • 4
  • 8
2
  1. Create App Developer Facebook Page.

Then code exmaple:

<ul>
<?php

$page_name = '{PAGE_NAME}'; // Example: http://facebook.com/{PAGE_NAME}
$page_id = '{PAGE_ID}'; // can get form Facebook page settings
$app_id = '{APP_ID}'; // can get form Developer Facebook Page
$app_secret = '{APP_SECRET}'; // can get form Developer Facebook Page
$limit = 5;

function load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len) {
    $access_token = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
    $access_token = file_get_contents($access_token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
    $access_token = str_replace('access_token=', '', $access_token);
    $limit = 5;
    $data  = file_get_contents("https://graph.facebook.com/$page_name/posts?limit=$limit&access_token=$access_token");
    $data = json_decode($data, true);
    $posts = $data[data];
    //echo sizeof($posts);

    for($i=0; $i<sizeof($posts); $i++) {
        //echo $posts[$i][id];
        $link_id = str_replace($page_id."_", '', $posts[$i][id]);
        $message = $posts[$i][message];

        echo ($i+1).". <a target='_blank' href='https://www.facebook.com/AqualinkMMC/posts/".$link_id."'>".$message."</a><br>";
    }
}

load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len);
?>
</ul>
Ramin Darvishov
  • 1,043
  • 1
  • 15
  • 30
-1

All what you need to get latest posts from facebook feed is described here in my website: http://piotrpasich.com/facebook-fanpage-feed/

In shortcut - use your fanpage feed (please replace {id} by proper id)

https://facebook.com/feeds/page.php?format=atom10&id={id}

You can download the feed with this piece of code:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $rss_url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)');
curl_setopt($curl, CURLOPT_REFERER, '');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$raw_xml = curl_exec($curl); // execute the curl command
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Piotr Pasich
  • 2,639
  • 2
  • 12
  • 14