IBM Cloud Docs
将您的应用程序从推送通知迁移到 Event Notifications

将您的应用程序从推送通知迁移到 Event Notifications

您可以将移动应用程序从不推荐的 IBM Cloud Push Notifications 服务迁移到 Event Notifications 以继续使用 Push。

简介

Event Notifications 是一种路由服务,用于告知您 IBM Cloud 帐户中发生的关键事件。 您可以将 IBM Cloud® Event Notifications 从 IBM Cloud 服务 (例如,Monitoring,Security and Compliance Center和 Secrets Manager ) 过滤和路由到通信通道 (例如,电子邮件,SMS,推送通知和 Webhook)。

本指南概述了迁移移动应用程序和后端以与 Event Notifications 服务集成的步骤。

采取以下步骤迁移您的移动应用程序:

  • 创建并配置 IBM Cloud® Event Notifications 的实例
  • 修改 Android 或 iOS 移动应用程序以使用 Event Notifications 服务
  • 修改后端以与 Event Notifications 服务的新 API 集成
  • 发布新版本的移动应用程序

创建并配置 Event Notifications 服务的实例

创建 Event Notifications 服务实例。 此过程不使用 Event Notifications 服务的任何高级功能。 在服务中,创建 API 源,主题,预订和目标,如图 1 中所述。

有关 Event Notifications的概念的更详细说明,请参阅 IBM Cloud® Event Notifications 入门。

Push capability in Event Notifications
Push capability in Event Notifications

创建源

创建 API 源。 此源表示从中发送通知的后端。

创建主题

创建一个主题,所有来自后端的事件都将流入该主题。 但是,本主题不会执行任何过滤,而是定义用于将所有事件从源发送到此主题的过滤器。

创建目标

创建所需类型的目标。

创建预订

创建从主题到目标的预订。

创建服务凭证

创建一组具有“设备管理器”角色的凭证。

修改 Android 移动应用程序

修改移动应用程序源代码以使用新的 Event Notifications SDK。 将现有的 Push Notifications 服务 SDK 替换为 Event Notifications FCM SDK。

创建 Android 目标

为 Android 应用程序创建类型为 Android Push Notification (FCM) 的目标。 从 Google 控制台提供发送方标识和服务器密钥。

创建 Android 目的地{: caption="创建 Android 目的地创建 Android" caption-side="bottom"}

在 Firebase 控制台中修改项目

Push Notifications SDK 的软件包名称为 com.ibm.mobilefirstplatform.clientsdk.android.push。 新的 Event Notification SDK 具有软件包 com.ibm.cloud.eventnotifications.destination.android。 使用新软件包更新 Firebase Console 中的项目,然后下载并替换 Android 项目中的新 google-services.jsonfile

  1. 转至 Firebase 控制台

    Firebase 控制台{: caption="Firebase 控制台Firebase" caption-side="bottom"}

  2. 选择要用于 Push Notifications的项目。

    选择项目
    选择
    *

  3. 在导航面板中,选择项目概览旁边的设置图标,然后选择设置 > 项目设置。 向下滚动以查找 您的应用程序

    项目设置
    * 项目设置
    项目设置

  4. 查找软件包名称为 com.ibm.mobilefirstplatform.clientsdk.android.push 的应用程序,然后单击 除去此应用程序

  5. 单击 添加应用程序> 选择 Android

  6. 输入 com.ibm.cloud.eventnotifications.destination.android 作为软件包名称,然后单击 注册应用程序

    注册应用程序*{: caption="注册" caption-side="bottom"}

  7. 下载 google-services.json。 稍后在修改应用程序时使用此文件。

编辑 Android 应用程序

  1. 在应用程序模块中添加 Firebase google-services.json

  2. 更改模块的 build.gradlefile 以包含新的 SDK。

    // Replace the following section
    
    dependencies {
       ........
       implementation 'com.google.firebase:firebase-messaging:20.0.0'
       Implementation 'com.ibm.mobilefirstplatform.clientsdk.android:core:3.+'
       .......
    }
    
    // with this
    
    dependencies {
       ........
       implementation platform('com.google.firebase:firebase-bom:29.0.0')
       implementation 'com.google.firebase:firebase-messaging'
       implementation 'com.ibm.cloud:sdk-core:9.15.0'
       implementation 'com.ibm.cloud:eventnotifications-destination-android:0.0.1'
       .......
    }
    
  3. 打开 AndroidManifest.xml 并更改以下元素:

    • 更改 <service> 部分以引用新服务

      
      // Replace the following section
      
      <service android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushIntentService" android:exported="true" >
         <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
         </intent-filter>
      </service>
      
      <service
      android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush" android:exported="true" >
         <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
         </intent-filter>
      </service>
      
      // with this
      
      <service android:name="com.ibm.cloud.eventnotifications.destination.android.ENPushIntentService" android:exported="true">
         <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
         </intent-filter>
      </service>
      
      <service android:name="com.ibm.cloud.eventnotifications.destination.android.ENPush" android:exported="true" >
         <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
         </intent-filter>
      </service>
      
    • <activity> 部分更改为指向新类

      
      // Replace the following section
      
      <activity  android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.    MFPPushNotificationHandler" android:theme="@android:style/Theme.NoDisplay"/>
      
      // with this
      
      <activity   android:name="com.ibm.cloud.eventnotifications.destination.android.     ENPushNotificationHandler" android:theme="@android:style/Theme.NoDisplay"/>
      
  4. 更改代码中的 import 语句。 新软件包名称为 com.ibm.cloud.eventnotifications.destination.android.*。 替换旧的推送导入,如下所示:

    // Replace the following section
    
    import com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush;
    
    // with this
    
    import com.ibm.cloud.eventnotifications.destination.android.ENPush;
    
  5. 初始化新 SDK

    // Replace the following section
    
    BMSClient.getInstance().initialize(this, "ibmCloudRegionSuffix");
    MFPPush push = MFPPush.getInstance();
    push.initialize(getApplicationContext(), "appGUID", "clientSecret");
    
    // with this
    
    String instanceGUID = "<instance_guid>>";
    String destinationID = "<instance_destination_id>";
    String apiKey = "<instance_apikey>";
    
    ENPush enPush = ENPush.getInstance();
    push.setCloudRegion(ENPush.REGION_US_SOUTH); // Set your region
    
    push.initialize(getApplicationContext(),instanceGUID,destinationID, apiKey);
    

    在新的 initialize() 方法中还有其他字段,例如 destinationIDapikey

    有关获取 apikey for client SDK 的更多信息,请参阅 管理服务访问权

  6. 新 SDK 中的回调类有更改。 在侦听器中进行这些更改。

    // Replace the following section
    
    MFPPushNotificationListener notificationListener = new MFPPushNotificationListener() {
    
       @Override
       public void onReceive (final MFPSimplePushNotification message){
          // Handle Push Notification
       }
    };
    
    push.listen(notificationListener)
    
    // with this
    
    ENPushNotificationListener notificationListener = new ENPushNotificationListener() {
    
          @Override
          public void onReceive (final ENSimplePushNotification message){
             // Handle Push Notification
          }
    };
    
    push.listen(notificationListener)
    
  7. 对设备注册步骤进行更改。

    • 如果在没有 userID 的情况下注册

         // Replace the following section
      
      push.registerDevice(new MFPPushResponseListener<String>() {
      
           @Override
           public void onSuccess(String response) {
               //handle successful device registration here
           }
      
           @Override
           public void onFailure(MFPPushException ex) {
               //handle failure in device registration here
               }
      });
      
      // with this
      
      push.registerDevice(new ENPushResponseListener<String>() {
      
           @Override
           public void onSuccess(String deviceId) {
                //handle successful device registration here
           }
      
           @Override
           public void onFailure(ENPushException ex) {
                //handle failure in device registration here
           }
      });
      
    • 如果您使用 registerDeviceWithUserId

      // Replace the following section
      
      push.registerDeviceWithUserId("userId", new MFPPushResponseListener<String>() {
      
           @Override
           public void onSuccess(String response) {
               //handle successful device registration here
           }
      
           @Override
           public void onFailure(MFPPushException ex) {
               //handle failure in device registration here
           }
      });
      
      // with this
      
      push.registerDeviceWithUserId("userId",new ENPushResponseListener<String>() {
      
            @Override
            public void onSuccess(String deviceId) {
                //handle successful device registration here
            }
      
            @Override
            public void onFailure(ENPushException ex) {
                //handle failure in device registration here
            }
      });
      
  8. 对注销 API 调用进行更改。

    // Replace the following section
    
    push.unregister(new MFPPushResponseListener<String>() {
    
       @Override
       public void onSuccess(String s) {
             // Handle success
       }
    
       @Override
       public void onFailure(MFPPushException e) {
             // Handle Failure
       }
    });
    
    // with this
    
    push.unregister(new ENPushResponseListener<String>() {
    
          @Override
          public void onSuccess(String s) {
             // Handle success
          }
    
          @Override
          public void onFailure(ENPushException e) {
             // Handle Failure
          }
    });
    
  9. (可选) 如果您正在使用标记

    • 更改标记预订,如下所示:

      // Replace the following section
      
      push.subscribe("tagName", new MFPPushResponseListener<String>() {
      
            @Override
            public void onSuccess(String arg) {
               System.out.println("Succesfully Subscribed to: "+ arg);
            }
      
            @Override
            public void onFailure(MFPPushException ex) {
               String message = ex.getMessage();
               System.out.println("Error subscribing to Tag " + message);
            }
      });
      
      // with this
      
      push.subscribe("tagName", new ENPushResponseListener<String>() {
      
            @Override
            public void onSuccess(String arg) {
               System.out.println("Succesfully Subscribed to: "+ arg);
            }
      
            @Override
            public void onFailure(ENPushException ex) {
               String message = ex.getMessage();
               System.out.println("Error subscribing to Tag " + message);
            }
      });
      
    • 用于获取设备的所有标记预订的更改

      // Replace the following section
      
      push.getSubscriptions(new MFPPushResponseListener<List<String>>() {
      
            @Override
            public void onSuccess(List<String> tags) {
               System.out.println("Subscribed tags are: "+tags);
            }
      
            @Override
            public void onFailure(MFPPushException ex) {
               String message = ex.getMessage();
               System.out.println("Error getting subscriptions " + message);
            }
      })
      
      // with this
      
      push.getSubscriptions(new ENPushResponseListener<List<String>>() {
      
            @Override
            public void onSuccess(List<String> tags) {
               System.out.println("Subscribed tags are: "+tags);
            }
      
            @Override
            public void onFailure(ENPushException ex) {
               String message = ex.getMessage();
               System.out.println("Error getting subscriptions " +message );
            }
      })
      
    • 对标记取消预订进行更改

      // Replace the following section
      
      push.unsubscribe("tagName", new MFPPushResponseListener<String>() {
      
         @Override
         public void onSuccess(String s) {
            System.out.println("Successfully unsubscribed from " + tag);
         }
      
         @Override
         public void onFailure(MFPPushException ex) {
            String message = ex.getMessage();
            System.out.println("Error while unsubscribing from tag "+ message);
         }
      });
      
      // with this
      
      push.unsubscribe("tagName", new ENPushResponseListener<String>() {
      
            @Override
            public void onSuccess(String s) {
               System.out.println("Successfully unsubscribed from tag . "+ tag);
            }
      
            @Override
            public void onFailure(ENPushException ex) {
               String message = ex.getMessage();
               System.out.println("Error while unsubscribing from "+ message);
            }
      });
      
  10. (可选) 如果您正在使用“通知”选项,请进行以下更改:

  11. 对通知操作侦听器的更改

    // Replace the following section
    
    notificationListener = new MFPPushNotificationListener() {
       @Override
       public void onReceive(final MFPSimplePushNotification message) {
          if (message.actionName.equals("Accept Button")){
             System.out.print("Clicked Accept Action");
          } else if (message.actionName.equals("Decline Button")){
             System.out.print("Clicked Decline Action");
          } else if (message.actionName.equals("View Button")){
             System.out.print("Clicked View Action");
          }
       }
    };
    
    // with this
    
    notificationListener = new ENPushNotificationListener() {
             @Override
       public void onReceive(final ENSimplePushNotification message) {
          if (message.getActionName().equals("Accept Button")){
                System.out.print("Clicked Accept Action");
          } else if (message.getActionName().equals("Decline Button")){
                System.out.print("Clicked Decline Action");
          } else if (message.getActionName().equals("View Button")){
                System.out.print("Clicked View Action");
          }
       }
    };
    

Android 移动应用程序已准备好使用 IBM Cloud® Event Notifications的新实例。

修改 iOS 移动应用程序

修改移动应用程序源代码以使用新的 Event Notifications SDK。 您将把现有的 Push Notifications 服务 SDK 替换为 Event Notifications FCM SDK。

创建 iOS 目的地

为 iOS app创建类型为 Apple Push Notification (APN) 的目标。 提供 P12 或 P8 及其配置。

创建iOS{: caption="创建iOS " caption-side="bottom"}

编辑 iOS 应用程序

请按照以下步骤从 BMPush 迁移到ENPushDestination:

  1. 更改 import 语句

    // Replace this
    
    import BMSCore
    import BMSPush
    
    // with this
    
    import ENPushDestination
    
  2. 替换 SDK 初始化代码

    // Replace this
    
    let push = BMSClient.sharedInstance
    
    push.initialize(bluemixRegion: "<IBM cloud region>")
    
    push.initializeWithAppGUID(
                   appGUID: "<IBM Cloud Push Instance GUID>",
                   clientSecret:"<IBM Cloud Push Instance ClientSecret>"
                )
    
    // with this
    
    let instanceGUID = "<IBM-Cloud-en-instance_guid>>";
    let destinationID = "<IBM-Cloud-en-instance-destination-id>";
    let apiKey = "<IBM-Cloud-en-instance-apikey>";
    
    let push = ENPush.sharedInstance
    
    push.setCloudRegion(region: "<IBM cloud region>")
    
    push.initialize(instanceGUID, destinationID, apiKey)
    

    在新的 initialize() 方法中有额外的字段,例如 destinationIDapikey。 有关获取 apikey for client SDK 的更多信息,请参阅 管理服务访问权

  3. 更改设备注册步骤

    • 如果在没有 userID 的情况下注册

      // Replace this
      
         push.registerWithDeviceToken(deviceToken: "<apns-device-token>") {
            (response, statusCode, error) -> Void in
      
               print(response)
      
         }
      
         // with this
      
         push.registerWithDeviceToken(deviceToken: "<apns-device-token>") {
               response, statusCode, error in
      
                  print(response?.id ?? "")
         }
      
    • 如果您正在使用用户标识进行注册

      // Replace this
      
      push.registerWithDeviceToken(deviceToken:("<apns-device-token>",                                                         WithUserId: "<your-user-id>") {
         (response, statusCode, error) -> Void in
      
            print(response)
      }
      
      // with this
      
      push.registerWithDeviceToken(deviceToken: "<apns-device-token>",
                                    withUserId: "<your-user-id>") {
         response, statusCode, error in
      
         print(response)
      }
      
  4. 更改注销 API 调用

    // Replace this
    
    push.unregisterDevice(completionHandler: {
       (response, statusCode, error) -> Void in
    
       print(response)
    }
    
    // with this
    
    push.unregisterDevice { response, statusCode, error in
       print(response)
    }
    
  5. (可选) 如果您正在使用标记:

    • 更改标记预订,如下所示:

      // Replace this
      
      push.subscribeToTags(tagsArray: ["<tag_name>"], completionHandler: { (response, statusCode, error) -> Void in
      
         /**.....*/
      }
      
      
      // with this
      push.subscribeToTags(tagName: "<tag_name>") {
         response, statusCode, error in
      
         /**.....*/
      });
      
    • 对获取设备的所有标记预订的更改

      // Replace this
      
      push.retrieveSubscriptionsWithCompletionHandler(completionHandler: { (response, statusCode, error) -> Void in
      
         /**.....*/
      }
      
      // with this
      
      push.retrieveSubscriptionsWithCompletionHandler {
         response, statusCode, error in
      
         /**.....*/
      }
      
    • 对标记取消预订的更改

      // Replace this
      
      
      push.unsubscribeFromTags(tagsArray: ["<tag_name>"], completionHandler: {
      (response, statusCode, error) -> Void in
      
         /**.....*/
      }
      
      
      // with this
      
      push.unsubscribeFromTags(tagName: "<tag_name>") {
         response, statusCode, error in
      
         /**.....*/
      }
      
  6. (可选) 如果您正在使用 通知选项,请进行以下更改:

    • 初始化类

      // Replace this
      
      let notificationOptions = BMSPushClientOptions()
      notificationOptions.setInteractiveNotificationCategories(
                           categoryName: [category])
      push.initializeWithAppGUID(
            appGUID: "<IBM Cloud Push Instance GUID>",
            clientSecret:"<IBM Cloud Push Instance ClientSecret>",
            options: notificationOptions)
      
      
      // with this
      
      let notificationOptions = ENPushClientOptions()
      notificationOptions.setInteractiveNotificationCategories(
                           categoryName: [category])
      enPush.initialize("<instance_guid>",
                        "<instance_destination_id>",
                        "<instance_apikey>",
                        notificationOptions)
      
    • 更改“通知”按钮

      // Replace this
      
      let acceptButton = BMSPushNotificationAction(
                        identifierName: "Accept",
                        buttonTitle: "Accept",
                        isAuthenticationRequired: false,
                        defineActivationMode:.background)
      
      let rejectButton = BMSPushNotificationAction(
                        identifierName: "Reject",
                        buttonTitle: "Reject",
                        isAuthenticationRequired: false,
                        defineActivationMode: .background)
      
      // with this
      
      
      let actionOne = ENPushNotificationAction(
                     identifierName: "Accept",
                     buttonTitle: "Accept",
                     isAuthenticationRequired: false,
                     defineActivationMode: .foreground)
      
      let actionTwo = ENPushNotificationAction(
                     identifierName: "Reject",
                     buttonTitle: "Reject",
                     isAuthenticationRequired: false,
                     defineActivationMode: .destructive)
      
    • 更改“通知”类别

         // Replace this
      
      let category = BMSPushNotificationActionCategory(
                     identifierName: "category",
                     buttonActions: [acceptButton, rejectButton])
      
      // with this
      
      let category = ENPushNotificationActionCategory(
                     identifierName: "category",
                     buttonActions: [actionOne, actionTwo])
      

iOS 移动应用程序已准备好处理 IBM Cloud® Event Notifications的新实例。

修改 Web 应用程序

修改 Web 应用程序源代码以使用新的 Event Notifications SDK。 您将把现有的 Push Notifications 服务 WebPush SDK 替换为 Event Notifications WebPush SDK。

创建 Web 目标

Chrome 目标

为 Web 应用程序创建类型为 Chrome Push Notification 的目标。 提供网站 URL 和 FCM 服务器密钥。

创建 Chrome 浏览器目的地
创建 Chrome 浏览器目的地*创建 Chrome 浏览器

Firefox 目标

为 Web 应用程序创建类型为 Firefox Push Notification 的目标。 提供网站 URL。

创建Firefox{: caption="创建Firefox " caption-side="bottom"}

Safari 目标

为 Web 应用程序创建 Safari Push Notification 类型的目标。 提供网站名称、网站推送 ID、网站 URL URL 格式字符串、p12 文件、密码和图标。

创建 Safari 目的地
Safari

编辑 Web 应用程序

使用以下步骤使用最新 SDK 更新 Web 应用程序。

  1. 更改 import 语句。

       // Replace this
       <script src="BMSPushSDK.js" async></script>
    
       // with this
       <script src="https://github.com/IBM/event-notifications-destination-webpush-sdk/blob/main/ENPushSDK.js" async></script>
    
  2. 替换 SDK 初始化代码。

       // Replace this
    
       var bmsPush = new BMSPush()
       function callback(response) {
       	alert(response.response)
       }
       var initParams = {
           "appGUID":"push app GUID",
           "appRegion":"Region where service hosted",
           "clientSecret":"push app client secret",
           "websitePushIDSafari": "website Push ID for safari",
           "deviceId":"Optional deviceId for device registration",
           "applicationServerKey":"VAPID key",
       }
       bmsPush.initialize(params, callback)
    
       // with this
    
       var enPush = new ENPush()
    
       function callback(response) {
         alert(response)
       }
    
       var  initParams = {
          "instanceGUID": "<IBM-Cloud-en-instance_guid>",
          "apikey": "<IBM-Cloud-en-instance-apikey>"; ,
          "region": "<IBM cloud region>",
          "chromeDestinationId": "<IBM-Cloud-en-instance-chrome-destination-id>",
          "chromeApplicationServerKey": "<IBM-Cloud-en-instance-chrome-vapid>",
          "firefoxDestinationId": "<IBM-Cloud-en-instance-firefox-destination-id>",
          "firefoxApplicationServerKey": "<IBM-Cloud-en-instance-firefox-vapid>",
          "safariDestinationId": "<IBM-Cloud-en-instance-safari-destination-id>",
          "websitePushIdSafari": "<safari-web-push-id>"
       }
    
       enPush.initialize(initParams, callback)
    

    BMSPushSDK.js

  3. 更改设备注册步骤

    • 如果在没有 userID 的情况下注册

      // Replace this
      bmsPush.register(function(response) {
          alert(response.response)
      })
      // with this
       enPush.register(function(response) {
          alert(response)
      })
      

      BMSPushSDK.js

    • 如果您正在使用用户标识进行注册

      // Replace this
      bmsPush.registerWithUserId("your UserId", function(response) {
          alert(response.response)
      })
      
      // with this
       enPush.registerWithUserId("your UserId", function(response) {
          alert(response)
      })
      

      BMSPushSDK.js

  4. 更改注销 API 调用

    
    // Replace this
    
    bmsPush.unRegisterDevice(function(response) {
    	   alert(response.response)
       })
    
    // with this
    
    enPush.unRegisterDevice(function (response) {
       alert(response)
    })
    
  5. (可选) 如果您正在使用标记:

    • 更改标记预订,如下所示:

      // Replace this
      
      bmsPush.subscribe("your tag", function (response) {
        alert(response)
      })
      
      // with this
      
      enPush.subscribe("your tag", function (response) {
        alert(response)
      })
      
    • 对获取设备的所有标记预订的更改

      // Replace this
      bmsPush.retrieveSubscriptions(function (response) {
        alert(response)
      })
      
      // with this
      
      enPush.retrieveSubscriptions(function (response) {
        alert(response)
      })
      
    • 对标记取消预订的更改

      // Replace this
      bmsPush.unSubscribe("your tag", function (response) {
        alert(response)
      })
      
      // with this
      enPush.unSubscribe("your tag", function (response) {
        alert(response)
      })
      

您的 Web 应用程序已准备好使用 IBM Cloud® Event Notifications的新实例。

修改后端

此部分包含您在后端执行的步骤。 发送通知 API 已更改,因此所有 SDK 也会更改。

如果您正在使用 Node.js SDK

将现有 Node SDK 迁移到新的 IBM Cloud® Event Notifications SDK。 请遵循此链接以获取新的 Node 管理 SDK 文档。

  1. 对导入 SDK 的更改

    // Replace the following section
    
    var PushNotifications = require('ibm-push-notifications').PushNotifications;
    var Notification = require('ibm-push-notifications').Notification;
    var PushMessageBuilder = require('ibm-push-notifications').PushMessageBuilder;
    var PushNotificationsApiKey = require('ibm-push-notifications').PushNotificationsWithApiKey;
    
    // with this
    
    var IamAuthenticator = require('@ibm-cloud/event-notifications-node-admin-sdk/auth').IamAuthenticator
    var EventNotificationsV1 = require('@ibm-cloud/event-notifications-node-admin-sdk/event-notifications/v1')
    
  2. 对初始化 SDK 的更改

// Replace the following section

var myPushNotifications = new PushNotificationsApiKey(PushNotifications.Region.US_SOUTH, "appGUID","apikey");

myPushNotifications.getAuthToken(function(hastoken,token){
     console.log(hastoken, token);
}

// with this

const authenticator = new IamAuthenticator({
  apikey: <apikey>,  // Event notifications service instance APIKey
});

const eventNotificationsService = EventNotificationsV1.newInstance({
  authenticator,
  serviceUrl: "https://" + region + ".event-notifications.cloud.ibm.com/event-notifications"
});
  1. 对创建通知目标的更改
// Replace the following section

var target = PushMessageBuilder.Target
  .deviceIds(["deviceID1", "deviceID2"])
  .userIds( ["userID1", "userID2"])
  .platforms([Notification.Platform.Apple,
            Notification.Platform.Google,
            Notification.Platform.WebChrome,
            Notification.Platform.WebFirefox,
            Notification.Platform.WebSafari,
            Notification.Platform.AppExtChrome])
  .tagNames(["tag1", "tag2"])
  .build();

// with this

const notificationDevicesModel = {
    user_ids: ['userID1', 'userID2'],
    fcm_devices: ['deviceID1'],
    apns_devices: ['deviceID2'],
    tags: ['tag1', 'tag2'],
    platforms: ['push_android', 'push_ios', 'push_chrome', 'push_firefox', 'push_safari'],
};
  1. 对 FCM 样式有效内容的更改
// Replace the following section

var style = PushMessageBuilder.FCMStyle
    .type(Notification.FCMStyleTypes
    .BIGTEXT_NOTIFICATION)
    .text("IBM Push")
    .title("Big Text Notification")
    .url(" https://upload.wikimedia.org/wikipedia/commons/2/24/IBM_Cloud_logo.png ")
    .lines(["IBM", "IBM Cloud", "Big Text Notification"])
    .build();

var lights = PushMessageBuilder.FCMLights
    .ledArgb(Notification.FCMLED.RED)
    .ledOffMs(1.0)
    .ledOnMs("1.0")
    .build();

// with this

// Style
const styleModel = {
    type: 'bigtext_notification',
    title: 'Big Text Notification',
    url: ' https://upload.wikimedia.org/wikipedia/commons/2/24/IBM_Cloud_logo.png ',
};

// Lights
const lightsModel = {
    led_argb: 'red',
    led_on_ms: 1.0,
    led_off_ms: '1.0',
};
  1. 对 FCM 消息体的更改
// Replace the following section

var fcm = PushMessageBuilder.FCM
   .collapseKey("ping")
   .interactiveCategory("Accept")
   .delayWhileIdle(true)
   .payload({ "alert" : "20% Off for you" })
   .androidTitle("Title for Android")
   .priority(Notification.FCMPriority.DEFAULT)
   .sound("sound.mp3")
   .timeToLive(1.0)
   .icon("http://www.iconsdb.com/icons/preview/purple/message-2-xxl.png")
   .sync(true)
   .visibility(Notification.Visibility.PUBLIC)
   .style(style)
   .lights(lights)
   .build();

// with this

const notificationFcmBodyMessageDataModel = {
  alert: '20% Off for you',
  collapse_key: 'ping',
  interactive_category: 'Accept',
  icon: 'http://www.iconsdb.com/icons/preview/purple/message-2-xxl.png',
  delay_while_idle: true,
  sync: true,
  visibility: 'PUBLIC',
  payload: { "alert" : "20% Off for you" },
  priority: 'DEFAULT',
  sound: 'sound.mp3',
  time_to_live: 1.0,
  lights: lightsModel,
  android_title: 'Title for Android',
  style: styleModel,
  type: 'DEFAULT',
};

// NotificationBodyMessage
const notificationBodyMessageModel = {
  en_data: notificationFcmBodyMessageDataModel,
};
  1. 对“发送”通知方法的更改
// Replace the following section

var settings = PushMessageBuilder.Settings
    .fcm(fcm)
    .build();

var notificationExample = Notification.message(message)
    .target(target)
    .settings(settings)
    .build();

myPushNotifications.send(notificationExample, function(error, response, body) {
    console.log("Error: " + error);
    console.log("Response: " + JSON.stringify(response));
    console.log("Body: " + body);
});

// with this

const params = {
  instanceId: instanceId,
  ceIbmenseverity: notificationSeverity,
  ceId: notificationID,
  ceSource: notificationsSource,
  ceIbmensourceid: sourceId,
  ceType: typeValue,
  ceTime: date,
  ceIbmenpushto: JSON.stringify(notificationFcmDevicesModel),
  ceIbmenfcmbody: JSON.stringify(notificationFcmBodyModel),
  ceIbmenapnsbody: JSON.stringify(notificationApnsBodyModel),
  ceIbmenapnsheaders: JSON.stringify(apnsHeaders),
  ceSpecversion: '1.0',
};

let res;
try {
  res = await eventNotificationsService.sendNotifications(params);
  console.log(JSON.stringify(res.result, null, 2));
} catch (err) {
  console.warn(err);
}

如果您正在使用 REST API

本部分包含有关“发送通知”API 所需的修改的详细信息。 新 API 在请求主体中具有额外的参数。 Android 推送通知的必需参数如下所示:

{
   "specversion": "1.0",
   "type": "com.acme.flightbooking.complete"
   "source": "com.acme.flightbooking",
   "id": "1234-1234-sdfs-234",
   "ibmensourceid": "00bb34e5-b8c1-4159-af15-8bc6980c3ab2:api",
   "ibmenfcmbody": "{\"en_data\":{\"alert\":\" Your flight is booked\"}}",
   "ibmenpushto": "{\"fcm_devices\": [\"9c75975a-3898-905d-3bd7c172\"]]}",
  }

有关事件属性的详细描述,请参阅 IBM Cloud® Event Notifications 事件属性定义。

// Replace this

{
 "message": {
    "alert": "Your flight is booked"
  },
  "target": {
     "tags": ["ibm_tag_1"]
  },
  "settings": {
     "gcm": {
        "interactiveCategory": "view info",
        "androidTitle": "Booking Info",
        "payload": "{\"nid\": \"1234-1234-sdfs-234\"}"
      }
  }
}

// with this
{
  "id": "1234-1234-sdfs-234",
  "ibmenfcmbody": "{\"en_data\":{\"alert\":\"Your flight is booked\",
                    \"android_title\":"Booking Info",
                    \"interactiveCategory\":\"view info\"}}",
  "ibmenpushto": "{\"tags\": [\"ibm_tag_1\"]}",
  "source": "234-rwekj-55bbc6-980c3ab2:scc",
  "ibmensourceid": "91f18cee-7d23-4895-a3ba-0c26696d9d96:api",
  "specversion": "1.0",
  "type": "com.acme.flightbooking.complete"
}
  • target 字段替换为 ibmenpushto
  • 已除去 message 字段。 alerturl 字段是 ibmenfcmbody 的一部分
  • settings->gcm 被替换 ibmenfcmbody

ibmenpushto 字段可以采用与推送 API 的 target 相同的四个值

  1. tags-标记名称数组
  2. user_ids-用户标识数组
  3. fcm_devices-设备标识的数组
  4. 平台-目标设备平台

ibmenfcmbody 字段包含服务的 settings-> gcmfield 中的每个字段,但有以下更改:

  1. 所有的田地都是蛇壳而不是骆驼壳。 例如,interactiveCategoryinteractive_category
  2. 不支持通道和通道组 Push Notifications。

将数据从 Push Notifications 服务迁移到 IBM Cloud® Event Notifications 服务

您可以使用 push-en-migration-tool 将设备和标记预订数据从 Push Notifications 服务迁移到 IBM Cloud® Event Notifications 服务。

发布新版应用程序

完成集成后,发布新版本的应用程序。 在新版本中,询问用户是否允许发送通知并再次注册设备。 在重叠窗口中,当用户群体从应用程序的旧版本迁移到新版本时,可能必须将通知发送到现有 Push Notifications 环境和新的 IBM Cloud® Event Notifications 环境。