Push

Push helps you reach out to your users in a timely fashion with important messages. You can use it to inform users about updates to some piece of data, about new services available nearby or that they are winners in a game. Using Custom server code you can set up triggers which send push notifications to a targeted set of people based on changes in the data you specify.

Kinvey brings Android Push Notifications to you through an integration with Google Cloud Messaging (GCM) and iOS Push Notifications through an integration with AWS SNS. While push notifications can only be configured to be used by either iOS or Android devices, our APIs provide support for registering/unregistering devices and associating them with Kinvey users.

Setup

Console Setup

Android

  1. Navigate to the Firebase Console and follow the guide to create a new project or select an existing project.
  2. Click the gear icon in the top left of the side menu and select Project Settings.
  3. Click on the Cloud Messaging tab and write down the Sender ID and Server Key (formerly known as Project Number).
  4. On Kinvey's console select your App.
  5. Navigate to Engagement and select Push.
  6. Click Configure Push.
  7. In the Android section, fill in the Sender ID and Server Key fields with the respective Sender ID and Server Key values obtained in step 3.
  8. Click Save

iOS

When using Apple Push Notification Service (APNS) you will get two push certificates; one for development and one for production/ad-hoc. These certificates require push notifications to be sent to different servers depending on if your app is in development or production.

The production certificate is only usable if your app is in the App Store.

  1. Generate an Apple Push Certificate .p12 file for your app (instructions).
  2. After you export the .p12 file, on Kinvey's console navigate to Engagement and select Push.
  3. Click Configure Push.
  4. In the iOS section drag your .p12 file generated in step 1 where it says Drag here or click to upload a .p12 file.
  5. Click Save
  6. When you are ready to deploy your app, use your production/ad-hoc certificate. Export the .p12 file, and upload that to our service. Then select production as the certificate type and click Save. Deploying your application is a one-time action and cannot be undone.

Preparation

Before using the endpoints to register and unregister devices, you must configure your app for push notifications through the Kinvey Console. For more information, please refer to the iOS or Android push notification guides.

Note that the iOS and Android libraries already use these endpoints "behind the scenes". If you are using one of these libraries, you need not register or unregister devices explicitly through the REST API.

Registering a device

In order to register a device, send a POST request to /push/:appKey/register-device. The request must be authenticated with either user or master credentials.

The body of the request must contain the following information:

  • platform: A string. Either "ios" or "android".
  • deviceId: A string containing the push notifications token issued by Google or Apple to the device you wish to register.
  • userId: Required only if your request is authenticated using the master credentials. If your request is authenticated with user credentials, the userId will be the ID of the authenticated user, and it needs not be specified in the request body.

The request must contain the following headers: Authorization Content-Type: application/json

Example with master credentials:

POST /push/:appKey/register-device HTTP/1.1
Host: baas.kinvey.com
Authorization: [master credentials]
Content-Type: application/json

{
  "platform": "ios",
  "deviceId": "device ID goes here",
  "userId": "5058c666474f050906000001"
}
HTTP/1.1 204 OK

Example with user credentials:

POST /push/:appKey/register-device HTTP/1.1
Host: baas.kinvey.com
Authorization: [user credentials]
Content-Type: application/json

{
  "platform": "ios",
  "deviceId": "device ID goes here"
}
HTTP/1.1 204 OK

When you register a device for push notifications, the deviceId is saved as a device push notification token in Kinvey (stored in the _messaging.pushTokens property of the active user upon registering for push notification). The active user is taken from the supplied user credentials or the supplied userId (in case master credentials are used).

{
    "_messaging":
    {
        "pushTokens": [
        {
            "token": "ex6xc3igTBI:APA91bG.....",
            "platform": "android",
            "arn": null
        },
        {
            "token": "01c5b7eec38298164e....",
            "platform": "ios",
            "arn": "arn:aws:sns:us-east-1:853461911189:endpoint/...."
        }]
    }
}

A single user account can have multiple device push tokens—one for each device that the user is using the app on. When sending a push notification to a user, the backend is sending the notification to all registered devices (tokens) of that user.

The user account is the smallest entity you can target with a push notification with Kinvey.

Optional fields

When working with the NativeScript, PhoneGap, or Titanium SDKs you will witness the field framework added to the device registration request and subsequently stored with the push token. It specifies the type of multiplatform framework in use and is rarely needed when using the REST API exclusively.

If you need to set framework for any purpose such as testing, use the following values for the respective SDKs: titanium, phonegap, nativescript.

Unregistering a device

The unregister operation allows you to remove the current device from the user account's list of registrations, effectively stopping the user from receiving push notifications on the device. The operation is useful when the user has opted out of receiving this kind of notifications or for another reason. Unregister requires an active user. It will return an error if you call it after logging out the user.

In order to unregister a device, send a POST request to /push/:appKey/unregister-device. The request must be authenticated with either user or master credentials. The body of the request must contain the following information:

  • platform: A string. Either "ios" or "android".
  • deviceId: A string containing the push notifications token issued by Google or Apple to the device you wish to unregister. It is stored as token in the user account object.
  • userId: Required only if your request is authenticated using the master credentials. If your request is authenticated with user credentials, the userId will be the ID of the authenticated user, and it needs not be specified in the request body.

Example with master credentials:

POST /push/:appKey/unregister-device HTTP/1.1
Host: baas.kinvey.com
Authorization: [master credentials]
Content-Type: application/json

{
  "platform": "ios",
  "deviceId": "device ID goes here",
  "userId": "5058c666474f050906000001"
}
HTTP/1.1 204 OK

Example with user credentials:

POST /push/:appKey/unregister-device HTTP/1.1
Host: baas.kinvey.com
Authorization: [user credentials]
Content-Type: application/json

{
  "platform": "ios",
  "deviceId": "device ID goes here"
}
HTTP/1.1 204 OK

Required headers

  • Authorization
  • Content-Type: application/json

Triggering Push Notifications

In addition to using the Console, you can trigger a push notification from Business Logic or a Flex service. This approach allows for greater flexibility as it makes it possible to schedule push notifications, to tie them down to various data events, and to set advanced options supported by Android and iOS.

You can send push notification from either collection hooks, effectively tying the notification to a data event, or custom endpoints which you can call manually or programmatically when needed.

The methods for sending push notifications are provided by the push module available in both Business Logic and the Flex SDK. They include send(), sendMessage(), sendPayload(), broadcastPayload(), and broadcastMessage(). Check the module's reference for detailed information.

The following code uses the onPreSave() before-processing collection hook to send a simple push notification to all users who fancy the winning team. Instead of saving any data to the data store, this request just causes the push notification to be sent.

function onPreSave(request,response,modules){
   var userCollection = modules.collectionAccess.collection('user')
   , utils = modules.utils
   , push = modules.push
   , template = '{{name}}, the {{team}} just won!'
   , pushedMessageCount = 0
   , userCount;

   // Find all users whose favoriteTeam matches
   // the incoming request's winning team.
   userCollection.findAsync({"favoriteTeam": request.body.winningTeam})
   .then(function(userDocs){
     // Total number of messages to send
     userCount = userDocs.length;

     // Each message is customized
     userDocs.forEach(function(doc){
       var values = {
          name: doc.givenName,
          team: doc.favoriteTeam
       };

       // Render the message to send
       var message = utils.renderTemplate(template, values);

       // Send the push
       push.send(doc, message);

       // Keep track of how many pushes are sent
       pushedMessageCount++;

       // Reduce the number of users left to push to
       userCount--;
       if (userCount <= 0){
         // All pushes sent out, complete the request
         response.body = {
             "message": "Attempted to push "
             + pushedMessageCount
             + " messages."
         };
         response.complete(200);
        }
     });
  })
  .catch(function(error){
      response.body = error;
      response.complete(400);
  });
}

The body of the request must have a winningTeam property. For example:

{
  "winningTeam": "Boston Red Sox"
}

Users are expected to have a givenName property and a favoriteTeam property.

The Push notification will be similar to:

Joe, the Kansas City Royals just won!

Push methods

See our reference documentation for push.