Send SMS push notifications to your mobile app using IBM Worklight

Many companies today are extending their enterprise applications to the mobile channel. One of the key requirements for enterprise apps is the ability to send short messages (as notifications or alerts) to mobile clients. Notifications drive user engagement and can be based on events or triggered by user behavior or by some pre-condition. IBM® Worklight® V5.0.5 provides support for sending SMS/text notifications to mobile devices in addition to smart phone push notifications. This article explains how you can set up and send SMS notifications with Worklight, using a retail banking scenario as an example. Sample mobile app source is provided to illustrate how to subscribe and receive SMS notifications. This content is part of the IBM WebSphere Developer Technical Journal.

Share:

Thejaswini Ramachandra (thejaswini@in.ibm.com), Advisory Software Engineer, IBM

Thejaswini Ramachandra is an Advisory Software Engineer in IBM Worklight Product Development group. During her twelve years of experience with IBM, she has worked across SWG, STG and Research groups in the areas of Business Process Modeling, Model Driven Architecture and now in Mobile. She has presented at several conferences and has international publications to her credit.



Pradeep Bhat (pradeepsbhat@in.ibm.com), Software Developer, IBM

Pradeep S Bhat has been working with IBM for 4 years. He is currently working as a Software Developer for IBM Worklight. He enjoys solving problems and playing with mobile and web technologies.



Girish Dhanakshirur (girishdhanak@in.ibm.com), Senior Architect, IBM

Girish DhanakshirurGirish Dhanakshirur is an IBM Master Inventor and Senior Architect, leading IBM Mobile Platform development. During his fifteen years with IBM, Girish has led the development of various WebSphere products, such as WebSphere DataPower, WebSphere Voice Server and others. His IP portfolio includes six issued patents. Girish has presented in various forums, including IBM Impact and the Business Agility Conference, and has contributed to many various external publications. He holds a Masters in Computer Science and an MBA, both from Florida Atlantic University in Boca Raton, US.



08 May 2013

Also available in Chinese Russian

Introduction

Today, successful enterprises are redesigning their front-office processes and user interfaces to better engage with their customers. Mobile interfaces are a key aspect of that transformation, where enterprise applications are extended to run on a variety of devices. One of the key requirements is the ability to send notifications or alerts to mobile users. These notifications, in turn, drive user engagement.

In a broad sense, notifications are classified as smart phone-based push notifications and SMS (Short Message Service) messages, or more commonly known as text messages.

  • Push notifications are limited to those phones that have an end-to-end notification mediator offered by the OS provider. For example, iOS-based devices use Apple-provided APNS service. Similarly, Android phones use Google's GCM service.
  • SMS support is ubiquitous and is available in all equipped phones, including smart phones and other non-traditional phone devices.

IBM Worklight V5.0.5 includes support for sending SMS notifications on iOS, Android, Windows Phone 7, Windows® Phone 8, and Blackberry devices that support SMS functions. Using a sample application designed for mobile banking, this article describes the basics of SMS notifications, setting up the SMS notification infrastructure, subscribing to notifications, and sending SMS notifications to a mobile device. By the end, you should understand how to use this feature in developing real-world SMS-based notification applications.


Scenario overview

A typical mobile banking app offers various features to its customers, such as balance enquiry, utility payment, demand draft request, and so on. Such mobile apps can be further extended by adding rich SMS notifications. For example, sending the customer an SMS when their pay is direct-deposited will help the customer keep track of his finances. Similarly, enabling the customer to subscribe to such events to receive SMS alerts can make the mobile banking app much more rich and interactive.

The scenario for this sample app begins with a login screen displayed on a smart phone. When the customer has logged into the banking application, typical banking options display, along with an option for subscribing to SMS alerts. Selecting the SMS alerts option, the user can subscribe or unsubscribe to a set of pre-defined alerts, such as bill pay, cheque deposits, overdraft, and so on.

The development of this scenario is made up of these components:

  • A hybrid mobile banking app built using Worklight Studio.
  • A Worklight adapter running on Worklight Server acts as a connector between the bank back end application and the hybrid mobile banking app.
  • Bank web application service (called AcmeBankWebApplication.war), which exposes a set of interfaces.
  • SMS aggregator for sending SMS messages to the user device.

The subscription flow is shown in Figure 1. At a high level, this is what happens:

  1. The customer downloads the hybrid application on to his device and launches the app.
  2. He then selects the alert category for which he wants to receive SMS alerts.
  3. After performing the initial security handshake (see Worklight documentation on authentication), the app sends a subscribe request to the Worklight Adapter running on IBM Worklight Server.
  4. The Worklight Adapter registers the subscription for that user.
Figure 1. Subscription flow
Subscription flow

The notification flow is shown in Figure 2. Here is what happens:

  1. When the back end service has to notify a customer for one or more subscribed alerts, it invokes a method in Worklight adapter.
  2. The adapter checks whether a SMS subscription already exists for that user and, if it does, sends the SMS alert message through a preconfigured SMS Aggregator.
Figure 2. Notification flow
Notification flow

The set up

IBM Worklight Studio is required to complete this exercise. You can download and use IBM Worklight Developer Edition at no charge. A sample Worklight mobile application (AcmeBank.zip) and a web application (AcmeBankWebApplication.war) are included with this article for download.

To create this sample scenario:

  1. Download the sample materials included with this article. Also, if necessary, download and install IBM Worklight Developer Edition.
  2. Setup the mobile banking app. Import AcmeBank.zip into the Eclipse workspace where you installed Worklight Studio. The AcmeBank project includes an adapter AcmeBankAdapter (in the adapters directory), application AcmeBankApp (in the apps directory), and configuration files authenticationConfig.xml and SMSConfig.xml (in the server/conf directory), as shown in Figure 3.
    Figure 3. Application folder structure
    Application folder structure
  3. Install the application server. An application server will be required to run the banking web application.
    1. Download and install Apache Tomcat v7.0.
    2. In Worklight Studio, create a new server by navigating to File > New > Server > Server and select Apache > Tomcat v7.0 Server.
    3. Click Add, then provide the path where you installed your Tomcat server in the resulting dialog. Click Finish. A new Tomcat server definition is added in Worklight Studio.
    4. To view this configured server go to Windows > Show View > Other > Server > Servers. Select the Tomcat server definition, and modify the port from 8080 to say 8081. This is required because the Worklight console runs on 8080.
  4. Setup back end banking server. Import the AcmeBankWebApplication.war into the same workspace. To deploy the application on the application server, right click on the Tomcat server in the server view and select Add and Remove. In the resulting window, add the web application from Available side to Configured side and click Finish. The application will be configured to run on Tomcat.
  5. Start the server. Right click on the Tomcat server and select Start. Review the logs in the console view to make sure that the server and the web application are started without any errors.
  6. Deploy and configure the mobile app. Open AcmeBankAdapter.xml in AcmeBankAdapter folder. Specify the domain name and port name where your Tomcat server is running. Right click on the Worklight application and select Start Worklight Server. Right click on the AcmeBankAdapter and select Run As > Deploy Worklight Adapter. Right click on AcmeBankApp and select Run As > Build All and Deploy. This action will build the Worklight application for all the configured environments and deploy to the Worklight server. In the sample files, Android environment is already added. The deployed app can be viewed by visiting the Worklight console (Figure 4).
    Figure 4. Worklight console displaying the deployed application and adapter
    Worklight console displaying the deployed application and adapter
  7. Preview the app using an Android simulator. Assuming you have the Android SDK already installed, the Build All and Deploy action in the previous step would result in an Android project by the name AcmeBankAcmeBankAppAndroid. This Android project can be run just like any other Android application. Right click on this project and select Run As > Android Application. If an Android device is connected through USB and USB debugging enabled on the device, then the application will be deployed and launched on the device. If an Android device is not connected, then Android launches the built-in emulator and displays the app in that utility. Notice that the bin folder of the Android project will contain the file AcmeBankAcmeBankAppAndroid.apk, which can also be used to install the application on Android device separately.

After completing the above steps, the mobile application should be running on the device.


Application details

SMSConfig.xml

To send SMS notifications from Worklight Server, one or more SMS gateways must be configured in the SMSConfig.xml file, which is in the /server/conf folder of your project. To configure an SMS gateway, you must set the values of the following elements, subelements, and attributes in the SMSConfig.xml file. Any time changes are made to SMSConfig.xml, the Worklight server must be restarted for the values to take effect.

An SMS aggregator will be required to send SMS messages from a Worklight server. Worklight Server offers a template-ized way of configuring any SMS aggregator. For example, if an SMS gateway expects an HTTP post in the following format to forward SMS messages to a mobile device:

http://myhost:13011/cgi-bin/sendsms?to=destination mobile phone
number
&text=message text&username=fcsuser&password=fcspass

then the SMSConfig.xml should be configured as shown in Listing 1.

Listing 1. Sample SMSConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<sms:config xmlns:sms="http://www.worklight.com/sms/config" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<gateway hostname="myhost" id="gatewayID" port="13011" 
programName="cgi-bin/sendsms" toParamName="to" textParamName="text">
     <parameter name = "username" value = "fcsuser" />
     <parameter name = "password" value = "fcspass" />
</gateway>
</sms:config>

Be aware that the id attribute value in the gateway node in Listing 1 (gatewayID) should match the id attribute in the smsGateway node in application-descriptor.xml. The code from applicationdescriptor.xml shown in Listing 2 illustrates an example of selecting an already defined SMS gateway in SMSConfig.xml.

Listing 2. applicationdescriptor.xml with the gatewayid from SMSConfig.xml
<smsGateway id="gatewayID"/>
<android version="1.0" securityTest="AcmeBankAdapter-mobile-securityTest">
<worklightSettings include="true"/>
 <security>
       <encryptWebResources enabled="false"/>
       <testWebResourcesChecksum enabled="false" 
ignoreFileExtensions="png, jpg, jpeg, gif, mp4, mp3"/>
       <publicSigningKey>Replace this text with the public 
key of the certificate with which you sign the APK. For details 
see the Worklight Developer's Reference Guide.</publicSigningKey>
</security>
</android>

Worklight SMS Notification APIs

The SMS related notification APIs shown in the following listings are used in the sample scenario.

Listing 3. SMS Subscription API is used to subscribe for SMS notifications from a smart phone
       WL.Client.Push.subscribeSMS("alerts", "AcmeBankAdapter", "AcmeBankEventSource", 
phoneNumber, {
      // on success, update the backend
      onSuccess: updateAlertsBackend,
      onFailure: function() 
{ alert("Failed to subscribe to alerts. Please try again later."); }
      });

subscribeSMS takes five parameters.

  • alerts – is the alias that can be used across multiple phones belonging to a same user.
  • AcmeBankAdapter – is the adapter that sets up the event source and also communicates with the Worklight server.
  • AcmeBankEventSource – is the actual event source this application is tied to.
  • phoneNumber – the phone number that will receive the SMS notifications, ideally the current SIM number.
  • Optional JSON block to handle onSuccess and onFailure.

The unsubscribeSMS API (Listing 4) takes two parameters. The first one is the alias, the same string which was used in subscribeSMS (Listing 3), and an optional JSON block to handle onSuccess and onFailure.

Listing 4. SMS UnSubscription API is used to unsubscribe from receiving SMS Notifications
    WL.Client.Push.unsubscribeSMS("alerts", {
    onSuccess: updateAlertsBackend,
    onFailure: function() 
{ alert("Failed to unsubscribe from all alerts. Please try again later."); }
    });
Listing 5. SMS check Subscription API is used to check if there is an existing SMS Subscription for this device
     WL.Client.Push.isSMSSubscribed();
Listing 6. SMS check support API is used to check if SMS Notification is supported for the current environment
       WL.Client.Push.isPushSMSSupported();

Worklight server side API to send SMS notification

Once the subscriptions are set up, the back end application can send SMS alerts to any subscribed phone using the submitNotification adapter function. This function takes two parameters, A userID, which identifies the unique user that should receive the messages, and the actual text to be sent out. The actual Worklight server API to send SMS notification is WL.Server.notifyDeviceSubscription. This function takes a devicesubscription as an argument followed by a JSON string that contains the actual text (Listing 7).

Listing 7. submitNotification function in the adapter
function submitNotification(userId, notificationText){
	var userSubscription =   
WL.Server.getUserNotificationSubscription('AcmeBankAdapter.AcmeBankEventSource', userId);
	if (userSubscription==null){return 
{ result: "No subscription found for user :: " + userId };};
	WL.Logger.debug("submitNotification >> userId :: " + userId + ", 
text :: " + notificationText);	
	WL.Server.notifyDeviceSubscription(userSubscription.getDeviceSubscriptions()[0], 
{badge: 1, alert: notificationText});
	return { result: "Notification sent to user :: " + userId };
  }

See the Worklight documentation for more details on these APIs.


Run the sample application

You should be able to deploy and run the mobile banking application included with this article without any additional modification. Ensure the SMSConfig.xml is configured with the appropriate SMS aggregator information as described earlier. The back end banking webapp service, which is deployed on a Tomcat server, is already pre-populated with dummy account and customer information. Use one of these pre-configured accountIds to log into the app. For example, use AccountId "987654" as account id, phone number 9008029891, and any password string. (The password is not validated in this example.)

Pre-configured account information:

  • Account 1:
    • AccountId: 987654
    • CustomerId: 123
    • FirstName: Mike
    • LastName: Preston
    • PhoneNumber: 9008029891
  • Account 2:
    • AccountId: 456789
    • CustomerId: 345
    • FirstName: Kate
    • LastName: Winslet
    • PhoneNumber: 9008039786
Figure 5. Login panel
Login panel
Figure 6. SMS Alerts option selection screen
SMS Alerts option selection screen
Figure 7. Alert selection screen
Alert selection screen

The Save action results in an SMS subscription being created on the Worklight server. The selected alerts are passed to the back end application through the Worklight adapter and are persisted in the back end application. The back end invokes the Worklight adapter method submitNotification to send out an SMS alert. This can be simulated by manually invoking the submitNotification() of the adapter in Worklight Studio. To do this, right click on the adapter and select Run As > Invoke Worklight Procedure menu option (Figure 8). This displays the Edit Configuration and Launch window, where you can input parameters to configure the function and then invoke it (Figure 9).

Figure 8. Invoke Adapter Procedure action
Invoke Adapter Procedure action
Figure 9. Invoke Adapter Procedure details screen
Invoke Adapter Procedure details screen

Once the message is delivered to an SMS aggregator, the aggregator in turn forwards the SMS message to the Worklight mobile banking application on the end user's device (Figure 10).

Figure 10. SMS received on the device
SMS received on the device

Conclusion

IBM Worklight provides unified APIs to subscribe and send notifications. With Worklight V5.0.5, this support has been extended to support SMS notifications that enable a mobile app to subscribe/unsubscribe SMS notifications, as well as receive SMS messages. Further, SMS notification can be configured with any third party SMS aggregator of your choice. With Worklight 5.0.6, the SMS support is further extended to support traditional (non-smartphone) devices as well. This will be the subject of an upcoming article.


Downloads

DescriptionNameSize
Sample web applicationAcmeBankWebApplication.zip6.3 MB
Sample Worklight applicationAcmeBank.zip10.3 MB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Mobile development
ArticleID=877543
ArticleTitle=Send SMS push notifications to your mobile app using IBM Worklight
publish-date=05082013