Facebook Icon

Auto Post to Facebook with the Facebook SDK

I was assigned with the task to auto post to my work’s fan page from one of our content sytems. At first, I thought it to be a fairly trivial thing and wouldn’t take me that long but boy was I wrong. I started off by trying a bunch of the existing examples out there already that use curl to mimic someone logging in as they normally would, use regex to match the form variables and submit a status update using curl with the form variables. Facebook didn’t like this and promptly locked my account down for unauthorized access.

Next I moved on to the Facebook API.

The Facebook Graph API allows websites to interact with Facebook users. In order to post status updates, we first need to create an app.

Create A Facebook App

Go to the Developers area of Facebook and click the “Set Up a New App” button. Follow the steps through setting up your application until you get to the edit settings page. Click the “Facebook Integration” tab and in the Canvas URL and Secure Canvas URL enter a URL to a script on your web server. In this script put the following:

print_r($_GET);

App Permissions

Now we need to set up permissions for the app to post on our behalf. Load the following URL in your browser:

https://www.facebook.com/dialog/oauth?client_id=app_id&redirect_uri=redirect_url&
scope=manage_pages,offline_access,publish_stream

app_id = Application ID (Facebook Integration Tab)
redirect_url = Canvas URL (Facebook Integration Tab)

This will give your app full access to your feed and your pages. The offline_access priv will make it so we don’t have to re-authenticate every time we want to post. See Facebook API Permissions for more info.

After you confirm the app access to your account it should redirect back to your canvas URL script. The canvas URL script should output the GET array which should have a “code” variable. Take the code value and plug it into this URL:

https://graph.facebook.com/oauth/access_token?client_id=app_id&redirect_uri=redirect_url&
client_secret=app_secret&code=code_string

app_id = Application ID
redirect_url = Canvas URL (Facebook Integration Tab)
code_string = code from last URL response

This will output an access token variable. This token will allow us to post to our feed.

Post to Your Feed

Head over to GitHub and pick up the Facebook PHP SDK. Now we finally get into some PHP code. Put the following in a separate script:


// Include facebook class (make sure your path is correct)
require_once("path/to/facebooksdk/src/facebook.php");

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => 'app_id'
  'secret' => 'app_secret',
  'cookie' => true,
));

//$token is the access token from the URL above
$post = array('access_token' => $token, 'message' => 'new test post - ' . date('Y-m-d'));

try{
$res = $facebook->api('/me/feed','POST',$post);
print_r($res);

} catch (Exception $e){

    echo $e->getMessage();
}

This will post a message to your feed. Remember to replace the app_id and app_secret with the info from your app.

Post to Your Friend’s Feed

The access permissions we granted above also give us access to post on our friend’s feed. To do so we just need to change the api call above slightly:

$res = $facebook->api('/friend_username_id/feed','POST',$post);

Replace friend_username_id with the profile id or username of your friend (ie. facebook.com/username or facebook.com/profile.php?id=profile_id). This will also work for fan pages you like.

Post as a Fan Page

You may be an admin of a fan page and want to post as the fan page and not yourself. To do this we just need to take one extra step and get a different access token. Load the following URL:

https://graph.facebook.com/me/accounts?access_token=token

Where token is the access token from above. This will output a new access token for each of the pages you have admin access to. Use this token to post as your fan page instead of yourself.

//$token is the page access token variable from above
$post = array('access_token' => $token, 'message' => 'new test post - ' . date('Y-m-d'));

try{
$res = $facebook->api('/page_username_id/feed','POST',$post);
print_r($res);

} catch (Exception $e){

    echo $e->getMessage();
}

Change page_username_id to the ID or username of your page.

The Facebook API was extremely hard for me to grasp as their documentation was very poor. This was the result of a ton of trial and error and I hope it helps you out in your projects.

For more help check out Facebook Developers and Facebook Developer Forums.

Continue Reading

  • No Related Posts
  • Mark

    Hi, great tutorial but I’m struggling to complete it as the links to FB you need to get tokens don’t seem to work. Any advice?

    • Skye

      What does it say? Do you get an error? I put some line breaks in the URLs above to they would wrap properly so double that there isn’t a space in it.

  • Martin

    great tutorial ! Thx

    but I tried to post on a FAN page and got this message, even i did the publish_stream permission…

    (#200) The user hasn’t authorized the application to perform this action

    kind regards Martin

    • Skye

      hmmmm. I definitely ran into this. Are you trying to post as yourself or the fan page? Did you get the access token for the fan page?

  • Shyam

    Hello,

    Thank you so much for the code.

    I have a question, what if I don’t want to set up a callback URL? Here is what I need to do:

    My company X has their own website and Facebook PAGE. Everytime a user signs up on the company website, an update should reflect on Facebook page stating that user Y has signed up. There should be no limit on the number of posts on the facebook page since many users can sign up in a single day.

    Do I need a Callback URL?

    • Skye

      As far as I know you need a callback URL. Once you have the access token you don’t need to use it though. I only used the callback URL to obtain the different tokens.

  • Mark

    It’s ok Skye I figured it out, the facebook process is very convoluted (on their end not yours), I’d been using the wrong tokens to get the needed stuff. Using your tutorial I was able to post as a business page instead, thank you very much for the work.

    • Skye

      Yea exactly. Trying to read their documentation is a nightmare. It outlines certain things but doesn’t say specifically what you can and can’t do. There is also an extreme lack of examples.

  • Works like a charm! Thanks for sharing 😉

  • Pingback: how is send one Content on the site and display that on facebook or twitter ? - SitePoint Forums()

  • Mark

    Skye, have you had any luck with the returning message? I have it set to:

    echo($status);

    $status being my equivalent of your $res. But all I get is it printing “Array” where I need it to return 200 or whatever it should be returning to indicate success so I can be informed it worked.

  • Skye

    It returns an array so do print_r($status) to see what the response is.

    • Mark

      All it seems to return is the post id composed of the ID of the page being posted to and then a different number. I tried doing foreach but it still only prints that so it seems that is all that is being returned.

  • One of the most concise, working explanations I’ve come across so far. Thanks.

  • todd

    Worked like a charm!

  • Melissa

    Hello. I am still relatively new to php, and I am trying to utilize this script to publish content to a facebook wall. However, all I am getting back is: Array ([ID]=>[(facebook page id)_(random number that changes upon page refresh)])

    If anyone has any ideas on what I am doing wrong and how I can make this script publish to a facebook wall like it is suppose to, I would appreciate it.

    Here is the code:

    ‘XXXX’,
    ‘secret’ => ‘XXXX’,
    ‘cookie’ => true,
    ));

    $post = array(‘access_token’ => $accessToken, ‘message’ => $message . date(‘Y-m-d’));

    try{
    $res = $facebook->api(‘/’.$userID.’/feed’,’POST’,$post);
    print_r($res);
    } catch (Exception $e){

    echo $e->getMessage();
    } ;

    ?>

  • Thanks! That was what I have been looking for for weeks!

  • Mango

    Brilliant; thanks!

  • Major thanks to you on putting this post out there. It helped me a great deal. I also had a hard time finding solid documentation on posting to facebook through php until I found this post.

    One question, any idea on how to post to a fan page as that fan page? My wall posts are all showing up as from my personal account.

    • Skye

      See the piece on posting as a fan page. You need to use the fan page token for posting.

  • JSRR

    Thanks you man. This tutorial really worked for me.

  • borgo

    Thanks, it helped!

  • haroun

    (#200) The user hasn’t authorized the application to perform this action

    hi . could you explain me what problem that generates this error message? thanks

  • chris1776

    Is this for the SDK v 4.x? It doesn’t appear to be current.