Menu Bar

Wednesday, 28 November 2012

Real-time push notifications from Force.com to Heroku using WebSockets

Real-time push notifications from Force.com to Heroku using WebSockets

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
1$ 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
01
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.
1trigger PushOfferNotification on Offer__c (after insert) {
2 
3    OfferNotificationToPusher.sendPusherNotification(trigger.newMap.keySet());
4}
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.
01public class OfferNotificationToPusher {
02    public static final String pusherApiURL = 'http://api.pusherapp.com';
03    public class Offer{
04        Decimal num;
05        String text;
06        public Offer (Decimal n, String t){
07            num = n;
08            text = t;
09        }
10    }
11 
12    @future (callout=true)
13    public static void sendPusherNotification(Set> offerIds) {
14        JSONGenerator gen = JSON.createGenerator(true);
15        List> offers = new List>();
16        gen.writeStartObject();
17        for (Offer__c o : [select Offer_Number__c, Offer_Description__c fromOffer__c
18                           where id in : offerIds
19                           and status__c = 'Active']){
20            Offer off = new Offer(o.Offer_Number__c, o.Offer_Description__c);
21            offers.add(off);
22        }
23        gen.writeObjectField('offers',offers);
24        gen.writeEndObject();
25 
26        String notificationString = gen.getAsString();
27 
28        PusherConfig__c config = PusherConfig__c.getAll().values()[0];
29        String pusherApiURI = '/apps/'+
30                              config.Pusher_App_Id__c +
31                              '/channels/'+config.Pusher_Channel__c +
32                              '/events';
33        Long now = Datetime.now().getTime() / 1000;
34        String pusherQueryString =  'auth_key='+config.Pusher_Key__c+'&auth_timestamp='+now+
35                                '&auth_version=1.0&body_md5='+
36                                EncodingUtil.convertToHex(Crypto.generateDigest('MD5',
37                                                          Blob.valueOf(notificationString)))+
38                                '&name=new_offer';
39        String stringToEncode = 'POST\n'+pusherApiURI+ '\n'+ pusherQueryString;
40        String sig = EncodingUtil.convertToHex(Crypto.generateMac('hmacSHA256',
41                                               Blob.valueOf(stringToEncode),
42                                               Blob.valueOf(config.Pusher_Secret__c)));
43 
44        String finalPusherApiURL = pusherApiURL + pusherApiURI + '?' +
45                                   pusherQueryString + '&auth_signature=' + sig;
46        HttpRequest req = new HttpRequest();
47 
48        req.setEndpoint(finalPusherApiURL);
49        req.setMethod('POST');
50        req.setHeader('Content-Type', 'application/json');
51        req.setBody(notificationString);
52 
53        Http http = new Http();
54        HTTPResponse res = http.send(req);
55    }
56}
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.

No comments: