15 Notifications

Oracle Mobile Cloud Service (MCS) provides a Notifications API to simplify sending notifications to devices running your mobile apps. As a mobile app developer, you can set up your mobile applications for notifications and use the Notifications API to send notifications. As a service developer, you can add implementation code to your custom APIs to trigger notifications.

What Can I Do with Notifications?

Notifications can provide the timely awareness of information and events that mobile users seek. Notifications are short, specific, targeted messages sent to a mobile application. The purpose of a notification is usually to tell users that there is new information available. For example, a user who is running a shopping app might get information about an upcoming sale.

You can send short, highly-targeted messages either on demand or on a predefined schedule to:

  • a specific device ID or a collection of device IDs (mostly useful for testing)

  • a specific user or a collection of users

  • all users and devices associated with a specific mobile backend

  • devices or users for a given operating system (iOS, Android or Windows)

Note:

Push notifications should not be used to send critical or emergency information, because network delays and other issues can make deliveries untimely. However, for everyday uses like sports scores and upcoming sales, notifications are great.

How Are Notifications Sent and Received?

As a mobile application developer, you configure your mobile app to receive notifications over the network. Once your mobile app is configured and installed on a device, it connects to its mobile backend to receive notifications sent by MCS. The steps below summarize the path that a notification takes.

  1. You compose a notification, for example, "Hi! Our storewide sale is tomorrow," and define a recipient for it. You can send the notification to a specific user or device or set of users or devices, to everyone in the mobile backend, or to a specific device type (Android, iOS or Windows). You can send the notification immediately or schedule it to be sent at a later date and time. When you POST a notification, MCS creates an ID for the message. You can use this ID to cancel a message if it hasn’t been sent yet.

  2. MCS uses the recipient you defined to address notifications to the associated device IDs and distribute them to the appropriate push networks for delivery.

  3. The notification is received by the mobile application, and the owner of the device gets it.

What is the Device ID or Notification Token?

The device ID, also known as the notification token, uniquely identifies the specific instance of a mobile application associated with a specific device. This ID is used to ensure that notifications are sent to the correct recipient.

A unique device ID is assigned when a mobile app registers a device with MCS during the device handshake. After that point, the ID can be used to identify that specific recipient. Multiple instances of the same mobile app on the same device have different device IDs. The device ID changes periodically, but this is handled internally by MCS and is transparent to the mobile app.

You can look up the device IDs registered with a mobile app in the Device Registry, from the Notifications page for the associated mobile backend in the MCS UI. To register a specific device ID to be used as a recipient address for notifications, you can use the REST API. Keep in mind that sending a notification directly to a device ID is only useful for testing. There are more efficient ways to send notifications to a specific group of users. For details and examples, see Sending Notifications to and from Your App.

Setting Up a Mobile App for Notifications

To make notifications work in your mobile apps, there are several key steps. Before you begin, you can install the Notifications SDK library to simplify development. The Notifications SDK library can be individually installed into your app, or along with the other mobile client SDK libraries. For details on the SDKs, see The SDKs.

  1. First, get credentials from the notification provider to establish your mobile app as a known item on the network. See Getting Network Credentials for Notifications.

  2. Create a client for your mobile app in MCS, and configure notifications profile(s) by entering the network credentials you got in step 1. See Client Management.

  3. Set up the app to connect to the notification provider from the mobile device and establish rules for communication. See Setting Up a Device Handshake for Notifications.

After you complete these steps, you have a few options for sending notifications from MCS to your mobile app. See Sending Notifications to and from Your App.

Getting Network Credentials for Notifications

To enable your app to send and receive notifications via MCS, you create a client for your app in MCS and configure associated notifications profile(s) using the appropriate network credentials.

The sections that follow include details on how to get network credentials for different network providers:

For detailed instructions on configuring clients and profiles with these network credentials, see Client Management.

Android: Google API Key
Configuring an Android mobile app for notifications requires Firebase Cloud Messaging (FCM), formerly Google Cloud Messaging (GCM).

Note:

Google Cloud Messaging (GCM) is being phased out, so you should configure new apps with FCM. See Migrate a GCM Client App for Android to Firebase Cloud Messaging on Google Developers.
For details on setting up your Android mobile application, see Set Up a Firebase Cloud Messaging Client App on Android on Google’s developer site. This page includes detailed instructions and a link to generate the required configuration file for your project, as well as information on using the Instance ID API to create and update registration tokens.

Note:

When you generate the configuration file for your app, make sure you choose to enable the Cloud Messaging service.
In the Android app’s AndroidManifest.xml file, within the <application> node, add the following entries:
<service android:name="oracle.cloud.mobile.notifications.McsRegistrationIntentService" android:exported="false" /> 
<service android:name="oracle.cloud.mobile.notifications.GcmTokenRefreshListenerService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
Google Play Services must be added as a dependent library in the application's build file, or these services will be flagged in error.
When generation is complete, the Project Number (aka Sender ID) and API Key are displayed. You need these credentials to register the mobile app for notifications inMCS. They are unique to the mobile app and can’t be used to send notifications to any other app. You also need these values to get a registration token from FCM and set up the connection with MCS, as described in Setting Up a Device Handshake for Android.
iOS: Apple Secure Certificates
Notifications require additional secure certificates from Apple, in addition to the certificate used to set up your account. This section assumes you have an Apple Developer account. For information on using notifications in iOS, see the Local and Remote Notification Programming Guide on http://developer.apple.com.

Notifications make special use of Apple's network, so Apple wants extra security protections. You need one of the following secure certificates:

  • Apple Push Notification service SSL (Sandbox) certificate for developing and testing your application with notifications while you do development. Sandbox certificates are intended for automated QA environments where devices don’t change often. In most cases, spam filters should be disabled.

  • Apple Push Notification service SSL (Production) certificate for releasing your application to Apple’s App Store. Apple requires this certificate before you can ship your app to the public, but you can wait until your app is finished to get it.

The steps for getting a Sandbox or Production certificate are very similar to the steps you used to get the first secure certificate when you set up your app. This section assumes that you already set up your Apple developer account, got the required secure certificate, and set up an Application ID and a Provisioning Profile.

  1. If you didn’t enable notifications in your provisioning profile when you created your App ID, go back and enable it now.
  2. Get your certificate(s) from the Apple Developer Center. Use the App ID you set up when you created your app.

    Note:

    Follow Apple’s direction to create a Certificate Signing Request (CSR) file, then export it to a .p12 file to upload it to MCS. Do not password protect the .p12 secure certificate. (Leave the password field blank when you save the .p12 file.)
You need your certificate to register the mobile app for notifications in MCS. It is unique to the mobile app and can’t be used to send notifications to any other app. Once you have configured these extra certificates, you can get a device token from Apple and set up communication with MCS, described in Setting Up a Device Handshake for iOS.
Windows: WNS Credentials
Configuring a Windows mobile app for notifications requires a unique set of credentials for Windows Push Notification Service (WNS). This section assumes you have a Microsoft Developer account.
The following credentials are required to authenticate with WNS:
  • Client ID (also called the Package SID)

  • Client Secret (also called a secret key)

To get these credentials, register your mobile app in the Windows Store Dashboard, accessible from the Windows Dev Center. For details on WNS, see Windows Push Notification Services (WNS) overview on MSDN.

You need these credentials to register the mobile app for notifications in MCS. They are unique to the mobile app and can’t be used to send notifications to any other app.

Syniverse: SMS Credentials

To send Short Message Service (SMS) messages using the Syniverse Messaging Service, the first step is to establish a profile on the Syniverse Developer Community, where you subscribe to the service, register your app, and get credentials.

Create a Profile on the Syniverse Developer Community

To subscribe to the Syniverse Messaging Service, you need a profile on the Syniverse Developer Community. If you already have a profile, you can skip this step.

  1. Go to the Syniverse Developer Community (developer.syniverse.com).

  2. Click Sign Up in the top right corner of the site and enter the requested information.

  3. If you have an invitation code from a company in the Syniverse Developer Community enter that into "Company invite code" field. If not, ignore this step.

  4. Read and accept the Terms of Service.

  5. Check the Captcha box and answer the challenges to prove you aren’t a robot.

  6. Click Create profile.

  7. When the confirmation email arrives, click the link in the email and verify your user credentials.

Subscribe to the Syniverse Messaging Service

To use SMS in your apps using the SMS short code you got from Syniverse, you need to subscribe to the Syniverse Messaging Service.

  1. Log in to the Syniverse Developer Community (developer.syniverse.com).

  2. Click your user name in the top right corner and select Company. SDC generates an account automatically and provides a default credit of $5 to all users on sign up. Verify that your accounts have a billing address associated with them.

  3. Navigate to Service Offerings > Messaging Offering and click Subscriptions.

  4. Click Subscribe and select “Initial account for [Your username]”

    1. Read and accept the Terms of Service.

    2. Select Confirm.

    3. Verify that your account is listed in Subscriptions.

  5. If you’re using a Syniverse-provisioned public channel to test messages, you also need to add test phone numbers to the associated whitelist. (Whitelisting is only necessary when testing SMS to U.S. or Canada phone numbers and isn’t required for production apps.)

    1. Click your user name in the top right corner and select Company.

    2. On the Company page, click the Whitelist tab.

    3. Click Add phone number and enter your phone number in the ITU-T E.164 format (i.e., +11234567890).

    4. Click Send confirmation code to send a randomly generated number to the phone number in a text message.

    5. Retrieve the confirmation code from the text message and enter it in the Confirmation code field. Click Add to confirm the phone number whitelist.

    6. Verify that your phone number is included in the whitelist table with "Validated" status.

Register Your App and Get Credentials

Before messages can be sent through the Syniverse Messaging Service, there must be an application configured in the SDC platform. Once your app is registered, you can generate the required credentials.

  1. Log in to the Syniverse Developer Community (developer.syniverse.com).

  2. Click Applications.

  3. Click New application.

    1. Give your application a name and description and click Save.

    2. Click the gear icon next to your app name and select Edit.

    3. Click SDC Self Service and make sure all the options are selected.

    4. Click Account & APIs and select the "Initial account for [Your username]" from the Account dropdown.

      Turn on the following services: Messaging, SDC Gateway Services, Event Subscription Services, Voice & Messaging and Whitelisting Services.

    5. Click Save.

  4. Generate the required credentials.

    1. From the Applications page, click the gear icon next to your app name and select Edit.

    2. Click Application permissions.

    3. Make sure Require user token validation is unchecked.

    4. Click the first check box next to your app name to give your application full entitlements.

    5. Click Auth Keys to generate the credentials.

    6. Copy and store the keys to a safe place on your computer.

    7. Click Save.

The next steps are to create a client for your mobile app in MCS, and configure notifications profile(s) by entering the network credentials you got above, described in detail in Client Management. After you complete these steps, you have a few options for sending notifications from MCS to your mobile app as shown in Sending Notifications to and from Your App.

Setting Up a Device Handshake for Notifications

To allow notifications to be delivered to your mobile app through the network, every platform requires some form of “device handshake” to register and establish the protocol for communication.

Setting Up a Device Handshake for Android
This section assumes you have already created a configuration file for your app. You will need the Sender ID (Project Number) you got when you configured your project, described in Android: Google API Key above.

In addition to the device handshake, an Android app needs to extend GcmListenerService to define a receiver for the Notifications service. By overriding the onMessageReceived method in the Android SDK, you can perform actions based on the incoming message. For more information on handling notifications in Android, see Simple Downstream Messaging on Google Developers.

In your app’s main/AndroidManifest.xml file, just before the closing </application> tag, register service and broadcast receivers for the Notifications service, as shown below.
<application>
...
	<receiver android:name="oracle.cloud.mobile.notifications.Mcs2GcmListenerService"
            android:permission="com.google.android.c2dm.permission.SEND">
		<intent-filter>
			<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
			<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
			<category android:name="YOUR.PACKAGE.NAME"/>
		</intent-filter>
	<receiver>
</application> 
Set permissions to receive and display notifications by inserting these entries in the Android manifest (somewhere above the <application> entry).
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<permission android:protectionLevel="signature"
            android:name=YOUR.PACKAGE.NAME.permission.C2D_MESSAGE"/>
<uses-permission android:name="YOUR.PACKAGE.NAME.permission.C2D_MESSAGE"/>
<application>
Then, to establish communication and register for notifications with the MCS server, here’s what the device handshake might look like in an Android app, using the SDK:
...
import oracle.cloud.mobile.exception.ServiceProxyException;
import oracle.cloud.mobile.mobilebackend.MobileBackendManager;
import oracle.cloud.mobile.notifications.Notifications;

public class MainActivity extends Activity {
    private Notifications mNotification;
    private final String PROJECT_ID = "PROJECT_ID_COPIED_FROM_GOOGLE_API_CONSOLE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.registerNotificationClient();
        ...
    }
//method that initializes and returns the Notifications client
    private void registerNotificationClient(){
        try {
            mNotification = MobileBackendManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Notifications.class);
            mNotification.initialize(this, PROJECT_ID);
        } catch (ServiceProxyException e) {
            e.printStackTrace();
        }
    }
...
}

Obtaining an FCM Registration Token

You also need the Sender ID to register your app with FCM or GCM to get a registration token. The registration token is passed to MCS, which packages it with the notification to tell Google that your app and the device it runs on are legitimate recipients on the network. Google provides the Instance ID API to handle registration tokens. See Set Up a Firebase Cloud Messaging Client App on Android on Google Developers.

To set up a callback on successful registration, you could add code like the example below:
public void onClick(View view) {
    try {
        //Registration process callback
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                SharedPreferences sharedPreferences =
                        PreferenceManager.getDefaultSharedPreferences(context);
                boolean sentToken = sharedPreferences
                        .getBoolean(NotificationsConfig.SENT_TOKEN_TO_SERVER, false);
                if (sentToken) {
                    Logger.debug(TAG, "Token retrieved and sent to server! App can use FCM or GCM");
                } else {
                    Logger.debug(TAG, "An error occurred while either fetching the InstanceID");
                }
            }
        };

				//call on successful registration
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(NotificationsConfig.REGISTRATION_COMPLETE));

        //Initialization of MCS notifications service
        not = MobileBackendManager.getManager().getDefaultMobileBackend(view.getContext()).getServiceProxy(Notifications.class);
        boolean result = not.initialize(view.getContext(), "714568881816");

    } 
		catch (ServiceProxyException e) {
        e.printStackTrace();
    }
}
After you’ve set up and registered your app, it can send and receive notifications. For details and sample code, see Sending Notifications to and from Your App.
Setting Up a Device Handshake for iOS
As an iOS developer, to make a device handshake happen in your mobile app, you need to add some code to get a device token, get a notifications object, and register your app for notifications.
Here’s the code you add to your Xcode project to set up a device handshake for your iOS application. The registration code should be called each time the app starts.
  1. Get a device token from Apple.
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)]){
    	//use registerUserNotificationSettings for iOS 8 and later
    	UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForType:(UIUserNotificationTypeBadge
    				|UIUserNotificationTypeSound
    				|UIUserNotificationTypeAlert) categories:nil];
    	[application registerUserNotificationSettings:settings];
    } else {
    	//We expect deprecation warnings here - this is for iOS 7.1 or before
    	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
    	(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }	

    After calling the above lines of code, the Apple Push Notification Service (APNS) will call one of the delegate methods based on the success or failure to retrieve the device token. If successful, one of the following methods is called: didRegisterUserNotificationSettings: (iOS 8 or later) or didRegisterForRemoteNotificationsWithDeviceToken: (iOS 7.1). In case of an error, the didFailToRegisterForRemoteNotificationsWithEffor: method is called.

  2. Get the MCS Notifications SDK object.
    (OMCNotifications *) getOMCNotifications{
       OMCAuthorization *auth = [[OMCMobileBackendManager sharedManager] mobileBackendForName:
         <Name_of_Mobile_Backend_from_OMC.Plist>].authorization;
       OMCNotifications* omcNOtifications=nil;
       NSError* err = [auth authenticate:<Username> password:<Password>];
       if (!err){
          omcNotifications = [[[OMCMobileBackendManager sharedManager] mobileBackendForName:
             <Name_of_Mobile_Backend_from_OMC.Plist>] notifications];
       }
       return omcNotifications;
    }
    
  3. Register for notifications in the MCS server using the MCS Notifications SDK object. Note that omcNotifications is the object of OMCNotifications.class.
    [omcNotifications registerForNotifications:dataDeviceToken
    	onSuccess:^(NSHTTPURLResponse *response){
    		dispatch_asynch(dispatch_get_main_queue(),^{
    			//Update UI here
    		});
    	} onError:^(NSError *error){
    	dispatch_async(dispatch_get_main_queue(),^{
    			//Update UI here
    		});
    	}];	

Next, register your mobile app with the associated MCS mobile backend, and enable notifications. For detailed instructions, see Registering an App as a Client in MCS in the Mobile Backends chapter.

After you’ve registered your app, it can receive notifications from a range of sources. For details and sample code, see Sending Notifications to and from Your App.
Setting Up a Device Handshake for Windows
This section assumes you have already registered your mobile app with WNS, described in Windows: WNS Credentials.
Here’s what a device handshake might look like in a Windows app, using the SDK:
...

using Oracle.Cloud.Mobile.Notifications;
using Windows.Networking.PushNotifications;

namespace MyWindowsApp
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            //
            // First login to MCS
            //
            var loginDialog = new LoginDialog();
            loginDialog.ShowAsync().ContinueWith((task) => RegisterForNotificationsAsync());
        }

        private async Task RegisterForNotificationsAsync()
        {
            var backend = ((App)App.Current).Backend;

            // Register for Push Notifications
            PushNotificationChannel channel =
                await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

            await backend.GetService<Notifications>().RegisterForNotificationsAsync(channel.Uri);
        }		

        ...
    }
}

For details on requesting a channel URI and constructing the notification payload, see Windows Push Notification Services (WNS) overview on MSDN.

Next, register your mobile app with the associated MCS mobile backend, and enable notifications. For detailed instructions, see Registering an App as a Client in MCS in the Mobile Backends chapter.

After you’ve registered your app, it can receive notifications from a range of sources. For details and sample code, see Sending Notifications to and from Your App.

Sending Notifications to and from Your App

Once you’ve set up and registered your mobile app, you can start sending notifications and SMS messages.

You can also check the status of your notifications in the UI or using the Notifications API. For details, see Troubleshooting Notifications.

Testing Notifications from the MCS UI

MCS provides a notifications testing UI that allows you to send scheduled notifications to a defined set of recipients.
  1. Make sure you’re in the environment where you want to create the notification. Click icon to open the side menu to open the side menu and select Applications > Mobile Backends.
  2. On the Mobile Backends page, select the mobile backend that includes your mobile app and click Open.
  3. Click Notifications.
  4. On the Notifications page, click the Send icon.
  5. If your device isn’t registered yet, you can access the Device Registry by clicking Manage Devices.
    To register a device for SMS through the UI, you must have consent management disabled in the associated MCS client profile as described in Client Management. If you register a device for SMS through the UI and it fails, it’s probably a problem with your Syniverse Developer Community setup. Make sure you completed all the steps described in Syniverse: SMS Credentials.
  6. Enter the notification message you want to send in plain text or a JSON payload. If you enter JSON, it must conform to the notification provider’s requirements. If it is not valid JSON, it will be sent as a plain text message.
  7. Choose when to send the message.
    • To send the notification immediately, leave the default Now.
    • To schedule the notification for a later date and time, choose Later and select the date and time for the notification to be sent.
  8. Choose who to send the message to.
    • To send the notification to everyone in the mobile backend, leave the default All notifications-enabled mobile apps that use this mobile backend. A single mobile backend may contain more than one version of a mobile application, with implementations for different devices and networks. This option sends to all notification-enabled clients, regardless of the network or device.
    • To define a filter by user name, platform type, device ID, Facebook ID, or any combination, choose Filtered set of recipients. Under Match all of the following, select the filter type from the dropdown list:
      • Device ID: Send a notification to a single device ID or to multiple device IDs at the same time. The device ID is a unique number assigned to a mobile device during the device handshake. For SMS, the device ID is a phone number. In general, sending a notification to a device ID is useful for testing your application but not practical in bulk.

      • Platform: Send to all recipients running on iOS, Android, Windows or Web.

      • Provider: Send to all recipients receiving APNS, GCM, WNS or SMS notifications.

      • User: Send a notification to a single user or to a list of users.

      • Facebook Unique ID: Send a notification to a Facebook user, by ID.

      If the list of recipients gets too long, click the + button to add another filter and continue your entries there. Filters can be mixed and matched for additional selectivity.
  9. Click Send.
Once you click Send, you can monitor the status of your notifications in the History pane. For details, see Troubleshooting Notifications.
Cancelling a Scheduled Notification from the UI

The only notifications that can be cancelled are those that are scheduled for a future time.

To cancel a scheduled notification, go to the Scheduled tab in the History pane and click the X in the corner of the entry you want to remove. You will be prompted to confirm the cancellation.

Sending Notifications Using the Notifications API

You can send notifications to mobile devices from your apps using the Notifications API.

You can call Notifications REST API endpoints directly or use custom code in your mobile app. This section details the REST endpoints. For information on using custom code including examples and sample code, see Accessing the Notifications API from Custom Code in the Calling APIs from Custom Code chapter.

To register a device ID for notifications, you can use the MCS UI or the Notifications Device Registration API as described in Registering a Device ID Using REST.

The /mobile/system/notifications/notifications endpoint allows you to send notifications, cancel scheduled notifications, and check the status of sent notifications.

Note:

Calls to this endpoint must include these headers:
  • Authorization: If you’re using basic authentication, this header should include the name and password for a team member with the MobileEnvironment_Notification role, encoded in Base64. For OAuth, this header should include the access token. If you’re using OAuth, you must also be a team member with the MobileEnvironment_Notification role.

  • Oracle-Mobile-Backend-ID: If you’re using basic authentication, you must include this header. The mobile backend ID is listed on the Settings tab for the mobile backend. For OAuth, this information is included in the access token.

When you send a notification, you can specify any combination of the following for the payload: MCS uses the unified payload if it exists, then the template, then the message, in that order.

To send notifications to specific recipients, add an argument after the content of the payload:

  • To send to a user or a list of users, add the users argument. A user can be defined by firstname:lastname or email address. Multiple users are listed as tokens in an array, and there’s no limit on the number. For example:
    -d '{"message": "Hi! Our storewide sale is tomorrow.", "users": ["bob@acme.com", "sjones@xyz.net", "banana@peelme.com"]}' 
  • To send to everyone on the same mobile platform, add the platform (IOS, ANDROID, WINDOWS or WEB). For example:
    -d '{"message": "Hi! Our storewide sale is tomorrow.", "platform": "IOS"}'
    
  • To send to a specific notification provider, add the provider (APNS, GCM, WNS or SYNIVERSE). For example:
    -d '{"message": "Hi! Our storewide sale is tomorrow.", "provider": "APNS"}'
    
  • To send to a specific device ID or a list of device IDs, add the notificationTokens argument. Multiple IDs are listed as tokens in an array, and there’s no limit on the number. For example:
    -d '{"message": "Test of notifications feature.", "notificationTokens": ["2DD2D2-D2DDG44GD-GDGSDFZS3-3-3DFZSDFDS"]}'
To schedule a notification for a future date and time, add the sendOn argument. For example:
-d '{"message": "Come to our discount sale today!", "sendOn": "2015-06-15T6:00Z"}' 

For further details, including HTTP response status codes and full schemas for the request and response bodies, see the REST APIs for Oracle Mobile Cloud Service.

Registering a Device ID Using REST

The Notifications Device Registration API lets you register the device ID of your mobile app, which can then be used as a recipient address for sending notifications. This API can also associate a user with the device ID, so the user name can also be used as a target for notifications.

You can register a device ID (notificationToken) directly and send notifications directly to that ID. You can also use this API to associate any user with the device ID.

The Notifications Device Registration API includes the following endpoints:
  • POST /mobile/platform/devices/register

  • POST /mobile/platform/devices/deregister

When you register a device, include these parameters:
  • The mobileClient parameter identifies the client in the mobile backend with three properties:
    • id: The Application ID assigned by the Google or Apple app store. (This is different from the "App-Key" used by MCS.)

    • version: The version of the mobile client that will receive the notifications, currently 1.0.

    • platform: "IOS" or "ANDROID" or "WINDOWS" or "WEB" (all caps)

  • The notificationProvider parameter defines the service the notificationToken is used for: "APNS" or "GCS" or "WNS" or "SYNIVERSE"

  • The notificationToken parameter defines the token needed by the notification service for sending calls. This token uniquely identifies the specific instance of a mobile app associated with a specific device, and is used to ensure that notifications are sent to the correct recipient. Encode in hexadecimal if necessary.

  • The optional user parameter associates the device ID with the user name provided. If the user parameter isn’t included, the device ID is associated with the user who is logged in during the registration call.

    Note:

    To specify a different user name, the logged in user must be a team member with the MobileEnvironment_Notifications role. Keep in mind that registering a user name this way doesn’t validate the entry in the MCS Device Registry. If this results in duplicate user names, notifications could be sent to multiple users. It’s up to the app to ensure that user names are unique if that’s a requirement.
This example registers a device with the device ID MyAppToken:
curl -v 
  -H "Authorization: Basic VGVzdE1vYmlsZVVzZXIyYzE4YWRiZjMyMDg0ZWZkOWQyODM0NjA1OGNmExampleAuthString="  
  -H "Oracle-Mobile-Backend-ID: 7cf06198-053e-4311-8186-cae145900d59" 
  -H "Content-Type:application/json" 
  -d '{"mobileClient": {"id": "MyClientac3d8baf1aa348b48d80e9b7fd026067","version": "1.0","platform": "IOS"},"notificationProvider":"APNS","notificationToken":"03767dea-29ac-4440-b4f6-75a755845ade","user":"JoeSmith"}' 
     http://www.fixitfast.com:8080/mobile/platform/devices/register
If the REST operation to register the device is successful, you can expect to get a response something like this:
Connected to fixitfast.com port (10.176.45.198) port 8080 (#0)
Server auth using Basic with user 'lucy'
POST /mobile/platform/devices/register/
Authorization: Basic VGVzdE1vYmlsZVVzZXIyYzE4YWRiZjMyMDg0ZWZkOWQyODM0NjA1OGNmExampleAuthString=
User-Agent: curl/7.33.0
Host: fixitfast.com:8080
Accept: application/json
Content-Type: application/json 
Oracle-Mobile-Backend-ID: 7cf06198-053e-4311-8186-cae145900d59
Content-Length: 32
upload completely sent off: 32 out of 32 bytes
HTTP/1.1 201 Created
The response includes a JSON payload that contains the device ID for the registered device.
{
  "id": "7cf06198-053e-4311-8186-cae145900d59",
  "user": "JoeSmith",
  "notificationProvider":"APNS",
  "notificationToken":"03767dea-29ac-4440-b4f6-75a755845ade",
  "mobileClient": {"id": "MyClientac3d8baf1aa348b48d80e9b7fd026067","version": "1.0","platform": "IOS"},
  "modifiedOn": "2016-05-25T14:58:16.373Z"
}
Sending a Text Message Notification with REST

The example below uses the Notifications REST API to send a simple notification to everyone in the mobile backend. As noted above, the name and password sent in the Authorization header must be a team member with the necessary permissions.

curl -X POST 
  -H "Authorization: basic bWNzOldlbGNvbWUxKg==" 
  -H "Accept: application/json" 
  -H "Content-Type: application/json; charset=UTF-8" 
  -H "Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d" 
  -d '{"message": "Hi! Our storewide sale is tomorrow."}' 
    http://www.FixItFast.com:8080/mobile/system/notifications/notifications/

If the notification is sent successfully, the response might look like the example below. The body will be the JSON for the created notification.

Connected to FixItFast.com port (10.176.45.198) port 8080 (#0)
Server auth using Basic with user 'lucy'
POST /mobile/system/notifications/notifications/ HTTP/1.1
Authorization: Basic bWNzOldlbGNvbWUxKg==
User-Agent: curl/7.33.0
Host: newclothes.com:8080
Accept: application/json
Content-Type: application/json; charset=UTF-8
Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d
HTTP/1.1 201 Created

You could also get a status code of 400 (bad request) or 401 (unauthorized).

Sending a Notification Using a Unified Payload with REST
A unified payload allows you to specify a different payload for each supported notification provider using Notifications REST API. One or more of the following can be defined under the services property:
  • The apns payload must conform to APNS requirements.

  • The gcm payload can contain arbitrary JSON properties.

  • The wns payload property must contain a well-formed WNS payload.

  • The syniverse payload property should contain the string to send as a SMS message.

Note:

The payload template allows you to send provider-specific payloads without defining the code. For details, see Sending a Notification Using a Payload Template with REST.
The following is a simple example that defines a payload for each notification provider.
curl -X POST 
  -H "Authorization: basic bWNzOldlbGNvbWUxKg==" 
  -H "Accept: application/json" 
  -H "Content-Type: application/json; charset=UTF-8" 
  -H "Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d" 
  -d '{"payload": {
        "services": {
            "apns": {
                "aps": {
                    "alert": "This is my alert message"
                }
            },
            "gcm": {
                "mcs": {
                    "alert": {
                        "body": "This is my alert message"
                    }
                }
            },
            "syniverse": {
                "mcs": {
                    "alert": {
                        "body": "This is my alert message"
                    }
                }
            },
            "wns": {
                "toast": {
                    "visual": {
                        "binding": {
                            "template": "ToastText01",
                            "text": ["This is my alert message"]
        		             }
            					}
					        }
          	  }
			     }
		    }
		}' 
  http://www.FixItFast.com:8080/mobile/system/notifications/notifications/
Sending a Notification Using a Payload Template with REST
When you use a payload template with the Notifications REST API, MCS uses the content you enter to create a driver-specific payload for each supported notification provider. The default payload template includes the following optional parameters.
Parameter Description Data Type Example
title The alert title. If a title is specified, the body parameter is also required. string "Sale On Now!"
body The alert body.

If only a body is specified, the content is used as the value for the alert property in the APNS and FCM payloads.

string "50% off until Saturday"
badge A number to badge the notification with.

Android applications don’t support badging but the number is still passed in the FCM driver payload, so the value can be used by the Android application in other app-specific ways.

number 43
sound The sound file to play with the notification. Only .wav format is supported by both APNS and WNS.
  • For APNS, the file must be in the app bundle.

  • For WNS, the file must be in the app package (MCS adds the "ms-appx:///" prefix automatically).

  • For FCM, the file can be anywhere.

string "alert.wav"
custom Any required custom data. object
{
  "acme1": "value1",
  "acme2": ["value2", "value3"]
}

The example below shows a notification that includes all five parameters and the resulting driver-specific payloads.

The notification specifies the default template and defines the parameters:
curl -X POST 
  -H "Authorization: basic bWNzOldlbGNvbWUxKg==" 
  -H "Accept: application/json" 
  -H "Content-Type: application/json; charset=UTF-8" 
  -H "Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d" 
  -d '{"template": {
	    	"name": "#default",
	    	"parameters": {
	    		"title": "Sale On Now!",
	    		"body": "50% off until Saturday",
	    		"badge": 5,
	    		"sound": "alarm.wav",
	    		"custom": {
	    			"acme1": "value1",
	    			"acme2": ["value2", "value3"]
		      	}
	  		  }
			  }
			}' 
  http://www.FixItFast.com:8080/mobile/system/notifications/notifications/
In this case, the APNS and FCM driver payloads are identical aside from the name. As noted above, Android apps don’t support badging, so your app can use the badge value in other ways.
APNS driver payload:
{
  "aps": {
    "alert": {
      "title": "Sale On Now!",
      "body": "50% off until Saturday"
    },
    "badge": 43,
    "sound": "alarm.wav",
  },
  "acme1": "value1",
  "acme2": ["value2", "value3"]
}
FCM driver payload:
{
  "mcs": {
    "alert": {
      "title": "Sale On Now!",
      "body": "50% off until Saturday"
    },
    "badge": 43,
    "sound": "alarm.wav" 
  },
  "acme1": "value1",
  "acme2": ["value2", "value3"]
}
For the WNS driver payload, MCS sends three notifications:
  • A toast notification for the alert and sound

  • A badge notification

  • A raw notification for the custom parameters

{
  "toast": {
    "visual": {
      "binding": {
        "template": "ToastText02",
        "text": ["Sale on Now!", "50% off"]
      }
    },
    "audio": {
      "src": "ms-appx:///alarm.wav"
  },
  "badge": {
   "value": "43"
  },
  "raw": {
    "acme1": "value1",
    "acme2": ["value2", "value3"]
  }
}
Cancelling Scheduled Notifications with REST
To cancel a scheduled notification, send DELETE to /mobile/system/notifications/notifications/{id} with the ID assigned to the notification you want to cancel. For this example, the notification ID is 113455.
curl -X DELETE 
  -H "Authorization: Basic bWNzOldlbGNvbWUxKg=="
  -H "Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d" 
  -H "Accept: application/json" 
  -H "Content-Type: application/json; charset=UTF-8" 
    http://www.fixitfast.com:8080/mobile/system/notifications/notifications/113455

Troubleshooting Notifications

Sending a notification is an asynchronous process. Once you send a notification, it can sit for minutes, hours, or maybe even days on an Apple, Google or Microsoft server before it gets delivered to the mobile device. Even if a notification can’t be delivered, there might be no error message returned. MCS has no control over a notification once it gets sent, but these are some common notification problems:

  • A secure certificate is missing, expired, or not located in the right place.

  • The network credentials for the device don't match the credentials registered with MCS.

  • A security identifier used in your code doesn’t match the identifier registered with Google, Apple or Windows, or match what’s defined in your Android manifest or iOS Xcode project.

  • The wrong identifier has been entered into a form. For example, when you register for notifications in a mobile backend and it asks you for an API Key, you entered the application key instead.

  • An APNS mismatch between production/development flag and certificate, for example uploading a production certificate but configuring the client saying it's a development certificate.

  • In FCM and GCM, the wrong API key or Project Number/Sender ID means the user might have disabled notifications on their device.

Checking Notification Status in the UI

Check the History pane, accessible from the Notifications page for your mobile backend, to find out if your notifications were successfully sent.

Scheduled notifications are displayed in the Scheduled tab. To see a list of sent notifications, click the Sent tab. If you don’t see the notifications you expect, click Check for Updates.

The status you see in the History pane reflects the success rate of the notifications that have been sent. You can quickly tell the status of each notification in the History pane by the color in the left column:

  • Green means that more than 70% of individual notifications in the batch were accepted by the Apple and/or Google networks.

  • Yellow means that less than 70% of individual notifications in the batch were accepted.

  • Red means that the batch failed to send successfully from MCS. In most cases, there is a configuration error that needs to be fixed. See Troubleshooting Notifications.

  • Blue means a batch of notifications is currently being sent. In most cases, a Blue indicator appears for only a few moments.

Given the large the number of recipients sent to a popular mobile application, there will never be 100% success. For example, if a notification is directed to a user that has recently lost her phone, the Apple or Google network won’t accept the notification for delivery to the device. The default warning threshold is 70%, but you can change it in the Notifications_DeviceCountWarningThreshold environment policy.

The Device Manager, also accessible from the Notifications page for your mobile backend, lists all registered devices for the mobile backend with their device IDs/notification tokens. If you don’t see your device, the network provider might have specified that the device ID/notification token is invalid and should be deregistered. Also, if a device hasn’t been reregistered in 60 days, it will be removed from the registry. You can click Clear Registry to remove all registered devices from a mobile backend to facilitate troubleshooting.

You can always look at the MCS logs to see if more information about a notification or batch of notifications is available. Click icon to open the side menu to open the side menu and select Administration > Logs. For details on the diagnostics tools available through MCS, see Diagnostics.

Checking Notification Status with the Notifications REST API

You can use the Notifications API to check the status of notifications.
Send GET to mobile/system/notifications/notifications with the ID of the notification or using the status= query parameter. You can check for any notification status: New, Scheduled, Sending, Error, Warning, or Sent. (The notification must have been successfully sent.)
The example below checks for scheduled notifications.
curl -i
-X GET 
-u team.user@example.com:Welcome1!
-H "Oracle-Mobile-Backend-ID: ABCD9278-091f-41aa-9cb2-184bd0586fce"
http://fif.cloud.oracle.com/mobile/system/notifications/notifications/?status=Scheduled
If the query is successful, the response will be JSON listing the first 1000 notifications found. You can specify a range using limit and offset parameters, for example, limit=100&offset=400 would return notifications 400-499.
{
  "items": [
   {                     
    "id": 1234,                     
    "tag": "Marketing",                     
    "message": "This is the alert message.",
    "status": "Sent",
    "notificationTokens": ["APNSdeviceToken"],
    "createdOn": "2014-04-02T12:34:56.789Z",
    "platformCounts": [
     {
       "platform": "IOS",
       "deviceCount": 1,
       "successCount": 1
      }
  ],
  "links": [
   {
     "rel": "canonical",
     "href": "/notifications/1234"
   },
   {
     "rel": "self",
     "href": "/notifications/1234"
   }
  ]
 },
 {
   "id": 1235,
   "tag": "System",
   "message": "Update required.",
   "status": "Sent",
   "processedOn": "2014-04-01T12:34:56.789Z",
   "notificationTokens": ["APNSdeviceToken"],
   "platformCounts": [                       
    {
     "platform": "IOS",
     "deviceCount": 1,
     "successCount": 1
    }
   ],
   "createdOn": "2014-04-03T58:24:12.345Z",
   "links": [
    {
     "rel": "canonical",
     "href": "/notifications/1235"
    },
    {
     "rel": "self",
     "href": "/notifications/1235"                       
    }
   ]
  }
 ],
  "hasMore": false
  "links": [
   {
    "rel": "canonical",
    "href": "/notifications?offset=0&limit=2"
   },
   {
    "rel": "self",
    "href": "/notifications?offset=0&limit=1000"
   }
  ]
}