Tutorial: Programatically Post a Status Update to Your Facebook Page

In my last post, To OAuth or Not to OAuth, I said I would write a complete tutorial on how to use the Facebook API to post status updates to your own Facebook page. This is that tutorial. Get ready, it’s a doozy.

Definitions

Before we begin there are some definitions I have to set down.

Facebook Account
The actual Facebook account you use to talk to friends and family.
Facebook Page
A separate page you have setup for your brand or online community.
Facebook Application
An application you create which is basically just an set of IDs you need to connect to the Facebook API.

Setup

Before we begin you have to create your facebook account, page and application. I’ll assume you already have an account, or know how to create one. That’s clearly outside the scope of this tutorial. Make sure you remain logged into your Facebook account throughout this entire process.

If you don’t already have one, you need to create a Facebook page. Go to https://www.facebook.com/pages/create.php, and follow the instructions. When you are all done you will end up looking at your new page. It will have a URL that will have the following format.

https://www.facebook.com/pages/PAGE_NAME/PAGE_ID_NUMBER

Save the PAGE_NAME and PAGE_ID_NUMBER. If you already have a page, visit it and look at the URL for the name and/or id number. Make sure that your Facebook account has permission to post status updates on that page. I’ve only tested this on pages where my account is the page administrator. Your mileage may vary otherwise, but I see no reason it wouldn’t work as long as you have the necessary permissions.

The next step is to create a Facebook application. To do that go to https://www.facebook.com/developers/createapp.php and follow the instructions. You will go through a configuration process. You can leave all settings as the defaults. Just save the Application ID and Application Secret, and you will be good to go.

Creating a Facebook Application

Get the Access Tokens Through OAuth

Now it’s time for the tricky parts. You have to give the application permission to access your account. Take the URL below and replace both instances of APP_ID with the ID of the application you just made.

https://www.facebook.com/dialog/oauth?client_id=APP_ID&
redirect_uri=http://www.facebook.com/appcenter/APP_ID&scope=manage_pages,offline_access,publish_stream

Visit this URL in your browser and you will get a dialog box that will ask you whether to allow or deny granting permissions on your account to the application. The page needs to redirect somewhere after you click allow, and it will only allow you to redirect to a page your application owns. That’s why we put the URL of your application’s profile page as the redirect_uri.

The three permissions we are granting are manage_pages, offline_access, and publish_stream. Manage_pages grants the application access to pages which your account has access to. Offline_access means that the application will get an access token that never expires so we never have to do this complicated process ever again. Publish_stream allows the application to post new updates to your account, or any other place your account is able to post updates to, including the page we just created.

Click the allow button. Immediately go to the location bar of your browser and copy and paste the URL to a text editor. Do not lose it. You will see that the URL looks something like this.

https://www.facebook.com/apps/application.php?id=APP_ID
&code=CRAZY_LONG_CODE

That crazy long code is the magic we need. Take that code and use it to create yet another URL in the format that follows. Replace APP_ID with the Application ID as usual. Replace APP_SECRET with the Application Secret. Lastly, put that CRAZY_LONG_CODE where it belongs. Paste the resulting gigantic URL into the location bar of your browser and visit it.

https://graph.facebook.com/oauth/access_token?client_id=APP_ID
&redirect_uri=https://www.facebook.com/apps/application.php?
id=APP_ID&client_secret=APP_SECRET&code=CRAZY_LONG_CODE

If you did everything right you should now be looking at a big beautiful access_token. We will call this the account access token. It gives your facebook application permission to access your account. If you just want to post status updates to your personal account, you can take this access token to the next section. Otherwise, proceed to get the page access token.

In order to get the page access token, we need to visit yet another URL, it looks like this.

https://graph.facebook.com/USER_ID/accounts/?
access_token=ACCOUNT_ACCESS_TOKEN

The USER_ID is the user id of your Facebook account. Mine is apreche because my Facebook profile can be found at https://www.facebook.com/apreche. You might not have a profile URL, in which case you can use a numerical ID instead. If your personal profile is at a URL such as https://www.facebook.com/profile.php?id=NUMBERS then use the NUMBERS as your USER_ID. Take the account access token we got from the previous step and put it in place of ACCOUNT_ACCESS_TOKEN.

Now visit this URL in your browser. You are going to see some slightly complicated text that is in a format known as JSON. It should look something like this.

{
   "data": [
      {
         "name": "PAGE_NAME",
         "access_token": "PAGE_ACCESS_TOKEN",
         "category": "Website",
         "id": "PAGE_ID"
      },
      {
         "name": "APPLICATION_NAME",
         "access_token": "APPLICATION_ACCESS_TOKEN",
         "category": "Application",
         "id": "APPLICATION_ID"
      }
   ]
}

Depending on how many different pages and applications you have on your Facebook account, you may see more than this. Regardless, you are only interested in one thing. Find the section with the PAGE_NAME of the page you want to post to and extract the PAGE_ACCESS_TOKEN from that section. This is the token we have been looking for. Save it and keep it safe.

Making the Post

Now that we have the page access token, we can finally do the actual status update. I will use curl in my examples since that is language agnostic. All you really need to do is make an HTTP POST. In Python you could use urllib. You could also use an appropriate Facebook library for your language, such as the Facebook PHP SDK. It’s up to you to learn how to get this done in your programming language of choice.

Here is what a complete POST looks like using curl in the shell. Remember to put the PAGE_NAME and PAGE_ACCESS_TOKEN where they belong.

$ curl -F access_token="PAGE_ACCESS_TOKEN" \
-F message="testing" \
-F picture="http://i.imgur.com/2uLkT.jpg" \
-F link="http://frontrowcrew.com" \
-F name="Front Row Crew.com" \
-F caption="FRC In the house!" \
-F description="Homepage of GeekNights and other fine free entertainment." \
-F source="http://www.youtube.com/e/NKWpGJ4Xhw8?autoplay=1" \
https://graph.facebook.com/PAGE_NAME/feed

You don’t actually have to include all of that information with every post. Just include the information that is relevant. I have simply included all of the possible information to demonstrate a complete example. Here is what the post above will look like on your Facebook page.

Example Facebook Post

The avatar and the username on the posting are going to be the avatar and username of the page itself. You can’t change those from post to post.

The word “testing” that you see there is the message of the post. Most of the time I imagine you are going to be posting just messages without any other information.

After that is a separate section with the link, picture, video, and everything else. Depending on which combination of information you post, that section will work differently. You only get one of these sections per post, so depending on what you want to do, you might need to stretch it out over multiple postings. If your post only contains a message, this section won’t exist at all.

The link field controls the URL where the user will be sent if they click on the blue text at the top of the section. The name field controls the blue text itself. If you don’t specify a name then Facebook will visit the link and figure out a name to use. In this example the link is http://frontrowcrew.com and the name is “Front Row Crew.com”. If you know HTML you can think of it like a basic “A” tag, since that is what it is.

<a href="LINK_GOES_HERE">NAME_GOES_HERE</a>

The caption controls that light gray text directly beneath the link. The description controls the block of text that is one space beneath the caption. If you leave either of these blank then Facebook will visit the link in question and try to figure out a caption and description on its own.

The picture is where things start to get a little bit complicated. First of all, if you specify a link without a picture, then Facebook will actually pick an appropriate picture based on the link, just like it does with the name, caption, and description. Since it will probably pick a bad picture, I suggest you set the picture manually whenever specifying a link. The picture is just a link to any image on the web. Clicking on the picture thumbnail will take the user to the URL of the link.

You can actually specify a picture all on its own without any link at all. In that case clicking on the picture will take the user to see the picture in its full size. The caption, and description will be extremely barebones unless you manually specify them.

Source may as well be called video instead of source. It needs to be a URL directly linking to a video file, usually a flash video. I’m pretty confident other HTML5 video formats will work, but I haven’t tested them myself. Don’t make the mistake of setting the source to a video’s page like this.

http://www.youtube.com/watch?v=NKWpGJ4Xhw8

That won’t work. You have to set the source to be the actual video file as in the example.

http://www.youtube.com/e/NKWpGJ4Xhw8?autoplay=1

You are on your own on how to structure these links on other video sites besides YouTube. I think I can safely assume the vast majority of people are using YouTube.

If a source is set without a picture, you may get an error if Facebook can’t figure out a video thumbnail on its own. In this case, you must specify a picture to successfully make the post. The picture will be used as the thumbnail. Clicking on the picture will cause the video to play. For YouTube the player is embedded within Facebook itself. As always, your mileage may vary with other video formats and sites.

Now, Facebook is actually pretty smart. Let’s say you specify just a link, and that link goes directly to a YouTube page. Facebook will automatically figure out the source and picture on its own, assuming you do not manually override them.

Lastly, what if you specify absolutely everything as in the example above? Obviously you will have complete manual control over all of the text appearing in the post as well as the picture. Clicking on the picture will play the source video. Clicking the blue text link will always go to the specified link. In this way you can actually link to two different things. Clicking on the picture will play a video, but clicking the link can take people to your blogpost about the video or other related place on the web.

Also, it should be noted that there is nothing forcing the picture and video to match. You can post a thumbnail for a video that is not related to the video at all. Users might be very confused if you abuse it, but there are legitimate reasons for doing so. You might just a brand logo as a thumbnail on a video which does not include that logo.

One last thing. The post will always return some information formatted in JSON. If it fails there will be an error for you to read. If it success there will be an ID that is the ID of the status update you just posted. You can save and use that ID for later if you want to edit or delete the post.

Conclusion

Figuring this out cost me many hours. If this saves even one person from that struggle, then it was worth it.

I hope this can also serve as an example to other people who write technical tutorials or howtos. You can’t just skip over details. You need to include every step and explain the what, why, and how of all those steps. Otherwise readers have to go to ten different sites to piece together the complete picture like I did. Even worse, users might blindly copy and paste without understanding what they are doing.

And of course, I hope this shows just how much of a pain OAuth can be when it is used unnecessarily. With my suggestion of every account also being an application, many of the OAuth steps would be eliminated without sacrificing any security or privacy.

This entry was posted in Technology and tagged , , , , . Bookmark the permalink.

22 Responses to Tutorial: Programatically Post a Status Update to Your Facebook Page

  1. jjray says:

    Very helpful and thanks but I wish you would have done the status update in straight PHP instead of using CURL.

  2. Jason says:

    Thank you. Great post! I was getting absolutely no-where with this, but your description gave me what I needed and was able to post a successful status update.. so really appreciate your clear distinct explanation of the process.. Thank you !!!

  3. Nick Budden says:

    I owe you a hug for this.

  4. Rich says:

    Awesome stuff. Thanks a lot for the level of detail and accuracy; I know how long it takes to put this kind of tutorial together. :)
    -Rich

  5. Ahmad says:

    Very Very Helpfull
    I want to give you a big thanks
    Great Post, Thanks alot
    I think its the only tutorial talking about this

  6. Lara says:

    Thanks so much for this tutorial. Not completely there yet, but you’ve definitely shed some light in my facebook darkness! ;)

  7. Nawed Khan says:

    I have only three words to say…..
    Holly Freaking Awesome !!!

    As someone mentioned above, this is probably the only article that dels with this issue and pretty well done/explained.

    I will try to do the first part (getting the magic token) programatically some times later. For one time thing its okay to do it manually.

    A bigggg thankssss :)

  8. GreatSky says:

    Thanks for the very exhaustive and very detailed post! Now I can proceed to stage three of my Facebook app, thanks! :)

  9. michael says:

    it’s great

    but i have problem with missing share button ?

  10. Gerrit Vos says:

    thank’s for the great post.

    However, when I post to the facebook page as intended, the page timeline says “Gerrit Vos” posted on the timeline, and not “Page Name” posted on the timeline…
    I tried to “use facebook as my page”, but in that case i cannot get access to the procedure of getting an access token…

  11. Aidan Watt says:

    Thank you very much, that really is the clearest tutorial I have found to do this. Might be worth updating the redirect url for the app as it has changed… &redirect_uri=https://www.facebook.com/apps/application.php?
    id=APP_ID is now &redirect_uri=http://www.facebook.com/appcenter/496540333700533 Thanks Again!

  12. Apreche says:

    I will definitely make this update. Thanks!

  13. Thanks for this tutorial. It’s very clear. The update of the redirect_uri suggested by Aidan Watt worked for me before Christmas 2012 (I substituted my own app ID of course) but when I went back and tried again today I could not get an account access token back no matter what. I tried it with and without trailing slashes.

    I wonder if FB have changed something over Christmas. Something related to the offline_access permission perhaps – I notice this is being deprecated.

    The error message I get is:
    “error”: {
    “message”: “Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request”,
    “type”: “OAuthException”,
    “code”: 100
    }

    Here’s what I put tried:

    https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=http://www.facebook.com/appcenter/APP_ID&scope=manage_pages,offline_access,publish_stream

    Then

    https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&redirect_uri=http://www.facebook.com/appcenter/APP_ID&client_secret=CLIENT_SECRET&code=CODE

    Not often I get completely stuck but no idea where to try next.

  14. Apreche says:

    I edited your post before approving it because you included secrets and ids in it. You should be much more careful about security that you aren’t posing your keys to public web pages. You are very lucky I’m nice and didn’t take over your Facebook account.

    I recently had to renew my keys and had a similar problem with the redirect_uri error. There are two possible problems. One is that the redirect_uri has to be exactly identical both times. If there is even one difference it will not work.

    Two is that according to the Facebook documentation

    The redirect_uri you use in your code throughout must have the same base domain as that specified in the App Domain property of your app’s settings, or be a URL of the form https://apps.facebook.com/YOUR_APP_NAMESPACE.

    https://developers.facebook.com/docs/howtos/login/server-side-login/

    So either set the App domain property in your app settings to be the domain of the redirect_uri or change the redirect_uri to follow that pattern.

  15. An update on my last post. I found that this works for me:

    redirect_uri=https://apps.facebook.com/APP_NAMESPACE

    Substitute your own app’s namespace (don’t forget to set this when creating the app, even though the UI suggests it is optional)

    This was from the Facebook docs, so presumably is the approved and modern way of doing it, for now at least. How long this will remain the case remains to be seen, given that Facebook’ official motto is “Move fast and break things”. Nightmare!

    Hope this info is useful.

  16. Whoops, thanks Apreche!

  17. clinton says:

    brilliant, i’m glad i found this

  18. Yogesh says:

    This is just so well written that I was blown away… Facebook should hire you as the head of their documentation team. They could really learn a thing or two from you.

    I have been struggling with getting the post to page feature done with the help of half-baked solutions from other places, but you have nailed it.

    Thanks so much.

    Yogesh

  19. Sam says:

    This is amazing, thanks for posting! I’m hitting a weird OAuth error when posting (error code 2, service unavailable) after a few days of this working without a problem. It looks like it only happens when I include the ‘link’ field in the post. Seems like ‘link’ is still valid in their docs; https://developers.facebook.com/docs/reference/api/post/

    Any thoughts on what might be happening?

  20. Grigor says:

    First of all thank you for this tutorial. It’s exactly what I wanted!

    However I can’t pass the step of getting account access token. I get the same problem with redirect_uri that Gaz Robertson had:

    “Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request”

    Neither my site’s my unique URL (tried different types) nor your suggestion won’t work.

    I wonder what does it mean by “the one you used in the OAuth dialog request”? Is it the redirect_uri used in first step? But it’s exactly the one I use.

    Any ideas?

  21. Grigor says:

    Never mind. I found the problem. The website URL in Facebook settings has a slash at the end. But the URL in the code was without one.
    So this means the URLs have to match EXACTLY :)

  22. jason nevin says:

    Really struggling to get past the first stage of giving my app permissions to post and as far as I can see I am following your instructions to the letter.

    When I post the URL provided I get the following error;

    Given URL is not permitted by the application configuration.: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

    URL I posted is:

    https://www.facebook.com/dialog/oauth?client_id=15_number_id&redirect_uri=https://apps.facebook.com/15_number_id&scope=manage_pages,offline_access,publish_stream

    I’ve tried viewing the page https://apps.facebook.com/15_number_id but I get the following error:

    Sorry, the application you were using is misconfigured. Please try again later.

    Message for developers only:
    To fix this error, please set your Canvas URL and/or Secure Canvas URL in the “App on Facebook” section of your app’s settings. Once it has been set, your users will be redirected to that URL instead of this error page.

    I tried adding a platform (app on facebook) so that I could add a canvas url but when I paste https://apps.facebook.com/15_number_id into the canvas Url field I get a facebook error telling me that I can’t use this uri because its a facebook page.

    Help!!!! Any advice would be appreciated.

    PS. It seems your instructions on creating an app may need updating.

Comments are closed.