Push Notifications Library

Contents

xp 7.+ blue

This library allows sending Push Notifications to a web application.

To start using this library, add the following into your build.gradle file:

dependencies {
  include 'com.enonic.lib:notifications:2.0.0'
}

Usage

The use of Push Notifications requires a combination of client (browser) and server (Enonic XP service) code.

Here is an overview of how to implement the client part for sending notifications.

This library supports the implementation of Push Notifications on the server side.

To use this library in your server JavaScript code, it first needs to be required:

var notifications = require('/lib/notifications');

Generating a key pair

To identify an application with a push service we need a pair of application server keys:

  • The public key will be sent to the client, so that it can subscribe to notifications.

  • The private key is kept on the server, for sending push notifications.

The key pair only needs to be generated once per installed app, and stored in a secure place on the server.

To generate a private/public key pair, call the generateKeyPair function without parameters.

var keyPair = notifications.generateKeyPair();

The function will return an object with the privateKey, publicKey properties represented as Base64 strings. These are normally the ones you will need.
The object will also include privateKeyBytes and publicKeyBytes, the keys represented as a binary stream object.

keyPair = {
    'privateKey': 'GptHhouCpngOtvlG60lu3vtjJN3pGnfGNyDWUjNz7-4', (1)
    'publicKey': 'BG3YaWgwCl6XJmaihPnTRQ3MhxizJg1do6iI9KCanYo0', (2)
    'privateKeyBytes': <stream-object>, (3)
    'publicKeyBytes': <stream-object> (4)
};
1 A new private key encoded as Base64.
2 A new public key encoded as Base64.
3 The private key as a binary stream.
4 The public key as a binary stream.

Sending push notifications

Sending push notifications from the server to a client (that has previously subscribed) requires the following parameters:

  • publicKey Previously generated with the generateKeyPair function.

  • privateKey Previously generated with the generateKeyPair function.

  • endpoint Obtained on the client, in the Subscription object.

  • auth Obtained on the client, in the Subscription object.

  • receiverKey Obtained on the client, in the Subscription object.

  • payload Optional object or string to be pushed to the client.

var status = notifications.send({
    privateKey: 'SmItipweO3J9uzT927AhxVBtBvmJFk4CGD2Y7e5Qjnk',
    publicKey: 'BBfc7IpYHxS2OE2mX8L7XWYrqSBrAPYhZMjN5_Eszb3sWzlEGBu2lmgCU2VmdP1H8iJsuw',
    endpoint: 'https://fcm.googleapis.com/fcm/send/dttNMLkH4jg:APA91bGpKkDCoJe65no',
    auth: 'tkCu6tlXTgcWMVgW7z9qQA==',
    receiverKey: 'BKHSDNB3huPof8GdBXZNKePUrFL4gRgGn4RKKJ-sQtGLphyRfJsUEz9qJWEYeKXXiei4=',
    payload: {
        message: 'Hello',
        sender: 'Enonic XP'
    }
});

API

The following functions are defined in this library.

generateKeyPair

Generate a VAPID public/private key pair.

Returns

The function will return an object with a new key pair:

  • privateKey (string) A new private key encoded as Base64.

  • publicKey (string) A new public key encoded as Base64.

  • privateKeyBytes (object) The private key as a binary stream.

  • publicKeyBytes (object) The public key as a binary stream.

The private key must never be sent to the client.

send

Send a push notification to a client.

Parameters

The request function takes a parameter object with options.
All the parameters are mandatory except payload.

  • options (object) Parameters to send the push notification.

    • publicKey (string) VAPID public key (encoded as Base64).

    • privateKey (string) VAPID private key (encoded as Base64).

    • endpoint (string) The Push service endpoint URL, received as part of the Subscription data.

    • auth (string) The auth key received as part of the Subscription data.

    • receiverKey (string) The p256dh key received as part of the Subscription data.

    • payload (string|object) Message payload to send. Either a string or an object that will be serialized as JSON.

Returns

The function will return the status code from the HTTP request made.
The status will be 2xx if the notification is successfully sent (e.g. 200 OK or 201 CREATED).
A status of 404 or 410 indicates that the subscription data should be deleted from the backend.
See more details about status codes here.

sendAsync

Send a push notification to a client. The notification will be sent asynchronously.
This function returns immediately to the caller, while the sending is executed in the background.
The result of the notification can be obtained by passing a callback function in the error or success parameters.

Parameters

The request function takes a parameter object with options.
All the parameters are mandatory except payload, success and error.

  • options (object) Parameters to send the push notification.

    • publicKey (string) VAPID public key (encoded as Base64).

    • privateKey (string) VAPID private key (encoded as Base64).

    • endpoint (string) The Push service endpoint URL, received as part of the Subscription data.

    • auth (string) The auth key received as part of the Subscription data.

    • receiverKey (string) The p256dh key received as part of the Subscription data.

    • payload (string|object) Message payload to send. Either a string or an object that will be serialized as JSON.

    • success (function) A function to be called if the sending succeeds. The function gets passed the status from the HTTP request made.

    • error (function) A function to be called if the sending fails.

Examples

Generate key pair

var notifications = require('/lib/notifications');

var keyPair = notifications.generateKeyPair();
log.info('Public key: ' + keyPair.publicKey);
log.info('Private key: ' + keyPair.privateKey);

Send Push Notification

var notifications = require('/lib/notifications');

var status = notifications.send({
    privateKey: 'SmItipweO3J9uzT927AhxVBtBvmJFk4CGD2Y7e5Qjnk',
    publicKey: 'BBfc7IpYHxS2OE2mX8L7XWYrqSBrAPYhZMjN5_Eszb3sWzlEGBu2lmgCU2VmdP1H8iJsuw',
    endpoint: 'https://fcm.googleapis.com/fcm/send/dttNMLkH4jg:APA91bGpKkDCoJe65no',
    auth: 'tkCu6tlXTgcWMVgW7z9qQA==',
    receiverKey: 'BKHSDNB3huPof8GdBXZNKePUrFL4gRgGn4RKKJ-sQtGLphyRfJsUEz9qJWEYeKXXiei4=',
    payload: {
        message: 'Hello',
        sender: 'Enonic XP'
    }
});

if (status >= 200 && status < 300) {
    log.info('Push notification sent successfully');
} else {
    log.warning('Push notification failed. Status: ' + status);
}

Send Push Notification in the background

var notifications = require('/lib/notifications');

notifications.sendAsync({
    privateKey: 'SmItipweO3J9uzT927AhxVBtBvmJFk4CGD2Y7e5Qjnk',
    publicKey: 'BBfc7IpYHxS2OE2mX8L7XWYrqSBrAPYhZMjN5_Eszb3sWzlEGBu2lmgCU2VmdP1H8iJsuw',
    endpoint: 'https://fcm.googleapis.com/fcm/send/dttNMLkH4jg:APA91bGpKkDCoJe65no',
    auth: 'tkCu6tlXTgcWMVgW7z9qQA==',
    receiverKey: 'BKHSDNB3huPof8GdBXZNKePUrFL4gRgGn4RKKJ-sQtGLphyRfJsUEz9qJWEYeKXXiei4=',
    payload: {
        message: 'Hello',
        sender: 'Enonic XP'
    },
    success: function() {
        log.info('Push notification sent successfully');
    },
    error: function() {
        log.warning('Push notification failed.');
    }
});

Compatibility

This library requires Enonic XP release 7.0.0 or higher.


Contents

Contents