IBM Cloud Docs
プッシュ通知から Event Notificationsへのアプリの移行

プッシュ通知から Event Notificationsへのアプリの移行

モバイル・アプリケーションを非推奨の IBM Cloud Push Notifications サービスから Event Notifications にマイグレーションして、プッシュの使用を続行できます。

概要

Event Notificationsはルーティング・サービスで、 IBM Cloud アカウントで発生した重要なイベントについて教えてくれます。 Monitoring、 Security and Compliance Center 、 Secrets Manager などの IBM Cloud サービスから、電子メール、SMS、プッシュ通知、Webhook などの通信チャネルに IBM Cloud® Event Notifications をフィルタリングおよびルーティングできます。

このガイドでは、Event Notifications サービスと統合するためにモバイル・アプリとバックエンドをマイグレーションする手順について概説します。

モバイル・アプリケーションをマイグレーションするには、以下の手順を実行します。

  • IBM Cloud® Event Notifications のインスタンスの作成と構成
  • Event Notifications サービスと連動するように Android モバイル・アプリまたは iOS モバイル・アプリを変更する
  • Event Notifications サービスの新しい API と統合するためのバックエンドの変更
  • モバイル・アプリの新しいバージョンをリリースする

Event Notifications サービスのインスタンスを作成して構成します。

Event Notifications サービスのインスタンスを作成します。 この手順では、Event Notifications サービスの拡張機能は使用しません。 サービス内では、図 1 に概説されているように、API ソース、トピック、サブスクリプション、および宛先を作成します。

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 コンソールから送信者 ID とサーバー・キーを指定します。

Androidの目的地を作成する{: caption="地を作成するAndroidの" caption-side="bottom"}地を作成するAndroidの目的地を作成する

Firebase コンソールでプロジェクトを変更します

Push Notifications SDK のパッケージ名はcom.ibm.mobilefirstplatform.clientsdk.android.pushでした。 新しいイベント通知 SDK には、パッケージcom.ibm.cloud.eventnotifications.destination.androidがあります。 Firebase Console でプロジェクトを新しいパッケージで更新し、Android プロジェクトに新しいgoogle-services.jsonfileをダウンロードして置き換えます。

  1. Firebase コンソールに移動します。

    Firebaseコンソール
    *Firebase
    *Firebaseコンソール

  2. Push Notifications に使用するプロジェクトを選択します。

    を選択する*
    を選択する*プロジェクトを選択する

  3. ナビゲーション・パネルで、「プロジェクトの概要」の横にある「設定」アイコンを選択し、「設定」>「プロジェクト設定」を選択します。 スクロールダウンしてアプリを見つけます。

    caption-side=bottom"
    プロジェクト設定
    ※プロジェクト設定

  4. パッケージ名com.ibm.mobilefirstplatform.clientsdk.android.pushのアプリを見つけて、**「このアプリを削除」**をクリックします。

  5. **「アプリの追加」>「Android の選択」**をクリックします

  6. パッケージ名としてcom.ibm.cloud.eventnotifications.destination.androidと入力し、**「アプリの登録」**をクリックします。

    ![アプリ登録](images/en-migration-firebase-addapp.png "プロジェクト設定*" caption-side="bottom"}"){: caption="

  7. google-services.jsonをダウンロードします。 このファイルは、後でアプリケーションを変更するときに使用します。

Android アプリの編集

  1. アプリ・モジュールに Firebasegoogle-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. コード内のインポート・ステートメントを変更します。 新しいパッケージ名は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などの追加フィールドがあります。

    apikeyfor 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 アプリケーションのタイプ Apple Push Notification (APNs) の宛先を作成します。 P12 または P8 とそれらの構成を提供します。

iOSを作成するiOSデスティネーション
を作成する

iOS アプリケーションの編集

BMPush から ENPushDestination にマイグレーションするには、以下のステップを実行します。

  1. インポート・ステートメントの変更

    // 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などの追加フィールドがあります。 apikeyfor 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 ?? "")
         }
      
    • 登録にユーザー 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 アプリケーションの変更

新しい Event Notificationsを使用するようにWebアプリのソースコードを修正する。SDKを変更します。 既存の Push Notifications サービス WebPush SDKを Event Notificationsに置き換えます。 WebPush SDKに置き換えます。

Web 宛先の作成

Chrome 宛先

Web アプリの Chrome Push Notification タイプの宛先を作成します。 ウェブサイトの URLと FCMサーバーキーを入力してください。

クローム宛先を作成{: caption="を作成クローム" caption-side="bottom"}を作成クローム宛先を作成

Firefox の宛先

Web アプリの Firefox Push Notification タイプの宛先を作成します。 ウェブサイトの URLを入力してください。

Firefoxを作成するFirefoxデスティネーション
を作成する

Safari 宛先

Web アプリ用に Safari Push Notification タイプの宛先を作成します。 ウェブサイト名、ウェブサイトプッシュID、ウェブサイト URL、 URL フォーマット文字列、 p12 ファイル、パスワード、アイコンを入力してください。

Safariの目的地
Safariの目的地
を作成する

Web アプリケーションの編集

以下の手順を使用して、最新の SDK で Web アプリケーションを更新します。

  1. インポート・ステートメントを変更してください。

       // 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

    • 登録にユーザー ID を使用している場合

      // 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.jsSDK を使用している場合

既存の Node SDK を新しい IBM Cloud® Event Notifications SDK にマイグレーションします。 新しいノード Admin 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フィールドが削除されました。 alertフィールド、urlフィールドは、ibmenfcmbodyの一部です
  • settings->gcmibmenfcmbodyに置き換えられます

ibmenpushtoフィールドは、プッシュ API のtargetと同じ 4 つの値を取ることができます

  1. tags-タグ名の配列
  2. user_ids-ユーザー ID の配列
  3. fcm_devices-デバイス ID の配列
  4. platforms-ターゲット・デバイス・プラットフォーム

ibmenfcmbodyフィールドには、サービスの設定-> gcmfield のすべてのフィールドが含まれますが、以下の変更点があります。

  1. すべてのフィールドは、キャメル・ケースではなく、スネーク・ケースに入っています。 例えば、interactiveCategoryinteractive_categoryです。
  2. チャネルおよびチャネル・グループ Push Notifications はサポートされていません。

Push Notifications サービスから IBM Cloud® Event Notifications サービスへのデータのマイグレーション

push-ja-migration-tool を使用して、デバイスとタグ・サブスクリプションのデータを Push Notifications サービスから IBM Cloud® Event Notifications サービスにマイグレーションできます。

アプリの新規バージョンをリリースします

統合が完了したら、アプリの新しいバージョンをリリースします。 新しいバージョンでは、通知を送信してデバイスを再度登録する権限をユーザーに要求します。 オーバーラップするウィンドウで、ユーザー集団が古いバージョンのアプリケーションから新しいバージョンにマイグレーションするときに、既存の Push Notifications 環境と新しい IBM Cloud® Event Notifications 環境に通知を送信しなければならない場合があります。