Tuesday, 7 August 2012

FaceBook Real-Time Updates API Tutorial - Part I


"The Graph API supports real-time updates to enable your application using Facebook to subscribe to changes in data in Facebook. Your application can then cache data and receive updates, rather than polling Facebook’s servers. Caching data and using this API can improve the reliability of your application and decrease its load times.




Whenever a subscribed change occurs, Facebook makes an HTTP POST request to a callback URL you specify with a list of changes. Your application will generally receive notification of the change within a couple of minutes of its occurrence."

Tutorial
Understanding the documentation for this API can be quite frustrating for some, and it seems like many people are really struggling with understanding how to get updates and how how to handle them. I therefor decided to write a full length tutorial explaining each step in great detail. This part I of a three-part tutorial series on the FaceBook Real-Time Updates API will cover how to subscribe to real-time updates.

The documentation for this API can be found at the bottom of this post.

Here are the steps to set up a subscription:
1) Set up an endpoint URL that receives both HTTP GET (for subscription verification) and POST (for actual change data) requests from Facebook.


Setting up the endpoint URL:
This first step is actually quite easy if you didn't miss the tiny link to the sample code at the bottom of the documentation page.

- Create a php file and copy-paste the code below into the file
- Change the defined VERIFY_TOKEN to be something else than yourownsecretstring
- Upload the file to your server


Code:


Okay, thats it for the first step! Now we are ready to move onto the next step!

2) Make a POST to the graph API url https://graph.facebook.com/yourappid/subscriptions to subscribe, and be ready to handle the verification request.

Making a POST to the graph API
Before we can create a subscription we will need an access token.

Access token
This token is easily obtained by opening your web browser and copy-pasting the following into the address field:

https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APP_ID&client_secret=APP_SECRET

It should look something like this:
1234567891234|ABcDeFG1H2I34jklmNopQrstUvw5xYZ

(For those of you who don't remember where to find your app id and app secret, just go to https://developers.facebook.com -> Apps -> YourApp)

Creating the subscription
Now that we have our access token we can finally go ahead and create a subscription.

This is done by again simply opening your web browser and copying in the code below. Before you do this however, make sure that you can reach the php-file that you have set up. For this tutorial we will just subscribe to feed, but if you need to subscribe to multiple connections then all you have to do is separate them with a comma. (i.e. fields=feed, friends, events)

https://graph.facebook.com/yourappid/subscriptions?access_token=youraccesstoken&object=user&fields=feed&verify_token=yourownsecretstringsetinyourphpfile&method=post&callback_url=http://www.yourwebsite.com/facebook_subscribe.php

When the page is loaded, it should say null if the subscription was successful)
To check if your subscription is set up correctly
https://graph.facebook.com/yourappid/subscriptions?access_token=youraccesstoken&method=get

When the page is loaded, it should look like this:
{
   "data": [
      {
         "object": "user",
         "callback_url": "http://www.yourwebsite.com/facebook_subscribe.php",
         "fields": [
            "feed"
         ],
         "active": true
      }
   ]
}

To delete your subscription

https://graph.facebook.com/yourappid/subscriptions?access_token=youraccesstoken&method=delete


Conclusion
Aight, thats it for this tutorial! I hope that this has helped you to understand how to receive real-time updates from FaceBook.  

Please feel free to leave a short comment to let me know that this tutorial was of any use.

The second part of this tutorial-series will explain how to handle the notifications you receive from Facebook.

UPDATE:
FaceBook has now made it easier to add, modify, and delete subscriptions using their new Realtime Updates panel.

https://developers.facebook.com/docs/howtos/managing-realtime-update-subscriptions/

Documentation
The documentation for the FaceBook Real-Time Updates API can be found at: https://developers.facebook.com/docs/reference/api/realtime/

22 comments:

  1. can i use the localhost for the callback URL? please reply to this query!!!!!

    ReplyDelete
    Replies
    1. No, you can't use localhost because the callback URL needs to be publicly accessible or Facebook can't send you any updates.

      Delete
    2. Instead of localhost use your external IP address. Ie. http://555.555.555.555/you/end/point

      If you are behind a router you may need to forward port 80

      Delete
  2. Hi,
    I have set up the realtime subscription in FB but the POST updates are still not coming to my method. Can it be because the callback URL is an HTTPS URL?
    Thanks,
    Mausam

    ReplyDelete
    Replies
    1. I asked someone at Facebook if the callback url can be https and the reply I got back was: "I think yes, but we do strict SSL cert checking so make sure it's valid or it'll fail without anything on your logs to explain why."

      I hope this answers your question!

      Delete
    2. Also, you can see that they are using https in the example pic on:
      https://developers.facebook.com/docs/reference/api/realtime/

      Delete
  3. Hi Alexander
    Thank you very much for the detailed article.
    We have implemented real time updates for Facebook contacts (friends) changes.
    Are you familiar with similar mechanism for receiving notifications about Google/Gtalk Contacts changes?
    Thanks
    Ofer

    ReplyDelete
    Replies
    1. Hi! Im sorry, but I'm not familiar with any similar API for Google/Gtalk Contacts.
      Best of luck though!

      Delete
  4. Hi, is it possible to create this real-time facebook update in Java application? Pls advice. Thanks.

    ReplyDelete
    Replies
    1. Yes, it is indeed possible. This guide just goes through the steps needed to setup how to receive the notifications and storing them in a mysql database. A java application can easily query a mysql database for the updates.

      The whole idea behind this API is that you don't have to query Facebook's servers for a ton of data every time the user uses your application. The is neither good for your users or for Facebook's servers. You should instead query your own mysql server and ask it if there has been any updates. If there hasn't been a change in data, then you just use the data that you have cached in your application.

      Also, you could query your own mysql database at relatively fast intervals without it becoming an issue because there isn't that much data that get returned.

      Delete
  5. Thank's alot!

    Very good tutorial.

    One question please:

    I have .txt in github, and i want to print the $updates to that file..
    what should i write at "filepath", in order to print the a file?
    the full url for the file? for example:
    https://github.com/usrName/appName/blob/master/fileName.txt
    or just fileName.txt?

    and when should i see the changes? i mean, what should i do in my app in order to get the $updates" in the file?

    Thanks again..

    ReplyDelete
    Replies
    1. You should see the changes as soon as some data is updated for one of the users of your application.(If they get a new friend for example.) You need the whole file path, but I haven't tried outputting stuff directly into files on git, so I can't verify that it works.

      Delete
    2. In your app you will have to poll your own database for the data. Instead of just printing out the data with your endpoint, you have to send the data to a database. This was covered in part II of this tutorial.

      I don't know about android, but with iOS, you can't poll the database directly, so you have to create a php file which queries the database and outputs the data in xml or json. Then you have to parse the data of the output in your app. I haven't covered this part yet in my tutorials.

      Delete
    3. with the database i've come with no problems.. thanksto your tutorial..
      but still, i havnet succeded to print to a file.. i've tried many command such as:

      $myFile = "https://github.com/userName/AppName/master/fileName.txt";
      $fh = fopen($myFile, 'a') or die("can't open file");
      $stringData = "New Stuff 1\n";
      fwrite($fh, $updates);

      and changed the $myFile to :
      https://appName.herokuapp.com/fileName.txt
      or
      ~/AppName/fileName.txt

      but none is working..
      Any thoughts??

      Delete
    4. Writing to a file is just for testing, so as long as part II of this tutorial works for you then you may not want to waste time on that. With that said, the command in the first tutorial does work as long as you provide the full filepath and have the right write permissions.
      If you are using an FTP Client like Filezilla, then all you have to do is rightclick the file and check all the checkboxes that you need under permissions.

      I hope this helps!

      Delete
  6. Hi Alexander Norway,
    This seems to be a nice work.
    Do you know if setting a call back URL is possible in Twitter as well, or any other way to get real time updates. If you are familiar with twitter.
    Sorry for asking completely unrelated question here, but hope it might help others as well.

    Abhinav

    ReplyDelete
    Replies
    1. No problem! I haven't personally tried any of them, but I know that Twitter offer developers a set of streaming API's. Check out the link below:
      https://dev.twitter.com/docs/streaming-apis
      I hope this helps! Good luck!

      Delete
  7. Subscribing was fine, thanks to your great explanation.
    But receiving the data is a real challenge.
    What is php://input stand for, do I need to enter there an address?

    ReplyDelete
    Replies
    1. Actually file_get_contents("php://input") just allows you to read the raw POST data that you get from Facebook. json_decode will then take the encoded string and convert it into a php variable. When the assoc parameter is set to true like in the example above, the returned objects will be converted into associative arrays.

      You might want to just skip ahead to the next part of this tutorial if you are having problems with reading the data. I know that some have had problems writing the data to file, but have had no problems storing the data to a database.

      However, if json_decode simply isn't working for you at all using other examples on the web, then you might be using a php version < v5.2.0.

      Take a look at this article and the comment on how to fix this if that is the case:
      https://secure.kitserve.org.uk/content/how-fix-jsondecode-php-0

      I hope this helps! Good luck!

      Delete
  8. Thanks for this awesome tutorial, sir. But can you please tell me how can I take the result of this file (my server) and then relay this result to a desktop/mobile application (my client) please?

    ReplyDelete
  9. I am getting a (#2200) callback verification failed: Could you please tell me how to solve it?

    ReplyDelete
  10. Hi there does anyone know how I can do this in C# /ASP.NET?

    ReplyDelete