Skip to Content

SAP HANA Cloud Platform, Mobile Service for Development and Operations


1 Push Notification Overview


1.1 Introduction

In today’s mobile-centric world, push notifications are a ubiquitous occurrence in our daily lives. They provide up-to-date relevant information in a simple and effective format, encouraging engagement and increasing involvement from users. It is no doubt that any organization would be wise to leverage the advantage of push notifications in their enterprise applications. SAP HANA Cloud platform, mobile service for development and operations provides the functionality to seamlessly integrate native push notifications end-to-end, with minimum time and effort needed to develop push enabled mobile enterprise applications.


1.2 Overview

SAP HANA Cloud platform, mobile service for development and operations uses the native notification mechanisms APNS , GCM/FCM and WNS provided by the individual device platforms for iOS , Android and Windows respectively , to forward push notifications it receives from notification provides ( back-end systems) to mobile devices. Back-end systems can use either the Push REST service API ( recommended) or HTTP header based API, both exposed by the Mobile service for dev & ops to notify it about any push messages. In the former case , the notification data is sent as a json payload and in the latter, the notification data is sent as generic HTTP headers or as device platform-specific HTTP headers.


1.2.1 End-to-end flow

Let’s have a look at how push notification works from the end user perspective.

  • In a typical landscape, mobile service for dev & ops and push providers are located in the internet while all the SAP specific systems are protected by the firewall.
  • The device registers with a Push Provider ( such as an APNS , GCM or WNS server ).Each Push Provider shall provide the device with a notification token ( APNS) , canonical ID ( GCM) or Application Secrets and Package SID ( WNS)
  • The device sends the notification token (canonical ID or Package SID based on the device platform) obtained from the push provider to the mobile service for dev & ops, which in turn adds and stores the token in the existing user on-boarding information. Now the mobile service for dev & ops knows how to talk to the platform specific Push Provider server when it needs to send the message to your device.
  • In the case of an ABAP based notification provider, the device “subscribes” to business event. Technically it subscribes to the OData collection for which you want to get notified when Create/Update/Delete occurs. Once the subscription step is done, the backend keeps track of which application connection ID subscribes which OData collections.
  • If any the business event happens, the backend triggers the notification via SAP Gateway Hub to the mobile service for dev &ops. As SAP Gateway knows the firewall proxy configuration, the SAP HANA Cloud Connector is not used during this step. The notification is forwarded by the mobile service for dev & ops to the push providers for the specific device platform , which in turn push it to the devices.


1.2.2 Fiori Launchpad Notification Support

SAP HANA Cloud platform, mobile service for development and operations also supports Fiori Launchpad notification functionalites such as capability based push and badge handling on mobile devices for fiori applications running on the SAP Fiori Client.


1.2.3 Device Platforms and Versions

The SAP HANA Cloud platform, mobile service for development and operations (alias mobile service for dev & ops) uses the native notification services provided by individual device platforms to send notifications. The following platforms are supported via their respective notification services.

Platform Notification Service
iOS Apple Push Notification Service ( APNS)
Android

Google Cloud Messaging ( GCM)

Firebase Cloud Messaging ( FCM)

Windows Windows Notification Service ( WNS)

Platform  Supported Versions
iOS  8.x – 10.x
Android 4.1.3 -6.0
Windows Windows 8.1, Windows Phone 8.1, Windows 10

 

1.2.4 Application types

As with as the platform services, push notification services are exposed by the mobile service for dev & ops, through REST API. It can be easily accessed through the SMP SDK or through REST services from any development platform.
SMP SDK provides APIs to enable push for the following application types:

  • Native (iOS, Android, Win)
  • Hybrid (Kapsel)
  • SAP Fiori Client – Fiori Launchpad Notification Support for Custom & App Store versions


2 Configuring PUSH settings in the Cockpit


2.1 Configuring Notification role

In order to send push notifications to an application, you must have ‘Notification User’ privilege assigned to your user ID in SAP HCP mobile service for dev & ops. This must be done in the mobile services cockpit.

By default, HANA Cloud Platform uses SAP Cloud ID service to authenticate users against SAP user accounts. Assign the ‘Notification User’ role to the SAP user ID to be able to send the push notification to the device.

  • Login to SAP HANA Cloud Platform Cockpit.
  • Find the Provider and tenant account you want to use. (Need Administrator Permission for the tenant.)
  • From the subscribed Java Applications of that tenant, find and select HCPms Java application
  • In the Left pane, find the “Roles” menu, then add users for “Notification User” role.
  • Then that user will be able to send notification to devices.


2.2 Cockpit Settings for iOS

The APNS certificate needs to be uploaded to the PUSH tab of the application in the cockpit to enable APNS notifications for the application . For details on how to get an APNS certificate, please refer to section 3.1.2 . To upload the certificate, follow the steps below:

If using previous cockpit:

  • Log on HCPms server, find the corresponding application and click Configure
  • In PUSH tab -> Apple section, choose Sandbox in the APNS Endpoint column and upload the Certificate file and password.

If using new cockpit:

  • Log on HCPms server, find the corresponding application and click it
  • Click Push Notification from Assigned Features
  • In Configuration tab -> Apple section, choose Sandbox in the APNS Endpoint column and upload the Certificate file and password.


2.3 Cockpit Settings for Android

The senderID needs to be uploaded to the PUSH tab of the application in the cockpit to enable GCM notifications for the application . For details on how to get the sender ID, please refer to section 3.2.2 Get sender ID and API key. To upload the senderID, follow the steps below:
If using previous cockpit:

  • Log on SMP3/HCPms server, find the corresponding application and click Configure
  • In PUSH tab -> Android section, configure the Sender ID and API Key.

If using new cockpit:

  • Log on SMP3/HCPms server, find the corresponding application and click it
  • Click Push Notification from Assigned Features
  • In Configuration tab -> Android section, configure the Sender ID and API Key.


2.4 Cockpit Settings for Windows

The Client Secret and Package SID needs to be configured in the PUSH tab of the application in the cockpit to enable WNS notifications for the application . For details on how to get Package SID and Client Secret, please refer section 3.4.1 and 3.4.2 To configure them in the cockpit, follow the steps below:
If using previous cockpit:

  • Log on SMP3/HCPms server, find the corresponding application and click Configure
  • In PUSH tab -> WNS section, configure the Package SID and Client Secret.

If using new cockpit:

  • Log on SMP3/HCPms server, find the corresponding application and click Configure
  • Click Push Notification from Assigned Features
  • In Configuration tab -> WNS section, configure the Package SID and Client Secret.


3 Configuring clients for PUSH notifications


3.1 Configuring iOS Native Clients

3.1.1 Prerequisites

  • MacBook – OS X version 10.12.x or higher
  • Xcode 8.x or higher with iOS device on iOS 9 or higher
  • Required certificate downloaded from iOS provisioning portal: https://developer.apple.com/
  • Required provisioning profile downloaded from iOS provisioning portal and imported to Xcode
  • Knowledge of developing an SMP SDK based iOS native project.
  • Account on SAP HANA Cloud Platform, mobile services for dev & ops.
  • Valid mobile platform Administrator user credentials
  • Application Configuration is created on the mobile platform server
  • REST client (e.g. Firefox REST client or Postman REST client for Chrome)
  • Additional information on the prerequisites for Apple Push Notification Services can be found on the Apple Developer site: https://developer.apple.com/notifications/

3.1.2 Provision the iOS device for APNS

Push notification messages for the iOS platform cannot be tested on a simulator. The first step to receiving push notifications your iOS device is to obtain an APNS enabled certificate and corresponding provisioning profile from the Apple Developer portal. The following section will give a complete step-by-step guide on how to accomplish this task.

    • Create a unique application ID for your project. Go to App Settings -> General and change Bundle Identifier to something unique as shown below.
    • Next, you need to create the same App ID in your developer account and enable push notification entitlement. Xcode has a simple way to accomplish this. To be able to do this in Xcode, the ‘Automatically manage signing’ option must be on. Go to App Settings -> Capabilities and flip the switch for Push Notifications to On. After some loading, it should look like this:
    • Behind the scenes, this creates the App ID in your member center if it doesn’t exist already, then adds the push notifications entitlement to it. You can log in and verify this:
    • In your member center, go to Certificates, Identifiers & Profiles -> Identifiers -> App IDs and find the App ID for your app. Under Application Services, Push Notifications should be Configurable:
    • Click Edit and scroll down to Push Notifications. In Development SSL Certificate, click Create Certificate… and follow the steps to create a CSR. Once you have your CSR, click continue and Generate your certificate using the CSR.
    • Finally, download the certificate and double click it, which should add it to your Keychain, paired with a private key:
      Back in the member center, your App ID should now have push notifications enabled for development:
    • There is one last thing you need before you close Keychain Access. Right-click on your new push certificate and choose Export. Save it to Desktop as a .p12 file.You will be prompted to enter a password for the p12. You can either leave this blank or enter a password of your choosing. You’ll then need to enter your log-in password to permit the export.

3.1.3 Modifying the client application

This section describes how to modify an existing SMP SDK based native iOS client application to receive push notifications. The only part of the push implementation code that is specific to mobile services for dev & ops is the registering of the APNS token with the mobile service, as described in step 5. All other steps are generic APNS push implementation as required by Apple.

  1. Ask the user for permission to receive push notifications by calling the registerUserNotificationSettings: method of UIApplication.>
  2. Call the registerForRemoteNotifications: method of UIApplication , to tell the OS that the application wants to receive push notifications.
    Below is some sample code to be added to application: didFinishLaunchingWithOptions: method of the AppDelegate. The call to registerForRemoteNotifications: tells the OS that the app wants to receive push notifications. When the app starts and registers for push notifications, it should show a standard message for push enabled apps stating that the app “…Would Like To Send You Push Notifications…” with the option to confirm with “OK” or “Don’t Allow”.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        UIUserNotificationType types = (UIUserNotificationType)|        (UIUserNotificationTypeBadge |  
        UIUserNotificationTypeSound| UIUserNotificationTypeAlert);
        
        UIUserNotificationSettings *pushSettings =  [UIUserNotificationSettings settingsForTypes:types  
        categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:  pushSettings];
    
        // Register for notifications
        [application registerForRemoteNotifications];
    }
    
  3. Implement the application:didRegisterForRemoteNotificationsWithDeviceToken: method of UIApplicationDelegate to receive the unique device token generated by the push service.The code sample below retrieves the token and saves it for future use.
    - (void)application:(UIApplication*)applicationdidRegisterForRemoteNotificationsWithDeviceToken:
         (NSData*)deviceToken
    {
        NSLog(@"My token is: %@", deviceToken);
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:deviceToken forKey:@"apnsDeviceToken"];
        [defaults synchronize];
    }
    
  4. Implement the application:didFailToRegisterForRemoteNotificationsWithError: method of UIApplicationDelegate (iOS) or NSApplicationDelegate (OS X) to receive an error if the registration failed.
    In the sample below ,the error information is simply being written to the output log

    - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
    {    
    	NSLog(@"Failed to get token, error: %@", error);
    }
    
  5. Pass the device token to the mobile service for dev & ops .
    The SAP Mobile Platform server serves as the notification server that receives the notification from the backend and forwards it to the APNS server, which ultimately sends the notification to the device. Before the mobile platform server can serve in this mediation role, the app must register its APNS device token with the mobile platform server using its application connection ID (APPCID).
    An appropriate time to make this call to register the token is right after successful user onboarding takes place in the method call logonFinishedWirhError:. Method logonFinishedWithError: is the finish/fail handler for the MAF logon process. The call to register the APNS token is simply added in the finish handler once the user is successfully onboarded.
    These lines of code simply retrieves the APNS token from NSUserDefaults and makes a call to a local method that implements the actual call to register the APNS token with the mobile platform. This method implementation takes place in the next step. The original APNS device token retrieved from NSUserDefaults, is in the form of an NSData object. Getting its description results in an NSString object containing whitespace and beginning/ending angle brackets. For example, the resulting token might look like this:
    “<407b75b0 4d363ab1 2ab91eae 49cb981c c7cf59a5 e94ebf9f 3c890cd3 4a4349ad>”
    The setConfigProperty: method from class SMPAppSettings takes in an NSDictionary object containing properties to set for the application configuration corresponding to the passed in application connection ID. The angle brackets and whitespace must be stripped from the token value prior to adding it to the NSDictionary object and then used by the setConfigProperty: method.The rest of the code simply provides some information on the success/failure of registering the token with the mobile platform.
    Now the app is ready for receive push notifications from the mobile platform server.

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [[defaults objectForKey:@"apnsDeviceToken"] description];
    if([token length] > 0) {
        NSString *token = [[[[[defaults objectForKey:@"apnsDeviceToken"] description]
                     stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""]
                   stringByReplacingOccurrencesOfString: @" " withString: @""];
        
    NSError *setConfigTokenError = nil;
    NSDictionary *props = @{@"d:ApnsDeviceToken": token};
    [appSettings setConfigProperty:props error:&setConfigTokenError];
        
    if (!setConfigTokenError) {
        NSString *successMessage = [NSString stringWithFormat:@"APNS device token (%@) has been registered for CID (%@).", token, data.applicationConnectionId];
        NSLog(@"%@",successMessage);
    } else {
        NSString *errorMessage = [NSString stringWithFormat:@"Registering APNS device token(%@) for CID(%@) failed with error: %@.", token, data.applicationConnectionId, [setConfigTokenError localizedDescription]];
        NSLog(@"%@",errorMessage);
    }
    }
    
  6. In the method application: didReceiveRemoteNotification: enter code to retrieve the notification message from the ‘userinfo’ structure. This method handles the case when a notification is received while the app is open. Below is a sample, which parses the userInfo NSDictionary object passed in.
    NSLog(@"Received notification: %@", userInfo);
        
    NSString *message = nil;
    NSString *dataMessage = nil;
    NSString *alertMessage = nil;
        
    id dataMsg = [userInfo objectForKey:@"data"];
    if ([dataMsg isKindOfClass:[NSString class]]) {
        dataMessage = dataMsg;
    }
        
    id alertMsg = [userInfo objectForKey:@"aps"];
    if ([alertMsg isKindOfClass:[NSString class]]) {
        alertMessage = alertMsg;
    } else if ([alertMsg isKindOfClass:[NSDictionary class]]) {
        alertMessage = [alertMsg objectForKey:@"alert"];
    }
        
    message = [NSString stringWithFormat:@"Alert: %@\nData: %@", alertMessage, dataMessage];
                [Utilities showAlertWithTitle:@"TravelAgencies Push Notification" andMessage:message];
    
  7. Build and run the application. The first time you launch the application, you should see a prompt with the standard message for push enabled apps stating that the app “…Would Like To Send You Push Notifications…” with the option to confirm with “OK” or “Don’t Allow”. Select OK.
  8. In the OS Settings -> Notifications on your device, you should see your application listed.


3.2 Configuring Android Native Clients

3.2.1 Prerequisites

  • Android Studio
  • Register on Google API website with Google account to get sender ID and API key
  • Account on SAP HANA Cloud Platform, mobile services for dev & ops.
  • Valid mobile platform Administrator user credentials
  • Application Configuration is created on the mobile platform server
  • REST client (e.g. Firefox REST client or Postman REST client for Chrome)
  • Additional information on the prerequisites for Android Push Notification Services can be found on the Google Developer site: https://developers.google.com/cloud-messaging/http-server-ref

3.2.2 Get sender ID and API key

3.2.3 Set up Google Play services

  • Install the Google Play services SDK
    To implement a GCM (Google Cloud Messaging) client, you need to use the GCM APIs. To use this API, you must set up your project to use the Google Play services SDK

    1. Open Android Studio
    2. On the top menu, click on the Android SDK manager icon to open it
    3. The Android SDK manager will open
    4. Select Google Play services
    5. Click Apply
  • Import Google Play services
    1. Open the build.gradle file inside your application module directory
    2. Add a new build rule under dependencies for the latest version of play-services. Be sure you update this version number each time Google Play services is updated.
      compile 'com.google.android.gms:play-services-gcm:9.4.0'
    3. Save the changes and click Sync Project with Gradle Files in the toolbar

3.2.4 Implement Push Notification APIs in client app

A GCM client is an android app that has GCM enabled and can receive GCM messages. This section uses the sample code provided by the android developer website, click on this link to get more details
https://developers.google.com/cloud-messaging/android/client

You can choose any android project to enable GCM. If you are using your own project, remember to import SMP OData libraries.
If you don’t have an existing android project, you can create an android project from scratch with MAF Logon.

  1. Add GCM elements to AndroidManifest.xml
    • Open the AndroidManifest.xml file and add the following permissions after android.permission.INTERNET. These permissions are needed to enable GCM
    • After the application tag, add the following meta-data tag. It’s required for applications using the Google Play services
    • Define the GCM receiver. WakefulBroadcastReceiver that will receive intents from GCM services and hand them to the custom IntentService.
  2. Create GCM Broadcast receiver
    Create a receiver that extends WakefulBroadcastReceiver class. This receiver will receive intents from GCM services and hand them to GcmIntentService.
    The onReceive method code sample:

    public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    
       @Override
       public void onReceive(Context context, Intent intent) {
              // Explicitly specify that GcmIntentService will handle the intent.
         ComponentName comp = new ComponentName(context.getPackageName(),
                 GcmIntentService.class.getName());
         // Start the service, keeping the device awake while it is launching.
         startWakefulService(context, (intent.setComponent(comp)));
         setResultCode(Activity.RESULT_OK);
       }
    }
    
  3. Create GCM Intent Service
    This class processes the GCM message based on message type, and posts the result in a notification.
    Sample source code:

    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);
    
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MAFLogonActivity.class), 0);
    
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
         .setSmallIcon(com.sap.dcode.agency.R.drawable.ic_stat_gcm)
        .setContentTitle("GCM Notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);
    
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    
  4. Create GenericException class
    The GCM client app will use the GenericException to notify the user that an error has occurred.

    public class GcmException extends Exception {
    
       private static final long serialVersionUID = 1L;
    
       public GcmException(String errorMessage) {
            super(errorMessage);
        }
    
       public GcmException(Throwable throwable) {
            super(throwable);
        }
    
    }                 
    
  5. Create GcmManager class
    Most of the source code included in this class in the sample code provided by the android developer website. However, there are some additional steps to enable this GCM client for push notifications on SMP or HCPms.

    • Method registerInBackground gets the SENDER ID from the application configuration. This information is very important to get the registration id from the Gcm Server.
    • Method sendRegistrationIdToBackend updates the application configuration on the mobile services with the GCM registration ID. This will enable the GCM client to receive push notifications.
      	    public static void registerInBackground() {
              new AsyncTask<Void, Void, String>() {
                  @Override
                  protected String doInBackground(Void... params) {
                      String msg = "";
                      try {
                          GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
      
                          com.sap.maf.tools.logon.core.reg.AppSettings applicationSettings = LogonCore.getInstance().getAppSettings(); 
                         String senderID = (String)applicationSettings.getSettingProperties().get(com.sap.maf.tools.logon.core.reg.AppSettings.ANDROID_GCM_SENDER_ID/*PROPERTY_GCM_REGISTRATION_ID*/).getValue();
                          Log.d("SenderID", senderID);
                          
                          regid = gcm.register(senderID);
                          //regid = gcm.register("824532503871");
                          msg = "Device registered, registration ID=" + regid;
      
                          // You should send the registration ID to your server over HTTP, so it
                          // can use GCM/HTTP or CCS to send messages to your app.
                          sendRegistrationIdToBackend();
                          
                          
                         // Persist the regID - no need to register again.
                          storeRegistrationId(context, regid);
                          Log.d("GCMManager","GCM registration ID-->"+regid);
                      } catch (Exception ex) {
                          msg = "Error :" + ex.getMessage();
                          Log.e(TAG, "registerInBackground", ex);
                  }
                      return msg;
                  }
      
                  @Override
                  protected void onPostExecute(String msg) {
                    Toast.makeText(context, msg,
                          Toast.LENGTH_LONG).show();
                  }
              }.execute(null, null, null);
          }
          
       
        
          /**
           * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
           * messages to your app. Not needed for this demo since the device sends upstream messages
           * to a server that echoes back the message using the 'from' address in the message.
           * @throws GcmException 
           */
          private static void sendRegistrationIdToBackend() throws GcmException {
             
             try {
                com.sap.maf.tools.logon.core.reg.AppSettings applicationSettings = LogonCore.getInstance().getAppSettings(); 
                 String currentRegistartionId = (String)applicationSettings.getSettingProperties().get(com.sap.maf.tools.logon.core.reg.AppSettings.ANDROID_GCM_REGISTRATION_ID/*PROPERTY_GCM_REGISTRATION_ID*/).getValue();
                 
                 HashMap<String, AppSettingsProperty> writableProperties = applicationSettings.getWritableSettings();
                 writableProperties.get(com.sap.maf.tools.logon.core.reg.AppSettings.ANDROID_GCM_REGISTRATION_ID/*PROPERTY_GCM_REGISTRATION_ID*/).setValue(regid);
                 applicationSettings.updateAppSettings(writableProperties);
                 applicationSettings.downloadAppSettings();
                 String updatedRegistartionId = (String)applicationSettings.getSettingProperties().get("AndroidGcmRegistrationId"/*PROPERTY_GCM_REGISTRATION_ID*/).getValue();
             }
             catch (LogonCoreException le) {
                Log.e(TAG, "sendRegistrationIdToBackendOld", le);
             }
             
          }
          
      }
      
  6. Modify MainActivity
    Go to the onCreate method and add the following code to start the registration with GGM service and with SMP

    public class MainActivity extends Activity {
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          
          //Initialize MainFragment
          Fragment fragment = Fragment.instantiate(this, MainFragment.class.getName());
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(android.R.id.content, fragment);
            fragmentTransaction.commit();
            
            // Check device for Play Services APK. If check succeeds, 
                   // proceed with GCM registration.
                   Context context = getApplicationContext();
                     if (GcmManager.checkPlayServices(context)) {
                        String regid = GcmManager.getRegistrationId(context);
                        GcmManager.registerInBackground();
    
                     } else {
                        Log.d("MainActivity","No valid Google Play Services APK found.");
                     }
       }
    }               
    

    The application is now ready for receive push notifications from the mobile platform server.
    Build and run the application. You should see a prompt with message whether push registration is successful or not. If push registration is successful, it will display “Device registered, registration ID=xxxxx”, if push registration failed, it will display “Error : xxxxx”


3.3 Configuring Windows Native Clients

Windows 10 Desktop, Windows 10 Tablet Clients and Phone Clients are supported.

3.3.1 Prerequisites

  • Visual Studio 2015 professional or enterprise
  • Enroll Windows dev account with MSDN Subscription
  • Get Application Secrets and Package SID from Windows Live Application Management portal
  • Knowledge of developing an SMP SDK based Windows native project.
  • Account on SAP HANA Cloud Platform, mobile services for dev & ops.
  • Valid mobile platform Administrator user credentials
  • Application Configuration is created on the mobile platform server
  • REST client (e.g. Firefox REST client or Postman REST client for Chrome)

3.3.2 Get Application Secrets and Package SID

Go to https://apps.dev.microsoft.com/?mkt=en-us#/appList
Click Add an app, type an app name. After the app is created, you will be able to see the Application Secrets and Package SID, see below screenshot.

3.3.3 Implement Push Notification APIs in client app

  1. Open your Windows Native project in VS, add a button in any page where you can register for Push. Then add below code in the button click event method: First request a push notification…
                    PushNotificationChannel currentChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
                    currentChannel.PushNotificationReceived += currentChannel_PushNotificationReceived;
    
  2. Get currentChannel URI and upload the settings to SMP3 or HCMPs server for push registration. Below is sample code.
    var writableSettings = SharedContext.LogonContext.LogonCore.ApplicationSettings.GetWritableSettings();
    await SharedContext.LogonContext.LogonCore.ApplicationSettings.DownloadSettingsAsync();
    if (!SharedContext.LogonContext.LogonCore.State.IsGatewayConnectionUsed)
                    {
                        writableSettings["WnsChannelURI"].Value = currentChannel.Uri;
                        writableSettings["ApplicationVersion"].Value = "1.1";
                        await SharedContext.LogonContext.LogonCore.ApplicationSettings.UpdateSettingsAsync(writableSettings);
                    }
    
  3. Catch the exception If Push channel URI could not be fetched
    catch (Exception pushChannelURiException)
                {
                    System.Diagnostics.Debug.WriteLine("Push channel URI could not be fetched. Ensure you enable proxy or verify other settings" + pushChannelURiException.Message);
                }
    
  4. Once notification is received, it will trigger PushNotificationReceived event
    void currentChannel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
            {
                // TODO: Change 4 - Event handler method for PushNotificationReceived event 
                var notificationContent = String.Empty;
                switch (args.NotificationType)
                {
                    case PushNotificationType.Badge:
                        notificationContent = args.BadgeNotification.Content.GetXml();
                        break;
                    case PushNotificationType.Tile:
                        notificationContent = args.TileNotification.Content.GetXml();
                        break;
                    case PushNotificationType.Toast:
                        notificationContent = args.ToastNotification.Content.GetXml();
                        break;
                    case PushNotificationType.Raw:
                        notificationContent = args.RawNotification.Content;
                        break;
                }
                args.Cancel = true;
            }
    

3.3.4 Associate Windows project with the Windows Store app

  • Open the Windows project, right-click on the Windows project name -> Store -> Associate App with the Store…
  • In the opened the page, it will show the app you created in 3.4.2 section: Get Application Secrets and Package SID from Microsoft site section. If not, click Refresh
  • Select the app and click Next, then click Associate. It will associate your project with the app name you added. Also it will generate a .pfx file in your project

3.3.5 Deploy the native app and Register for Push

After associating, deploy the native app and register, then click the button to register for push. The application is now ready for receive push notifications from the mobile platform server.


3.4 Configuring Hybrid Applications (Kapsel SDK)

3.4.1 Prerequisites

  • Have an existing Kapsel App
  • Account on SAP HANA Cloud Platform, mobile services for dev & ops.
  • Valid mobile platform Administrator user credentials
  • Application Configuration is created on the mobile platform server
  • REST client (e.g. Firefox REST client or Postman REST client for Chrome)
  • Add push plugins to an existing Kapsel app
    cordova plugin add kapsel-plugin-push --searchpath %KAPSEL_HOME%/plugins
    

    As from SMP SDK SP15, it starts to support FCM. Additional steps or notes below are needed to make the push notification works.

    • Plugin for Firebase
      As part of this support there is a new plugin added to which is under the plugin/pushfcm. The name of the plugin is not changed. When we point to this directory for adding the push plugin, the manifest file will be changed in a different way that of the GCM push plugin.
    • Change to Android Manifest
      When the push plugin is added the following sections will be added to the Android manifest XML file. This section says the classes that listening to the incoming FCM message and Listener that communicate with FCM server. This changes will take place automatically when the plug-in is installed.
      Note that the GCM and FCM push will not co-exist
    • Preparing and configuring FCM
      To use FCM one has to configure an application with Google developer account and make necessary setup. To do this follow the steps.

      1. This step can be done by using your existing google email account. If you don’t have, one should be created
      2. Login to http://console.firebase.google.com using your google account.
      3. Create a New project using “CREATE NEW PROJECT” button or you can click on any of the existing project.
      4. Click on ”Add Another App” button and Select Android. Type in the package name and the application name and click “ADD APP”.
      5. This will take you to the new project dashboard page as shown here. From the new application use the the settings options to configure the application
      6. At this point we need to add firebase cloud messaging for Android by clicking on ”Add Firebase to your android app”
      7. This will take you to the new project dashboard page as shown here

        Here the the package name should match with the package name you are going to provide for the Cordova Kapsel/Fiori application you are going to create. If there is a mismatch FCM push won’t work. If you are making multiple package names, you need to create separate application with FCM console.After you have entered the package name and Nickname, press on ”ADD APP” button.
      8. Click continue on the next screen
      9. Client Finish on this next screen
      10. This will take you to the application screen.
      11. Click on the context menu on the right side of your application name and select ”Settings”
      12. From the next screen download the google-services.json and copy to the root directory of your project.

3.4.2 Implement Push Notification APIs in client app

  • add a button in Kapsel project and in its click method, add below code
    buttonRegPush: function (evt) {
       if (sap.Push == null) {
          sap.m.MessageBox.show("Push namespace is invalidated",sap.m.MessageBox.Icon.INFORMATION,"Info");
          return false;
           }       
        var nTypes = sap.Push.notificationType.SOUNDS | sap.Push.notificationType.ALERT | sap.Push.notificationType.BADGE;
              // sap.Push.registerForNotificationTypes(nTypes, regSuccess, regFailure, proccessNotification, null);  //GCM Sender ID, null for APNS
          var senderId=null;
          if(device.platform=="Android"){
             senderId="XXXXXXX";
          }
              sap.Push.registerForNotificationTypes(
             nTypes, 
             function (mesg){sap.m.MessageBox.show("Successfully registered "+mesg,sap.m.MessageBox.Icon.SUCCESS, "Success");}, 
             function regFailure(errorInfo) {
                alert("Failed to register.\n ErrorInfo: " + JSON.stringify(errorInfo));
                console.log("Error while registering.  " + JSON.stringify(errorInfo));
             }, 
             function proccessNotification(notification) {
                alert("Received a notifcation:  "+JSON.stringify(notification));
                console.log("Received a notifcation: " +  JSON.stringify(notification));
             }, 
             senderId);  
       },
    

    Need change the senderId accordingly with your own senderId which set in section 2.3.

3.4.3 Associate Windows project with the Windows Store app

If the kapsel application is Windows project, need associate windows project with the Windows store app. If the application is Android/iOS project, this steps is not needed.

  • Open the Windows project, right-click on the Windows project name -> Store -> Associate App with the Store…
  • In the opened the page, it will show the app you created in 3.3.2 section: Get Application Secrets and Package SID from Microsoft site section. If not, click Refresh
  • Select the app and click Next, then click Associate. It will associate your project with the app name you added. Also it will generate a .pfx file in your project
  • Right click the .pfx file, select Properties, change Package Action to “Copy always”
  • Open package.windows10.appxmanifest file, copy the Package name from Packaging tab
  • Replace the package name for Start page field on Application tab
  • Copy all text in Start page, replace the URI field on Content URIs tab.

3.4.4 Using GCM based server for push notifiation

This section is for Android specific.
From SMP SDK SP15, it starts to support FCM, to make an FCM client to work with GCM based server, we should use the legacy server key and sender ID provided in the Cloud Messaging tab of the project Settings. As in below screenshot.

You need config the legacy server key and sender ID in CPms which mentioned section 2.3 Cockpit Settings for Android.

3.4.5 Build and Install application

Build and install the application. Click RegPush button, it should show a message that “Successfully registered …”.


3.5 Configuring SAP Fiori Clients

3.5.1 Install the Fiori Client on your mobile device

  • Open the app store on your device
  • Install the app “SAP Fiori Client”

3.5.2 Configure The Fiori Client on your iPhone

  • Open the Fiori Client you just installed
  • On the Welcome Screen tip “Log In”
  • On the next Screen [Enter SAP Fiori URL or work e-mail provided.
  • Confirm the above step with [OK]
  • On the next Screen log on with your user credentials for FIA (Frontend Server)
  • On the next screen you can define a passcode.
  • Select [OK] on the following “SAP Fiori Would like to Send You Notifications” Pop-Up to receive notifications
  • After a couple of seconds, you should see the Fiori Launchpad

3.5.3 Test the Notification Delivery

  • Open the SAP GUI and logon to the System CWK, client 715.
  • Navigate to Transaction SE38 (Enter Transaction Code and Confirm with Enter)
  • Start the ABAP Report /IWNGW/R_BEP_DEMO_CREATE_NOTIF
  • Choose your Notification Type, Your Recipients (your user name is pre-filled) and Execute the report.
  • Now you should receive Notifications. This should work in both cases, the Fiori Client is running in the foreground, the Fiori Client isn’t running.
  • If you would like to send a notification with a long text (to test truncation and stuff), follow the steps described in 4) but start the ABAP Report Z_SK_CREATE_LONG_NOTIF instead of /IWNGW/R_BEP_DEMO_CREATE_NOTIF. This will send a leave request with a different long text.


4 Notification Data Formats

Notification data can be sent in the following formats:

  • Notification data sent through HTTP headers
  • Notification sent in URL format
  • Notification data sent using PUSH API


4.1 Notification data sent through HTTP headers

Notification data can be sent by the back end as generic HTTP headers or as device platform-specific HTTP headers . SAP recommends that you use the URLs provided in Notification Data Sent Using Push API as detailed in section 4.3

Request URL for a notication using HTTP headers is as follows:

URL: https://<HMC base URL>/Notification/<registration ID>

Add the neessary headers, as described below to the request above.

  • Generic header
    The generic HTTP header <X-SMP-DATA> is used in the HTTP request to send any notification type such as APNS, GCM, BlackBerry, or WNS.
  • APNS-specific headers
    Use these APNS-specific HTTP headers to send APNS notifications via SAP HANA Cloud Platform, mobile service for development and operations:

    Header Structure Consists of
    <X-SMP-APNS-ALERT> A JSON document. You can use this header or other individual headers listed in this table.
    <X-SMP-APNS-ALERT-BODY> Text of the alert message.
    <X-SMP-APNS-ALERT-ACTION-LOC-KEY> If a string is specified, this header shows an alert with two buttons: Close and View. iOS uses the string as a key to get a localized string for the correct button title instead of View. If the value is null, the system shows an alert. Click OK to dismiss the alert.
    <X-SMP-APNS-ALERT-LOC-KEY> Key to an alert-message string in a Localizable.strings file for the current localization.
    <X-SMP-APNS-ALERT-LOC-ARGS> Variable string values to appear in place of the format specifiers in loc-key.
    <X-SMP-APNS-ALERT-LAUNCH-IMAGE> File name of an image file in the application bundle. It may include the extension. Used as the launch image when you tap the action button or move the action slider. If this property is not specified, the system uses on of the following:

    • The previous snapshot
    • The image identified by the UILaunchImageFile key in the Info.plist file of the application
    • The Default.png.
    <X-SMP-APNS-BADGE> Number that appears as the badge on the application icon.
    <X-SMP-APNS-SOUND> Name of the sound file in the application bundle.
    <X-SMP-APNS-DATA> Custom payload data values. These values must use the JSON-structured and primitive types, such as dictionary (object), array, string, number, and boolean.
    <X-SMP-APNS-CATEGORY> Identifies a category that is used to specify notification actions, such as contacts, or messages.
    <X-SMP-APNS-CONTENT-AVAILABLE> Indicates whether the user can take action.
  • GCM-specific headers
    Use these GCM-specific HTTP headers to send GCM notifications:

    Header Structure Consists of
    <X-SMP-GCM-COLLAPSEKEY > An arbitrary string (such as “Updates Available”) that collapses a group of like messages when the device is offline, so that only the last message is sent to the client.
    <X-SMP-GCM-DATA> Payload data, expressed as parameters prefixed with data and suffixed as the key.
    <X-SMP-GCM-DELAYWHILEIDLE> (Optional) Represented as 1 or true for true, any other value for false, which is the default value.
    <X-SMP-GCM-TIMETOLIVE> Number of seconds that the message remains available on GCM storage if the device is offline.

4.1.1 SAP Gateway Notification support

There are no specific handling requirements for sending notifications on the SAP gateway side. SAP HANA Cloud Platform, mobile service for development and operations sends notifications using gateway-specific headers.

The SAP HANA Cloud Platform, mobile service for development and operations identifies the device type, and based on the device type, converts the gateway notification headers into the third-party notification context data for APNS, GCM,WNS, and MPNS. Non-SAP gateway back ends also use the headers listed below to send generic notifications; the back ends are unaware of the device platform.

  • SAP gateway-specific headers that are handled by the SAP Gateway Notification Support for sending notifications.
    Structure Header Consists of
    <x-sap-poke-title> Text of the alert message.
    <x-sap-poke-entriesofinterest> Number that appears as the badge on the application icon.
    <x-sap-poke-data> Custom payload data values. These values must use the JSON structured and primitive types such as dictionary (object), array, string, number, and boolean.
  • APNS
    SAP HANA Cloud Platform, mobile service for development and operations converts the following gateway notification headers into APNS notifications:

    Structure Header Consists of
    <x-sap-poke-title> Text of the alert message.
    <x-sap-poke-entriesofinterest> Number that appears as the badge on the application icon.
    <x-sap-poke-data> Custom payload data values. These values must use the JSON structured and primitive types such as dictionary (object), array, string, number, and boolean.
    <x-sap-poke-category> Identifies a category that is used to specify notification actions, such as contacts, or messages.
    <x-sap-poke-content-available> Indicates that the user can take action.
  • GCM
    SAP HANA Cloud Platform, mobile service for development and operations converts the gateway notification headers into GCM notifications:

    Header Structure Consists of
    <x-sap-poke-title> An arbitrary string (such as “Updates Available”) collapses a group of like messages when the device is offline, so that only the last message is sent to the client.
    <x-sap-poke-data> Payload data. Size should not exceed 4KB.
  • WNS
    SAP HANA Cloud Platform, mobile service for development and operations converts the gateway notification headers into WNS notifications:

    Structure Header Consists of
    <x-sap-poke-title> Text of the alert message to be shown on the Tile and Toast notifications
    <x-sap-poke-entriesofinterest> Number that appears as the badge on the application icon
    <x-sap-poke-data> Custom payload data to be sent to the device as a raw notification


4.2 Notification sent in URL format

Notification data can also be sent by using the REST client, using URL arguments as part of the mobile platform push endpoint, or as the delivery address URL. Request URL for a notication in URL format is as follows:
URL: https://<HMC base URL>/Notification/<application connection ID>?alert=<alert>&badge=<badge>&sound=<sound>&data=<data in text format>&category=<category_name>&content_available<true/false>

All URL arguments (zero to many) are optional. The arguments are converted into device-type specific notifications as explained:

  • APNS
    Parameters Description
    alert Text of the alert message.
    badge Number that appears as the badge on the application icon.
    sound Name of the sound file in application bundle.
    data Custom payload data values. These values must use the JSON-structured and primitive types, such as dictionary (object), array, string, number, and boolean.
    category Identifies a category that is used to specify notification actions, such as contacts, or messages.
    content_available Indicates whether the user can take action.
  • GCM
    Parameters Description
    alert An arbitrary string (such as “Updates Available”) that collapses a group of like messages when the device is offline, so that only the last message is sent to the client
    data Payload data, expressed as parameters prefixed with data and suffixed as the key
  • WNS
    Parameters Description
    alert The text of the alert message to be sent as a Tile notification
    badge Number that appears as the badge on the application icon
    data Payload data to be sent
  • MPNS (Notification for Windows Phone)
    Parameters Description
    alert The text of the alert message to be sent as a Tile notification
    badge Number that appears as the badge on the application icon
    data Payload data to be sent

Based on the data send either in headers or in the URL, corresponding notification is sent to the device:

Header Notification Tile Notification Toast Notification Raw Notification
Alert Yes Yes No
Badge Yes No No
Data No No Yes


4.3 Notification data sent using restnotification API

The RESTful service based restnotification API is the recommended way to send push notifications in the SAP HCP, mobile service for dev & ops, due to its many advantages over interfaces that are based on HTTP headers or URL parameters. Using this API, the notification data is sent as a json payload, instead of a HTTP header or URL parameter as described before.

The next section describes the restnotification API in detail:

How to config and consume Push Notification from SAP Mobile Services (Part2)

To report this post you need to login first.

5 Comments

You must be Logged on to comment or reply to a post.

  1. Suwardi Nursalim

    Hi Serena,

     

    Very interesting blog that you have above. However I can’t find the Push Notification option on my current SAP Fiori Client which should be the latest version in the App Store. Is there any pre-requisite on configuring the notification to the SAP Fiori Client?

     

    Thank you.

    (0) 
    1. Chang-gui Shen

      Hi,

      SAP Fiori Client is packaged with SAP certificate/provisioning profile, so you needn’t any pre-requisite configuration to it.

      But from server side(SMP3/CPms), you need select the option “Predefined for SAP Fiori Client” from Push Notification kit, so that you can use SAP built-in settings for push.

      Besides this, you also need ensure that your Fiori support notification, so that it can generate APNS device token, Android GCM registration ID or WNS channel URI automatically.

      Regards,

      Changgui

      (0) 
      1. Suwardi Nursalim

        Hi Chang Gui,

         

        When you talk about server side, SMP3/CPms, what kind of server are we talking about here?

         

        Our setup for Fiori deployment is Hub Gateway Setup (FES3.0) with backend on ECC EHP8.

         

        SMP3/CPms here refer to Cloud Platform Mobile Services? Do you have any documentation that you can share on this?

         

        Thank you.

        Suwardi

        (0) 
        1. Chang-gui Shen

          Hi Suwardi,

          Yes, CPms is SAP Could Platform Mobile Service, and SMP is SAP Mobile Platform. Please find detail info from here: https://help.sap.com/viewer/33c4b62fdc174d89a47d4baee3ced08a/Cloud/en-US/a8ad2154513f4da9bf47051d653f0052.html

          Regards,

          Changgui

           

          (0) 
          1. Team ABAP

            Hi Chang Gui,

             

            I’m not really sure how I can integrate the standard Fiori Client downloaded through the Apple/Android App Store with HCPms. I don’t really see a particular section in the help document related to this.

            There’s this particular section related to App Store Fiori Client, but it does not really say on how do we integrate our SAP Gateway with the SAP CPms. I believe there must be some link to be made. in order for me to integrate the Gateway as the Notification Provider and the SAP CPms as the push postman.

             

            Currently I don’t even see my Fiori Client trying to register my device to APNs / GCMs.

            (0) 

Leave a Reply