Push Notifications in Apstrata

Sending notifications to mobile devices has become a fundamental part of many applications. As a developer, you can leverage Apstrata to easily push notifications to mobile devices running on different platforms (iOS, Android) through a consistent interface. This article will explain how you can do this in a step by step approach. Before we proceed however, let us agree on the definition of some terms that will be used throughout the article:

  • A notification is a message that is sent to one or many mobile devices, through a notification service.
  • A notification service is a middle man that sits between a notification provider and mobile devices that run applications that accept notifications sent by the notification provider.
  • A notification provider is a software application that pushes notifications to mobile devices (more specifically, to applications deployed on mobile devices).
  • A mobile application is an application that is downloaded to a mobile device, which will receive the notifications you push.

Since there exist many notification services (notably the Apple Push Notification Service, APNS, and the Google Cloud To Device Messaging service, C2DM), developers who need to push notifications to mobile devices will have to tackle the differences that exist among those services and integrate these differences into their developments. Moreover, the notification providers will also need to handle subscription and unsubscription requests and their persistence. Resorting to Apstrata will help in simplifying the use of notification services by adding a layer of abstraction which provides a unique way of managing notifications and subscriptions, regardless of the targeted notification service.

Push notifications concepts in Apstrata

Apstrata allows you to push notifications to iOS and to Android devices. Let us examine the different concepts that are available in Apstrata:

  • Channel: a channel is a group of mobile devices towards which you can push the same notification. A channel is defined by a unique identifier (unique per Apstrata store), a mobile application ID (the device that will receive the notifications) and a platform (iOS or Android). Once you have a channel available (or upon creation of a channel), you can subscribe mobile devices to it. For example, you might be interested in pushing a notification about special discounts targeting your VIP customers that hold Apple devices. Therefore, it might be interesting for you to create a channel that you could name “vip_channel_ios” and to subscribe to it the devices of your VIP customers who use iPhones (of course, those customers will have to install some application on their iPhones in order to receive the notifications).

Note that you currently cannot have a channel for more than one type of platform (e.g. iOS and Android). This limitation will be removed in the coming release.

  • Application: a mobile application that is downloaded by your users to their mobile devices. You push notifications to an application through one or many channels. Regardless of the targeted platform, you will usually need some kind of credentials in order to be able to push notifications to an application. How to define credentials is platform specific and will be described in the following paragraphs.
  • Device Token: a device token is an identifier of a mobile device. As a developer, you are responsible for providing Apstrata with such identifiers. Usually, this will be part of the functionality of the mobile application your users will download to their device.

So what do I need to get started?

Pretty simple. You just need to:

  • Have a mobile application and create a definition for it in Apstrata (“create an application”).
  • Create a channel to broadcast notifications to mobile devices that have installed the aforementioned mobile application.
  • Push some notifications.

The below paragraphs will explain how you can do that using Apstrata’s API and tools.

How to create an application?

You can create an application in three different ways:

  1. By using the workbench.
  2. Through a call to the “AddCertificate” REST API.
  3. Using one of the client SDK libraries (The JavaScript SDK is used in this article).

1. Create an application using the workbench

Log in to the Apstrata workbench using your Apstrata authkey and secret. Click on “Manage Account” > “Push Notifications” then select a store (if you’re only testing Apstrata then the only store that you should have is the “DefaultStore”).

Once you have selected a store, a panel displaying the applications you have already created opens. Click on “New” or select an existing application and click “Edit” depending on whether you want to create a new application or edit an existing one. For this tutorial, we will click on “New”, which should open the following form:

[

Now we need to fill the form fields:

  • Application Id: a unique identifier (per store) that you choose for your application. It does not have to match the name of the corresponding mobile application.
  • Certificate:
    • If your mobile application is an iOS application, you will need to create a certificate from the Apple developer site and upload it using the panel (please refer to the following for more on certificates)
    • If your mobile application is an Android application, you will need to obtain an authentication token (auth token) from Google C2DM service (please read this article for more). Copy and paste your authentication token into a file and upload it to your application via the above form

Note that the auth token you receive from C2DM has a limited life-time and needs to be renewed on a regular basis. You are usually notified of the expiration of your token by C2DM when pushing a notification: C2DM either sends you a new token if the one you are using is about to expire, or notifies you that your token is obsolete. In all cases, you do not have to worry about renewing your token as this is automatically handled by Apstrata in the background.

  • Password:
    • If your application is an iOS application, you will have to enter the password that you have associated to your certificate.
    • If your application is an Android application, you will have to enter your Google account credentials, i.e. your email and password, separated by a comma (the one you might have created for the application for example).

Click on “Save"in order to save your changes.

Don’t forget that you still need to create a mobile application that will receive the notifications you will push. Your users will have to download this application to their mobile devices.

2. Create an application using the “AddCertificate" API

In order to create an application from your code, you just need to POST a request to the “AddCertificate" service. This service allows you to create a definition for a mobile application.

[code language="javascript"]

<a href=”https://sandbox.apstrata.com/apsdb/rest/” target=”_blank”>https://sandbox.apstrata.com/apsdb/rest/</a>[Your_Auth_Key]/AddCertificate?apsws.time=[TimeStamp]&apsws.authSig=[Your_Signature]&apsws.responseType=jsoncdp&apsws.authMode=simple

[/code]

with the following parameters:

[code language="javascript"]

{ "applicationId": "[Some_Id]", "password": "[Your_password/or Google e-mail,pwd]" }

[/code]

Do not forget that you also need to post the expected “certificate" file (i.e. either the certificate you got from APNS or the authentication key you obtained from C2DM), using the “apsdb_attachment" field.

3. Create an application from the JavaScript SDK

In the following we will be using one of the cool features of the Apstrata JavaScript SDK, which is the “form generator" (an Apstrata widget). The form generator allows you to easily create forms in HTML pages. We will not dive into its intricacies in this article, though we will add some comments to the code in order to make it is easier to understand. Also note that we are just displaying a snippet of the code here. You can download the complete HTML test file from here. We will use the form to upload the certificate file and to set all the other parameters required by “AddCertificate".

The first step, as usual, is to obtain a connection to Apstrata (we assume in this example that we do not already have such a connection), and to create an instance of the Apstrata JS client using that connection

[code language="javascript"]

var connection = new apstrata.sdk.Connection();

var client = new apstrata.sdk.Client(connection);

[/code]

Second, we create a “form definition" that will be used to automatically generate a form when passed to an instance of FormGenerator (later in the paragraph)

[code]

// This is a form definition used to generate a form that will be used to create an application
// it will contain the values of the parameters to post to the "AddCertificate" API, i.e.
// "applicationID", "password", "apsdb_attachment" (for the certificate file)
var formDefinition = {
// The label you need to be displayed on top of the form
label: "Add Certificate",
// A fieldset is a set of fields that will be contained in your form. The field set contains one definition line per field
fieldset: [
// We define a required input field of type string, named "applicationID", that will be labeled as "Application Id"
{name:"applicationID", label:"Application Id", type:"string", required:true},
// We define a required input field of type string, name "password", that will be labeled as "Password"
{name: "password", label: "Password", type: "string", required: true},
// We define a required field of type "file" that allows uploading/downloading a file (or displaying the file if "displayImage" is true
// note that you need to pass the current connection to that field so it can connect to Apstrata to retrieve or upload the file
{name: "apsdb_attachments", label: "Certificate", type: "file", required:true, displayImage:false, connection: connection, value:""}
],
// The form generator will automatically generate buttons for every action name in this array actions: ['save'],
// This is optional, if you add this attribute and set it to true, you will be able to submit the form by hitting "Enter"
submitOnEnter: true,
// We specify which of the actions defined in the actions array above will be used to submit the form
submitAction: "save"
};

[/code]

Third, we need to create an instance of FormGenerator and pass it the above definition. We do this using a function that will be called once the DOM tree is ready and all the widgets are loaded. The function will also take care of adding the DOM node of the FormGenerator instance to the body element of the current HTML document.

function addFormGenerator() {

   // Create an instance of FormGenerator
   var formGenerator = new apstrata.ui.forms.FormGenerator(
   {
       // We pass the form definition that we created above as a parameter
       definition: formDefinition,

       // The "save" function implements the logic that is associated to the "save" action, declared in the "actions"
       // attribute of the above form definition.
       // In our case, "save" will use the Apstrata JS client to post the required data + file using the AddCertificate
       // API. Notice how easy this is: you just need to invoke the "call" function on the Apstrata client,
       // passing it the form node (formGenerator.frmMain) and specifying the HTTP method you need (the "params" is sent
       // empty as all the attributes you need for "AddCertificate" will be retrieved from the form).
       save: function(data) {
	   var params = {};
	   client.call("AddCertificate", params, formGenerator.frmMain.domNode, {method:"post"}).then(
		function(response){
			console.dir(response);
		}
	   )
        }
   });

   var body = dojo.byId("body");
   dojo.place(formGenerator.domNode, body);
};

Finally, once dojo is ready, we invoke the addFormGenerator function.

dojo.ready(function() {

   addFormGenerator();
});

That’s it! You should now be able to fill a form to add new applications to your store.

How to create a channel?

As is the case for creating an application, and for most of what is doable in Apstrata, you can create a channel in three different ways:

  1. By using the workbench.
  2. Through a call to the CreateChannel REST API.
  3. Using one of the client SDKs (JavaScript in this article).

Let us examine what is needed, case by case:

1. Create a channel using the workbench

Log in to the Apstrata workbench using your Apstrata auth key and secret. Click on “Manage Account" > “Push Notifications" and select a store (if you’re only testing Apstrata then the only store that you should have is the “DefaultStore").

Assume for the sake of this example that we are editing an existing application. Select the application you need. Its details will be displayed in a new panel showing the list of channels that push notifications to the selected application as shown in the below figure (the list will be empty if you never created any channel before for that application).

Click on “Edit Application" then on the "+" button in order to create a new channel. The corresponding form will open:

In this form, you will have to define the following elements:

  • An identifier for your channel ("Channel Id" field). As previously mentioned, this identifier has to be unique in the selected store.
  • A platform ("iOS" or “Android"), depending on the targeted platform.
  • A lifetime, in seconds (optional): this specifies how long a notification service will try to push your notification if it wasn’t successful in pushing it the first time.
  • A list of device tokens (optional) that will be subscribed to this channel (just double click on the ellipsis to add a new device token). Note that using the workbench in order to subscribe mobile devices is mainly useful for test purposes.

Click on “Save" once you are done editing the channel details.

2. Create a channel using the REST API

In order to create an application from your code, you need to send a request to the "CreateChannel" API. This is pretty straightforward and your request should look like the following:

https://sandbox.apstrata.com/apsdb/rest/[your_auth_key]/CreateChannel?apsws.time=[timestamp]&apsws.authSig=[your_signature]&apsws.responseType=json&apsws.authMode=simple&apsdb.store=[your_store]&channelId=[channel_name]&platform=[iOS_or_Android]&applicationID=[existing_app_id]

Note that we did not subscribe any device token in the above call. In order to subscribe device tokens, you need to pass the deviceTokens attribute as many times as there are tokens to subscribe (deviceTokens=13344554&deviceTokens=…)

3. Create a channel using the Apstrata JS SDK

Once again, this is pretty easy to do. As usual, we first need to create an instance of a connection to Apstrata and then pass this connection to a new instance of the Apstrata JS client. After that, we call CreateChannel with all the parameters it requires.

dojo.require("apstrata.sdk.Client")

// Create a connection object with your Apstrata credentials (this example assumes you are logging in as
// an account owner
var connection = new apstrata.sdk.Connection({
	credentials: {
		key: "[your_auth_key]",
		secret: "[your_secret]"
	},
	loginType: "master"
})

// Instantiate a Client object passing the connection
var client = new apstrata.sdk.Client(connection)

// Create the call parameter object
var params = {
	"apsdb.store": "DefaultStore",
	"channelId": "MyTestChannelWithTokens",
	"platform": "iOS",
	"applicationID": "SomeMobileApp"
}

// If you need to subscribe device tokens upon creation of the channel, just add the following to the params object
// "deviceTokens" : ["111111", "22222", ...]

// Invoke the "CreateChannel" API
client.call("CreateChannel", params).then(

        // The event handler that gets called on success
	function(response) {
		// Replace with appropriate code
		console.dir(response)
	},

        // The event handler that gets called on call failure
	function(operation) {
		// Replace with appropriate code
		console.dir(operation.response)
	}
)

How to push a notification

  1. Using the Apstrata workench.
  2. Through a call the the “PushNotification" REST API.
  3. Using one of the Apstrata client SDKs (the JavaScript client in this example).

In this example, we will demonstrate how to push a notification to an iOS device. As mentioned at the beginning of this article, there are no differences in the way Apstrata is used depending on the targeted platform. Only the notification and certificate formats differ.

1. Push a notification using the workbench

Open the Apstrata workbench and log in using your Apstrata credentials as account owner. Click on “API Explorer" the select “PushNotification". This displays a form that you need to fill with the expected values:

  • The store to use (use “DefaultStore").
  • channelId: enter the identifier of a channel you previously created (one that is related to the mobile application you will be using on the devices). Make sure your channel is related to an application that has a valid certificate and password and remember to subscribe at least one valid device token to the channel.
  • notification. In this example, we will be using the APNS notification format, since we are pushing to an iOS device.
  • fireAndForget (optional): if set to “false", the notification will be sent synchronously (the caller will expect the result of the push from the notification service).

Once you have entered all the parameters, click on “Run" and wait for the notification to arrive to your mobile device.

2. Push a notification using the REST API

To push a notification from your code, you need to POST a request to the "PushNotification" API. Your request should look like the following:

https://sandbox.apstrata.com/apsdb/rest/[your_auth_key]/PushNotification?apsws.time=[time_stamp]&apsws.authSig=[your_signature]&apsws.responseType=json&apsws.authMode=simple&apsdb.store=DefaultStore&channelId=[your_channel_id]PushNotificationsChannel&notification=[your_notification_in_APNS_format_and_URL_encoded]&fireAndForget=yes

3. Push notification using the Apstrata JS SDK

dojo.require("apstrata.sdk.Client")

// Create a connection object with your auth key and secret (assuming you are logged in as an account owner)
var connection = new apstrata.sdk.Connection({
	credentials: {
		key: "[your_auth_key]",
		secret: "[your_secret]"
	},
	loginType: "master"
})

// Instantiate a Client object passing the connection
var client = new apstrata.sdk.Client(connection)

// The call attributes
var params = {
	"apsdb.store": "DefaultStore",
	"channelId": "PushNotificationsChannel",
	"notification": "{ aps: {alert:You got a new message!,badge : 5, sound : default}}",
	"fireAndForget": "true"
}

// Executes the call to apstrata
client.call("PushNotification", params).then(
	// The event handler that gets called on success
	function(response) {
		// Replace with appropriate code
		console.dir(response)
	},
	// The event handler that gets called on call failure
	function(operation) {
		// Replace with appropriate code
		console.dir(operation.response)
	}
)

 

One thought on “Push Notifications in Apstrata

  1. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>