Post from server to Facebook page with FB’s PHP SDK 4

On my server, I have a PHP script that runs once a day to post a message and a picture to a Facebook page that I administer. Yesterday Facebook upgraded their API to v2, breaking my script that had been running fine since a few years.

This was the error it threw:

[error] => Array
            (
                [message] => The 'manage_pages' permission must be granted before impersonating a user\'s page.
                [type] => OAuthException
                [code] => 190
            )

Which obviously means that the Facebook app I made to perform the task does not have the proper permission.

The app I made is also used for other tasks. In order not to break them, I created a new app and gave it the proper permissions. After that, I needed to get a page access token that never expires. I also upgraded to version 4 of Facebook’s PHP SDK. Here’s what worked for me.

Create app and token

Create a new website app at https://developers.facebook.com/ . Enter your Site URL and App Domains (www.example.com).

Get a short-lived access token via the Graph API Explorer:

  • from the Get Token menu, pick Get Access Token.
  • in the dialog window, pick manage_pages and publish_pages from the Extended Permissions tab. Facebook will prompt for confirmation.

Copy the token; it’s the short-lived access token with the proper permissions for posting to your page. It’s a pretty long string.

Make a long-lived access token out of the short-lived token. It’s required to create the never-expiring page access token. In the browser that’s logged in to Facebook as app admin, run this script (upload it to your server first…):

<?php
define('FACEBOOK_SDK_V4_SRC_DIR', '/PATH/TO/fb/src/Facebook/'); 
require 'fb/autoload.php'; 
use Facebook\FacebookSession; 
use Facebook\GraphUser;
use Facebook\FacebookSDKException;

// grab your app's APP_ID and APP_SECRET from the developer dashboard   
FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');

// create a FacebookSession with the short-lived access token 
$session = new FacebookSession('SHORT-LIVED_ACCESS_TOKEN');

// Get the AccessToken entity. 
$accessToken = $session->getAccessToken();

try { // get a long-lived token from the short-lived one 
    echo $longLivedAccessToken = $accessToken->extend(); 
} catch(FacebookSDKException $e) { 
    echo 'Error extending the short-lived access token: ' . $e->getMessage(); 
    exit; 
}

Copy the long-lived access token.

To create a never-expiring page access token, run this script. It will list all Facebook pages that you administer, with their names, IDs and access tokens:

<?php
define('FACEBOOK_SDK_V4_SRC_DIR', '/PATH/TO/fb/src/Facebook/'); 
require 'fb/autoload.php'; 
use Facebook\FacebookSession; 
use Facebook\GraphUser;
use Facebook\FacebookRequest; 
use Facebook\FacebookRequestException; 

FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');

// create a FacebookSession with the long-lived access token 
$session = new FacebookSession('LONG-LIVED_ACCESS_TOKEN');

try {
    // Get a list of pages with you as admin
    $request = new FacebookRequest($session, 'GET', '/me/accounts?fields=name,access_token');
    $pageList = $request->execute()->getGraphObject()->asArray();
    foreach ($pageList as $page) {
        print_r($page);
    }
} catch (FacebookRequestException $e) {
    echo 'Request error: ' . $e->getMessage();
    exit;
}

Copy the access_token of the proper page. It’s the never-expiring page access token. Also copy the page’s ID, if you didn’t already have it. It’s a long number.

Paste the token into Facebook’s Access Token Debugger to check. ‘Expires’ should say ‘Never’, ‘Valid’ should be ‘True’, and ‘Scopes’ should include ‘manage_pages, publish_pages, public_profile’.

Post to Facebook page

Fairly easy, given we now have the proper token.

<?php
define('FACEBOOK_SDK_V4_SRC_DIR', '/PATH/TO/fb/src/Facebook/'); 
require 'fb/autoload.php'; 

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
// use Facebook\GraphUser; // edit 2015-11-03: not used
use Facebook\FacebookRequestException;

FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');

$neverExpiringToken = 'NEVER-EXPIRING_PAGE_ACCESS_TOKEN';
$pageID = 'PAGE_ID';

// create a FacebookSession with the never-expiring page access token 
$session = new FacebookSession($neverExpiringToken);

try {
    $post_id = (new FacebookRequest(
        $session, 
        'POST', 
        '/' . $pageID . '/feed', 
        array(
                'access_token'  => $neverExpiringToken,
                'message'   => 'boy do I love the Graph API',
                'link'      => 'http://www.contentecontent.com/blog/',
                'picture'   => 'image URL here',
                'name'      => 'name here',
                'description'=> 'description here'
        )
    )
    )->execute()->getGraphObject()->asArray();
} catch (FacebookRequestException $e) {
    echo 'ERROR! ' . __LINE__ . $e->getMessage();   
} catch (Exception $e) {
    echo 'ERROR! ' . __LINE__ . $e->getMessage();
}

$post_id should now contain the ID of the post you just made to the page.

Make the posts visible to the world

While the app is in development mode, which it is by default, the postings are only visible to you. In the app’s dashboard, set the app to Public in the Status & Review tab.

11 thoughts on “Post from server to Facebook page with FB’s PHP SDK 4”

  1. HI, i finished right now to read your post. I need to ask you if is it possible to create a similar php system to do this work: I have a facebook page, and I need to publish a post which contains the text of a private message in facebook inbox (chat). I explain this things better. The user A send a message to my page (“hello”) the only thing my server must do is to copy this (“hello”) and to publish it in the home page of my Facebook page.
    Could u help me ?

  2. Hi, first of all thanks for this guide, i have a little question about the Facebook App configuration, how did you requested publish_pages and manage_pages permissions?
    I’ve submitted my request but they told me that my app seems to be still in development … maybe they don’t like my screenshots?

    1. I got the permissions in the Graph API Explorer when I created the short-lived access token (see “Create app and token” in my post) . Not by asking Facebook!

  3. Hy.
    I have a problem: i can only add “message” field into feed_data to post (and success to post, fb return object with new_feed id, and this new feed show on my fb page), but when add “link” or other field, facebook alway return error “Invalid parameter”.
    So, please help me.

  4. I have also same problem PhatHT. Do we have any solution on this? When I add link then message is not posting in facebook page. Its always shows invalid parameter response.

    1. From what I read:
      1. make sure the page that the link points to really exists, is publicly available and returns a 200 when FB tries to fetch it.
      2. some reports claim that you’re not allowed to have strings like ‘facebook’ or ‘fb’ in the link URL. It seems that FB does not want us to post links to FB, probably to prevent spam.

Leave a Reply

Your email address will not be published. Required fields are marked *