This is the third and final post in a series that reviews Social Web-to-Lead, a Node.js Facebook application running on Heroku that integrates with Force.com. My first post covered the basic application use case and its use of the REST API to insert Lead data in Salesforce from the Facebook application. The second post described the use of the Redis Heroku add-on and Apex REST to implement a more efficient design for the application that consumed fewer Force.com API calls. In this post I want to describe how Social Web-to-Lead implemented real time push notifications from Force.com to Heroku using HTML5 WebSockets. The entire application codebase is available here and you can also watch a recording of the Dreamforce 2012 session where I demoed the application.

 

Use Case

The primary use case for Social Web-to-Lead was to allow Facebook users to enter their contact information via a ‘Contact Me’ link (typically from the company/brand Facebook Page). That information was then captured as a Lead record in Salesforce via a Force.com REST API call. Imagine a use case where the data flow is reversed. In other words, say that you need to ‘push’ some data updates from Force.com to the Facebook application in real-time. Specifically for Social Web-to-Lead, say that a Force.com Custom Object (Offer__c) stores special customer offers and you want your Facebook application to display new offers as soon as they’re added in Force.com (without requiring a browser refresh). To make it a little more interesting, we’ll display the offers as QR Codes that your Facebook users/fans can print and bring to the physical store. This screenshot shows how this would look like to the Facebook users who click the ‘Exciting Offers’ link on the company/brand Facebook Page (screenshot on the left)  .

Every time that a new offer record is added in Salesforce, the offers page shown on the right would automatically display the new QR encoded offer (without requiring a browser refresh). You can also skip to this point in the session recording to see this real-time push notification in action.

 

Integration Architecture

The figure on the right shows the high-level architecture for the real-time push integration between Force.com and Heroku. We’re using a great Heroku add-on called Pusher to send the push notifications to the web page. Every time that a new offer is inserted in Salesforce, an Apex trigger make an HTTP callout to the Pusher REST API and sends over the offer details. Pusher does the rest. It uses WebSockets to push the offer data to the offer.ejs web page in the Heroku application where we use some simple JavaScript to generate a QR code for the offer.

 

Streaming API – where art thou?

Before we dive into the Pusher based architecture described above, lets address an important question. The use case described above requires real-time push notifications from Force.com to an external web application. That’s an ideal use case for using the Force.com Streaming API. There is one thing about this use case however that precludes the use of the Streaming API. Like all other Force.com APIs, the Streaming API requires authentication with Salesforce before a client can start receiving push updates via the API. In our use case however, the client is a Heroku-hosted web page that is surfaced as a Facebook application. None of the Facebook users will have an equivalent Salesforce identity in this use case and so we cannot authenticate with the Streaming API. For such unauthenticated push notification use cases, an intermediary service like Pusher may be considered.

 

Adding Pusher to the Heroku application

Lets start our deep dive into the integration design by reviewing how you can use the Pusher add-on in a Heroku application. As with all Heroku add-ons, its as simple as running the following command

$ heroku addons:add pusher:sandbox

from the Heroku CLI tool. This will provision a free developer/test account for you on the cloud based Pusher service. Next, in order to receive the WebSockets notifications on your web page, you have to add a couple of lines of JavaScript code to your page. Here is a snippet from the offers.ejs page of the Social Web-to-Lead application that shows that code

<script type="text/javascript">
    var pusher = new Pusher('<<unique app key assigned by Pusher>>');
    var channel = pusher.subscribe('test_channel');
    channel.bind('new_offer', function(data) {
      for (var i=0;i<data.offers.length;i++) {
        var container = $('<div class="qrcode"></div>').appendTo('#qrcodes');
        $('<div><h3>'+data.offers[i].text+'</h3></div>').appendTo(container);
        $('<div></div>').appendTo(container).qrcode(data.offers[i].text);
        $('<br/>').appendTo(container);
      }
    });
</script>

And with just those 10 lines of JavaScript code, you’re ready to receive real-time push notifications from Pusher. As part of initializing the Pusher JS library, you’ll need to pass in the unique Application Key assigned to your application by Pusher (line 2). After installing the Heroku add-on, simply login to your Heroku account, select your Heroku app and then click on the ‘Pusher Sandbox’ Add-on. Select the ‘API Access’ tab and you’ll find your unique application key to include in the JS code. Pusher uses the concept of  binding to specific ‘events’ on a ’channel’ (lines 3, 4). Once we get notified of a new offer event via Pusher, we QR encode the offer data using a simple JQuery plugin (line 8 ) and add the resulting image to the page DOM.

 

Sending push notifications to Pusher from Force.com

Lets complete the circle by reviewing how we push new offers to Pusher from Force.com. It starts with a simple trigger on the Offer__c custom object.

trigger PushOfferNotification on Offer__c (after insert) {

    OfferNotificationToPusher.sendPusherNotification(trigger.newMap.keySet());
}

As experienced Force.com developers know, you can’t make synchronous callouts directly from an Apex trigger. Instead, you use a @future annotation to execute the callout logic asynchronously from the main trigger execution thread. That’s exactly what the OfferNotificationToPusher class does. Here’s a snippet from that class.

public class OfferNotificationToPusher {
    public static final String pusherApiURL = 'http://api.pusherapp.com';
    public class Offer{
        Decimal num;
        String text;
        public Offer (Decimal n, String t){
            num = n;
            text = t;
        }
    }

    @future (callout=true)
    public static void sendPusherNotification(Set<ID> offerIds) {
        JSONGenerator gen = JSON.createGenerator(true);
        List<Offer> offers = new List<Offer>();
        gen.writeStartObject();
        for (Offer__c o : [select Offer_Number__c, Offer_Description__c from Offer__c
                           where id in : offerIds
                           and status__c = 'Active']){
            Offer off = new Offer(o.Offer_Number__c, o.Offer_Description__c);
            offers.add(off);
        }
        gen.writeObjectField('offers',offers);
        gen.writeEndObject();

        String notificationString = gen.getAsString();

        PusherConfig__c config = PusherConfig__c.getAll().values()[0];
        String pusherApiURI = '/apps/'+
                              config.Pusher_App_Id__c +
                              '/channels/'+config.Pusher_Channel__c +
                              '/events';
        Long now = Datetime.now().getTime() / 1000;
        String pusherQueryString =   'auth_key='+config.Pusher_Key__c+'&auth_timestamp='+now+
                                '&auth_version=1.0&body_md5='+
                                EncodingUtil.convertToHex(Crypto.generateDigest('MD5',
                                                          Blob.valueOf(notificationString)))+
                                '&name=new_offer';
        String stringToEncode = 'POST\n'+pusherApiURI+ '\n'+ pusherQueryString;
        String sig = EncodingUtil.convertToHex(Crypto.generateMac('hmacSHA256',
                                               Blob.valueOf(stringToEncode),
                                               Blob.valueOf(config.Pusher_Secret__c)));

        String finalPusherApiURL = pusherApiURL + pusherApiURI + '?' +
                                   pusherQueryString + '&auth_signature=' + sig;
        HttpRequest req = new HttpRequest();

        req.setEndpoint(finalPusherApiURL);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(notificationString);

        Http http = new Http();
        HTTPResponse res = http.send(req);
    }
}

The sendPusherNotification uses the native Apex JSON library and a simple ‘wrapper’ inner class (Offer) to translate the offer data into the appropriate JSON format for the Pusher REST API (lines 14-26). The Pusher API requires a very specific form of authentication and that is what lines 28-45 are doing. Notice also how the authentication code uses a Custom Setting (PusherConfig__c) to store the Pusher App id, key and secret assigned to your application. Once the Apex trigger invokes the above callout logic, Pusher takes care of propagating that offer data to all browser clients that are currently displaying the offers.ejs page of the Heroku application.

Hopefully this blog series have gotten your creative juices flowing on what’s possible when you combine the power of Facebook, Heroku and Force.com. If you have any other interesting use cases for such enterprise-focused social applications, please share them via the comments section.

tagged , , , , , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • http://www.facebook.com/mohitkumar.srivastav.1 Mohitkumar Srivastav

    Thanks sandeep .This is very useful

  • http://www.facebook.com/profile.php?id=100000178098050 Arun Gaikwad

    Silly question:
    Why can’t Web2Lead html page be created and run within facebook app hosted on Heroku? (or anywhere)

    • Anonymous

      Arun – you could do that as well. Embed the Web2Lead form in a Heroku web app.

  • http://th3silverlining.com/ Wes

    Great article, thanks! On your reasoning for not using the Streaming API, Pusher needs to authenticate with Salesforce anyway so why not just make the Heroku app authenticate directly and then using the streaming API?

    • Anonymous

      Hey Wes – good question. Though Pusher and the Streaming API both require authentication, they are actually authenticating different things. Pusher only requires app level authentication which means that all users of Social Web-2-Lead can use a common application credential (the app key and secret assigned by Pusher). The Streaming API on the other hand requires user level authentication which means that each FB user would need a valid Salesforce login. I guess that you could use a single ‘integration user’ Salesforce login with the Streaming API, but that is not necessarily the recommended approach.
      Plus, I wanted to play around with Pusher and WebSockets :)
      Hope this helps clarify my thinking somewhat.