Hein (fub) wrote,

  • Mood:

How to syndicate posts onto a Facebook Page

I've succeeded in syndicating the entries for kliktikfix onto Facebook, where I created a Page for the site. However, the process is a lot more complicated than it is with Twitter, mostly because of the way Facebook uses access authorisation. Also, there is a lot of outdated info to be found when searching for a solution, so I've decided to post the solution I'm using, in hopes it is of use to others.
Please note that this code works at this moment. Future API changes might invalidate it, which it did with so many other posts about the subject.
I'm assuming you know your way around PHP and that you have access to a site that runs PHP scripts.

The use case is as follows:
- I have a site where posts appear. I want to syndicate those posts to a Facebook Page dedicated to my brand/company/website;
- I do not wish to use third-party providers such as If This, Then That;
- I do not run a CMS such as Wordpress, so I can't use a plugin to do this;
- I do run a scheduled task (a cron job) every hour on the hour to create the RSS feed and to post to Twitter. This is a non-interactive process: it's run on the server without any user interaction. The posting to Facebook should be added to that script, and therefore needs to run un-attended;
- The RSS-script is in PHP, so I will need to use the Facebook PHP API.

I'm guessing if you want this, you're already on Facebook. Next step is to create a Page that you will syndicate to. If you don't know how to do that, this page will tell you how to go about it.

So far, so good. Now we have to register a new 'App', so that we can get the keys to the proverbial kingdom!
First, go to the Facebook Developer Home and register as a developer.
Next, register a new App. From the drop-down menu, select 'Apps' and then 'Create a new App'. You get a 'popup' which asks some basic information. You can name your App however you want -- in this example, I'll call it 'MySiteSync'. I'll leave the Namespace empty (we're not going to use that), and select 'Apps for Pages' as the Category.

Click 'Create App' and jump through the CAPTCHA hoop. You will find yourself on your newly create App's Dashboard. Here you can see the App ID and the App Secret, which we will need later to make the API calls.

Next, we need to add our website as the Platform. Click on the 'Settings'-entry in the menu on the left.
Enter your contact e-mail adress under 'Contact Email'. You won't be able to 'publish' your App without it.
On the same page, click on 'Add Platform' and select 'Website' as the platform. For this example, I'm using the site 'www.mysite.org' for the example -- of course you will need to enter your own site there. This is important, because we're going to use the site to get a so-called 'access token' for the Page! Do not forget to click 'Save Changes' here.

Now, click on 'Show' next to the App Secret. You will have to provide your password for this to show up. Copy the App ID and the App Secret into a text editor so it's available when you need it later. Do not share this information with others! You do not want others to impersonate your App, so the App Secret should stay... secret.

Next, we'll be creating a PHP script to get a so-called Page Access Token. The whole Access Token thing is explained in the documentation, but in short, here's what we'll be doing:
- First, we'll log in into our App on our website;
- This log in will ask, amongst others, for the manage_pages privilege. This is the access right that we'll be needing to post onto a Page that we are administering;
- However, the Access Token we'll get through that method, will expire in about two hours. So we will need to convert that short-time Access Token into a long(er)-time Access Token;
- Using that Access Token, we will ask for the accounts of the currently logged in user (and that's us!) to get the Page Access Token. Page Access Tokens do not expire, so we can use them for our unattended calls to the Page.

Follow these steps to create the script to get the Page Access Token:
- Download the Facebook PHP SDK and put the files on your server. In my code, I'm assuming you're putting them in a subdirectory called 'facebook';
- Create a PHP file called GetFBPageToken.php, with these contents:

// FB_APIKEY is your facebook application api key
// FB_SECRET is your application secrete key

$facebook = new Facebook(array(
  'appId'  => $FB_APIKEY,
  'secret' => $FB_SECRET,

// Get User
$user = $facebook->getUser();
// Login url depending on current user.
if (!$user) {
  // We need to log in
  $loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream,offline_access', 'redirect_uri' => 'http://www.mysite.org/GetFBPageToken.php'));
  echo '<a href="' . $loginUrl . '">Click here to log in</a>';
else {
  $facebook -> setExtendedAccessToken();
  $account_info = $facebook -> api("/$user/accounts");

Replace '[APIKEY]' with your App's API Key, and '[APISECRET]' with your App's API Secret. Make sure the redirect-URI in the call to getLoginUrl points back at this same page! In my example, we're putting this script on the root of mysite.org -- you should change it accordingly.
Put the file in the appropriate place (I use FTP myself), and point your browser to this PHP file. You will get a link to log in on Facebook. Click on the link to do so.
If you're not already logged in on Facebook, you will have to do so now. After that, you will get a series of permission pop-ups, like this one:

Accept all of them. The most important one is, of course, 'MySiteSync would like to manage your Pages'.

After this, you will be redirected to your PHP script. You will see some garbage on the screen -- this is the raw output of the account info API call. You might want to view the source because that's more readable. It will look something like this:
array(2) {
  array(1) {
    array(5) {
      string(7) "Website"
      string(10) "[Page Name]"
      string(183) "[Page Access Token]"
      array(6) {
        string(10) "ADMINISTER"
        string(12) "EDIT_PROFILE"
        string(14) "CREATE_CONTENT"
        string(16) "MODERATE_CONTENT"
        string(10) "CREATE_ADS"
        string(11) "BASIC_ADMIN"
      string(15) "[Page ID]"
  array(1) {
    string(101) "[Some URL]"

(I have redacted this output, of course.) You can see here that you (the user), adminsters a Page in the category 'Website', called '[Page Name]'. The '[Page Access Token]' is what we're after: this will allow us to post to the Page! Keep this one a secret as well: otherwise someone could make malicious posts on your Page. Also note down the [Page ID]: we'll need it to adress the page when we're posting to it.

Now we have our Page Access Token. Remove the PHP script from your server, so that it can't be called by someone else -- we don't need it anymore, and we don't want anybody to stumble upon it.

The next step is to create a PHP script that posts to our Page.
- Create a new PHP file called 'PostToFacebook.php', with the following contents:

# Facebook keys

# Initialise Facebook
$facebook = new Facebook(array(
  'appId'  => $FB_APIKEY,
  'secret' => $FB_SECRET,
$facebook -> setAccessToken($PAGE_ACCESSTOKEN);

$attachment = array(
 'message' => 'This is my message',
 'link' => 'http://www.mysite.org/my_post.html',
 'caption' => 'My caption',
 'picture' => 'http://www.mysite.org/thumbnail.jpg'
$post_result = $facebook -> api("/$PAGE_ID/feed", "post", $attachment);

- You will need to fill in the [APIKEY] and [APISECRET] like before. You will also need to fill in the [PAGE ID] and the [PAGE ACCESS TOKEN] that you acquired in the previous step;
- The documentation for the call to $page/feed can be found here. You might want to change this example according to your own tastes;
- Run the PHP file. You will see an entry appear on the Page. Verify that it works;
- Create or change your scheduled PHP script to post to your Page!

When I had it working, I saw the entries appear. There was only one problem: only I saw the entries! Other users or viewers who were not logged in, didn't see them! This gave me a few headaches, but in the end the solution was simple.
When Apps are created, they are put in 'development mode'. When they are in that mode, only the developer will see the posts of the App -- others won't. So you can experiment to your heart's content, to create the links/posts that you think best represents the posts on your site, without fear for having others see your testing work.
When you're satisfied, delete your testing posts, and go back to the App Dashboard in the Facebook Developer area. Click on the 'Status & Review' menu-item on the left. Click on the slider to the right of the question 'Do you want to make this app and all its live features available to the general public?' to put it in the 'YES' position.
From then on, all the posts done through your app are available!

It took me quite a bit of time (and some frustrating moments!) to get this working. I hope this posts helps others achieve the same -- with less time wasted and less frustration!
Tags: software, tools

  • Switching to LED

    Three years ago, I did some calculations on swapping out the 50W halogen spots in the extension for LED equivalents. We did buy a few types to try…

  • Visualising wifi signals

    I saw an interesting video passing by on my Twitter stream: visualising wifi signal strength with blinking LEDs and loooong exposures. It reminded me…

  • Found elsewhere

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded