How to Post to Facebook’s “Stream” using Facebook Connect and XFBML

For my day job, I’ve been developing a facebook application to coincide with its annual SpayDay event. Developing the application has caused several headaches, but once I realized that the majority of the facebook integration wouldn’t happen from the Facebook Developer Toolkit (an ASP.NET Facebook Development Framework), and instead from JavaScript-based XFBML, life got a lot easier. Specifically, the application that I’m developing is an ASP.NET-based iframe application, which probably isn’t the best choice for a facebook application, but it’s what I’m familiar with, so it works.

Facebook recently announced that they are streamlining their primary integration points to the stream (users’ facebook wall posts) and to the inbox. As of writing this article, the inbox API isn’t out yet, but the StreamPublish function (the function that everyone is supposed to use to write to people’s streams and facebook walls), has been out for a while. For the purpose of this demonstration, we’ll be writing an XFBML function using FacebookConnect. Typically this would apply to IFrame Applications on Facebook.

Here’s how to implement posting to a Facebook user’s wall/stream using Facebook Connect.

First, there some prerequisites to place on your page before you can use XFMBL. Basically, it’s a couple of scripts that you need to reference which process the FBML and pass data back and forth to Facebook using a cross-domain receiver. You can learn how to add those scripts to your page here.

The next thing to do is to write a function that will call the XFBML, which will look something like this. Note that the specific text I used is for the SpayDay application, but it’s pretty easy to start making modifications to specific parts of the post.

    <script type="text/javascript">

        //post story function
        function PostStory() {

            //init facebook
            FB_RequireFeatures(["Connect"], function() {

                FB.Facebook.init('PLACE_YOUR_API_KEY_HERE', 'xd_receiver.htm');

                FB.ensureInit(function() {

                    var message = 'I support Bill The Aircraft Carrier in the SpayDay Online Photo Contest! Will you vote for Bill The Aircraft Carrier?';
                    var attachment = {
                        'name': 'Vote for Bill The Aircraft Carrier!',
                        'href': 'http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2', 'caption': '{*actor*} supports Bill The Aircraft Carrier in the SpayDay Online Photo Contest!',
                        'description': 'Bill The Aircraft Carrier`s favorite thing to do is fight the Klingons, but sometimes gets in trouble because he/she likes to fight the Klingons. Bill The Aircraft Carrier makes me smile because... he has spock-like ears.',
                        "media": [{ "type": "image", "src": "http://spayday.factor360.com/calendar_contest/images/69839_1.jpg", "href": "http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2"}]
                    };
                    var action_links = [{ 'text': 'Vote for Bill The Aircraft Carrier!', 'href': 'http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2'}];
                    FB.Connect.streamPublish(message, attachment, action_links, null, "Share your support for Bill The Aircraft Carrier!", callback, false, null);
                });
            });
            function callback(post_id, exception) {
                alert('Wall Post Complete');
            }

}

</script>
A Few Notes:

  • The message variable is the text box that the user can modify. More often than not this will be left blank, but you can give the user a ‘suggestion’ as to what to right.
  • The ‘name’ field in the attachment is the title of the hyperlink, the ‘href’ field is destination URL.
  • the ‘caption’ field is basically a description for the link and the ‘description’ field is an extended description of the link.
  • The media field is used to add images and other media types. The example I have just loads one image, but you can also attach things such as video (look on Facebook’s Wiki for details)
  • The ‘Action Links’ are calls for users to perform a specific action, in our case, voting for the entry. These typically show up on the bottom of stories in the feed.
  • the “False” setting in the streamPublish function (second to last field), indicates that the pop-up should occur before the story is posted. If you want to automatically post the story and have extended permissions to posts to the users wall, you can set this to true and it will post the story without popup.
  • The “callback” function occurs after the wall post is complete. Typically you would use this to provide the user a notice, something along the lines of “Thanks for posting a story”

Now that we have our function written, we simply need to call it. You can use hat with a plain old hyperlink:

<a href=’#onclick=‘PostStory(); return false;’>Post a story!</a>

That’s pretty much it. Once you get the hang of a few different XFBML functions, the rest come pretty easily. You should see something like this if all is well with your code:

post

One debugging hint. If nothing pops up at wall and you can’t get ANY XFBML to work, make sure to set your Facebook Connect URL to the same URL as your Facebook Application in your Application’s settings in the Developer Application.

Comments

  1. I was wondering what all those messages coming from you on facebook were. Very cool.

  2. Hi,

    i am trying to post some text and images from my asp.net (C#) website to my facebook profile wall but i have had no luck so fa. i tried the example you mentioned but nothing seems to be getting posted to facebook after clicking on post story link i get a 404 . i even tried to set extended permission for my app to be able to post on to my own profile wall but that didnt work either. Any suggestions on how to get this to work?

    thanks

  3. Sriraj,

    Are you able to to get the pop-up to display at all? If not, it’s likely a problem related to your setup of the prerequisites, such as the cross-domain receiver, so that you can make use of XFBML

  4. Thanks Matthew,

    i tried setting up the prerequisites several times but still no luck. i cant even get the popup window.

    this is what i have tried
    1. created a new application under developer
    2. i set the connect url to the url of my app
    3. i have selected use IFRAME
    4. created the connector file path >> /connect/xd_receiver.htm

    5. updated your code with new API key and connector file path.

    heres the final code file . please let me know if this looks correct. thanks for your help.
    *******************************************************

    //post story function
    function PostStory() {

    //init facebook
    FB_RequireFeatures([“Connect”], function() {

    FB.Facebook.init(‘MY_API_KEY’, ‘/connect/xd_receiver.htm’);

    FB.ensureInit(function() {

    var message = ‘I support Bill The Aircraft Carrier in the SpayDay Online Photo Contest! Will you

    vote for Bill The Aircraft Carrier?’;
    var attachment = {
    ‘name’: ‘Vote for Bill The Aircraft Carrier!’,
    ‘href’: ‘http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2’,

    ‘caption’: ‘{*actor*} supports Bill The Aircraft Carrier in the SpayDay Online Photo Contest!’,
    ‘description’: ‘Bill The Aircraft Carrier`s favorite thing to do is fight the Klingons, but

    sometimes gets in trouble because he/she likes to fight the Klingons. Bill The Aircraft Carrier makes me smile

    because… he has spock-like ears.’,
    “media”: [{ “type”: “image”, “src”:

    “http://spayday.factor360.com/calendar_contest/images/69839_1.jpg”, “href”: “http://spayday.factor360.com/contest.html?

    page=viewInd&id=48082&contestId=2”}]
    };
    var action_links = [{ ‘text’: ‘Vote for Bill The Aircraft Carrier!’, ‘href’:

    ‘http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2’}];
    FB.Connect.streamPublish(message, attachment, action_links, null, “Share your support for Bill The

    Aircraft Carrier!”, callback, false, null);
    });
    });
    function callback(post_id, exception) {
    alert(‘Wall Post Complete’);
    }
    }

    Post a story!

  5. Thanks a lot!! Wonderful :)
    Fucking cool marketing strategy system.

    What about writing on friend’s wall, sending message, synchronizing friends on our site and on facebook ?

    hihihihihi

  6. Bernard Tolosa says:

    Thanks alot!!!!

  7. Hello My pop ups are working , however i need some help. my connect url is out side facebook, I want my users when click on the name of my Iframe based application , it should not take them to application page not the site url.

  8. Hello,

    I have Usuing facebook.dll(2.0.0.0). I want to post message in Friend’s wall. How i post it.

    Please Help me

  9. Hey so question, I can’t seem to find out how to actually publish a feed of a current stream. Anyone know how to do that? I don’t want to update the stream offsite (which I believe streamPublish is for) i just want to publish the current and updated stream from a fan page to a speparate url. Any help?

  10. Hi Matthew,

    i had used this code but i not got any popup to post data.

    please check following code and correct it.

    Untitled Page

    function PostStory() {

    //init facebook
    FB_RequireFeatures([“XFBML”], function() {FB.Facebook.init(‘c30c11e9c7bf5bfe18de665792374762’, ‘http://localhost:1535/Facebook/xd_receiver.htm’);

    FB.ensureInit(function()
    {

    var message = ‘I support Bill The Aircraft Carrier in the SpayDay Online Photo Contest! Will you vote for Bill The Aircraft Carrier?’;
    var attachment = {
    ‘name’: ‘Vote for Bill The Aircraft Carrier!’,
    ‘href’: ‘http://www.facebook.com/home.php?ref=home’, ‘caption’: ‘{*actor*} supports Bill The Aircraft Carrier in the SpayDay Online Photo Contest!’,
    ‘description’: ‘Bill The Aircraft Carrier`s favorite thing to do is fight the Klingons, but sometimes gets in trouble because he/she likes to fight the Klingons. Bill The Aircraft Carrier makes me smile because… he has spock-like ears.’,
    “media”: [{ “type”: “image”, “src”: “http://spayday.factor360.com/calendar_contest/images/69839_1.jpg”, “href”: “http://www.facebook.com/home.php?ref=home”}]
    };

    var action_links = [{ ‘text’: ‘Vote for Bill The Aircraft Carrier!’, ‘href’: ‘http://www.facebook.com/home.php?ref=home’}];
    FB.Connect.streamPublish(message, attachment, action_links, null, “Share your support for Bill The Aircraft Carrier!”, callback, false, null);
    });
    });

    function callback(post_id, exception) {
    alert(‘Wall Post Complete’);
    }

    }

    <%—-%>
    <%–
    FB_RequireFeatures([“XFBML”], function(){ FB.Facebook.init(“c30c11e9c7bf5bfe18de665792374762”, “http://localhost:1535/Facebook/xd_receiver.htm”); });
    –%>

    <%–
    FB.init(“c30c11e9c7bf5bfe18de665792374762”, “http://test.bigflix.com/xd_receiver.htm”);
    –%>
    Post a story!

  11. senthil.srinivasan says:

    Great Post man Keep it . Keep doing it. Thanks a lot.

  12. tahirmakhdoom says:

    your posts are helpful to me thanx

  13. Altimate article man …..thanks for saving my ass ! …amezing …keep writing . :)

  14. Thanks a lot, this was very helpful and simple. It is so painful how useless the JS API documentation is…

  15. Thanks, I’ve been messing around with the ASP.NET Facebook Developers Toolkit which is worse than useless because of the lack of documentation. I accomplished in 15 minutes what I spent 8 hours trying to do yesterday with that API.

  16. It’s important to remember that XFBML/FB Connect and the tool-kit really serve two purposes. The toolkit is great for getting data from Facebook that you want to interact with via a server-side programming language (C#/VB). XFBML is great for hooking into Facebook’s UI and creating various FBML elements such as posting.

  17. Lincon Ribeiro says:

    Great post! I was searching for something similar and your code really fits on my seek.

    For those who don’t know how to connect, I used the following code (note that the welcome message is in portuguese, but you can translate it =)):

    function update_user_box() {
    var user_box = document.getElementById(“user”);
    // add in some XFBML. note that we set useyou=false so it doesn’t display “you”
    user_box.innerHTML =
    “”
    + “”
    + “Bem-Vindo, . Você está logado na sua conta do Facebook.”
    + “”;

    document.getElementById(“postValue”).innerHTML = ‘Postar’;
    // because this is XFBML, we need to tell Facebook to re-process the document
    FB.XFBML.Host.parseDomTree();
    }

  18. Thanks my friend. This one works just as I wanted…

  19. very good my friend

    thats nice

  20. I am struggling hard to add bookmark and like buttons in iframe for an game application. I searched multiple tutorial. Most of outdated. I am totally confused of how to go further. Can you guide me in this?

  21. Hi,

    What if I just want to post a text to my group wall programmatically from an external aplication, how do we do it?

    thanks

  22. Can you have the siggested textbox “get” like a tagline, or if it is an ebay type site, the products description automatically?

    thank you

  23. Hi,

    I am wondering how to set Facebook Connect URL. In my application profile I am not able to find it.

Speak Your Mind

*