プラットフォーム間でメッセージをカスタマイズする

Firebase Admin SDKFCM v1 HTTP API を使用すると、メッセージ リクエストで message オブジェクト内のすべてのフィールドを設定できます。これには、次のものが含まれます。

  • メッセージを受け取るすべてのアプリ インスタンスによって解釈される共通のフィールド セット。
  • AndroidConfigWebpushConfig など、プラットフォーム固有のフィールド セット。指定されたプラットフォームで実行されているアプリ インスタンスによってのみ解釈されます。

プラットフォーム固有のブロックを使用すると、受信時に各種プラットフォームで正しく処理されるように、メッセージを柔軟にカスタマイズできます。FCM バックエンドにより、指定されたすべてのパラメータに従って、メッセージがプラットフォームごとにカスタマイズされます。

共通フィールドを使用する場合

次の場合は共通フィールドを使用します。

  • 任意のプラットフォームにフィールドを送信する
  • トピックにメッセージを送信する

プラットフォームに関係なく、すべてのアプリ インスタンスは次の共通フィールドを解釈できます。

プラットフォーム固有のフィールドを使用する場合

次の場合はプラットフォーム固有のフィールドを使用します。

  • 特定のプラットフォームにのみフィールドを送信する
  • 共通フィールドに加えてプラットフォーム固有のフィールドを送信する

特定のプラットフォームだけに値を送信する場合は、プラットフォーム固有のフィールドを使用してください。たとえば、Android を除いて Apple プラットフォームとウェブのみに通知を送信するには、2 つの異なるフィールド セット(Apple 用とウェブ用に 1 つずつ)を使用する必要があります。

特定の配信オプションを持つメッセージを送信する場合は、プラットフォーム固有のフィールドを使用してそれらのオプションを設定します。必要に応じてプラットフォームごとに異なる値を指定できます。ただし、すべてのプラットフォームで基本的に同じ値を設定する場合でも、プラットフォーム固有のフィールドを使用する必要があります。これは、プラットフォームごとに値の解釈が多少異なる可能性があるためです。たとえば、Android では秒単位で設定される有効期限が、Apple では有効期日として設定されます。

プラットフォーム固有の配信オプションを使用した通知メッセージ

次の HTTP v1 API 送信リクエストは、すべてのプラットフォームに共通の通知タイトルとコンテンツを送信しますが、プラットフォーム固有のオーバーライドも送信します。リクエストの詳細は次のとおりです。

  • Android およびウェブ プラットフォームに対しては長い有効期間を設定し、APNs(Apple プラットフォーム)メッセージには低い優先順位を設定します。
  • Android および Apple でユーザーが通知をタップしたときの結果を定義するために、それぞれ適切なキー(click_action および category)を設定します。
{
  "message":{
     "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
     "notification":{
       "title":"Match update",
       "body":"Arsenal goal in added time, score is now 3-0"
     },
     "android":{
       "ttl":"86400s",
       "notification"{
         "click_action":"OPEN_ACTIVITY_1"
       }
     },
     "apns": {
       "headers": {
         "apns-priority": "5",
       },
       "payload": {
         "aps": {
           "category": "NEW_MESSAGE_CATEGORY"
         }
       }
     },
     "webpush":{
       "headers":{
         "TTL":"86400"
       }
     }
   }
 }

詳細については、HTTP v1 のリファレンス ページで、メッセージ本文のプラットフォーム固有のブロックで使用できるキーの詳細をご覧ください。メッセージ本文が含まれる送信リクエストの作成方法の詳細については、FCM HTTP v1 API を使用してメッセージを送信するをご覧ください。

色とアイコンのオプションを使用した通知メッセージ

次の例では、送信リクエストはすべてのプラットフォームに共通の通知タイトルとコンテンツを送信しますが、Android デバイスにはプラットフォーム固有のオーバーライドも送信します。

Android の場合、このリクエストによって、Android デバイスに表示する特別なアイコンと色が設定されます。AndroidNotification のリファレンスにあるように、色は #rrggbb 形式で指定します。画像は Android アプリのローカル ドローアブル アイコン リソースである必要があります。

ユーザーのデバイスの視覚効果はおおよそ次のようになります。

2 つのデバイスのシンプルな図(1 つはカスタム アイコンと色を表示)

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: '`$FooCorp` up 1.43% on the day',
    body: 'FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  android: {
    notification: {
      icon: 'stock_ticker_update',
      color: '#7e55c3'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setAndroidConfig(AndroidConfig.builder()
        .setTtl(3600 * 1000)
        .setNotification(AndroidNotification.builder()
            .setIcon("stock_ticker_update")
            .setColor("#f45342")
            .build())
        .build())
    .setApnsConfig(ApnsConfig.builder()
        .setAps(Aps.builder()
            .setBadge(42)
            .build())
        .build())
    .setTopic("industry-tech")
    .build();

Python

message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    android=messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600),
        priority='normal',
        notification=messaging.AndroidNotification(
            icon='stock_ticker_update',
            color='#f45342'
        ),
    ),
    apns=messaging.APNSConfig(
        payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42),
        ),
    ),
    topic='industry-tech',
)

Go

oneHour := time.Duration(1) * time.Hour
badge := 42
message := &messaging.Message{
	Notification: &messaging.Notification{
		Title: "$GOOG up 1.43% on the day",
		Body:  "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
	},
	Android: &messaging.AndroidConfig{
		TTL: &oneHour,
		Notification: &messaging.AndroidNotification{
			Icon:  "stock_ticker_update",
			Color: "#f45342",
		},
	},
	APNS: &messaging.APNSConfig{
		Payload: &messaging.APNSPayload{
			Aps: &messaging.Aps{
				Badge: &badge,
			},
		},
	},
	Topic: "industry-tech",
}

C#

var message = new Message
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Android = new AndroidConfig()
    {
        TimeToLive = TimeSpan.FromHours(1),
        Notification = new AndroidNotification()
        {
            Icon = "stock_ticker_update",
            Color = "#f45342",
        },
    },
    Apns = new ApnsConfig()
    {
        Aps = new Aps()
        {
            Badge = 42,
        },
    },
    Topic = "industry-tech",
};

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title": "`$FooCorp` up 1.43% on the day",
       "body": "FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day."
     },
     "android":{
       "notification":{
         "icon":"stock_ticker_update",
         "color":"#7e55c3"
       }
     }
   }
 }

詳しくは、メッセージ本文のプラットフォーム固有のブロックで使用できるキーの詳細について、HTTP v1 のリファレンス ページをご覧ください。

カスタム イメージを使用した通知メッセージ

次の送信リクエストは、すべてのプラットフォームに共通の通知タイトルを送信しますが、画像も送信します。ユーザーのデバイスの視覚効果はおおよそ次のようになります。

表示された通知内の画像を示す簡単な図

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Sparky says hello!'
  },
  android: {
    notification: {
      imageUrl: 'https://foo.bar.pizza-monster.png'
    }
  },
  apns: {
    payload: {
      aps: {
        'mutable-content': 1
      }
    },
    fcm_options: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  webpush: {
    headers: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Sparky says hello!",
     },
     "android":{
       "notification":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "mutable-content":1
         }
       },
       "fcm_options": {
           "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "webpush":{
       "headers":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     }
   }
 }

詳しくは、メッセージ本文のプラットフォーム固有のブロックで使用できるキーの詳細について、HTTP v1 のリファレンス ページをご覧ください。

クリック アクションが関連付けられている通知メッセージ

次の送信リクエストは、すべてのプラットフォームに共通の通知タイトルを送信しますが、通知へのユーザー操作に応じて、アプリで実行されるアクションも送信します。ユーザーのデバイスの視覚効果の例を次に示します。

ユーザーがタップしてウェブページを開く様子を示す簡単な図

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Breaking News....'
  },
  android: {
    notification: {
      clickAction: 'news_intent'
    }
  },
  apns: {
    payload: {
      aps: {
        'category': 'INVITE_CATEGORY'
      }
    }
  },
  webpush: {
    fcmOptions: {
      link: 'breakingnews.html'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1