여러 플랫폼의 메시지 맞춤설정

Firebase Admin SDKFCM v1 HTTP API를 사용하면 메시지 요청을 통해 message 객체에 제공되는 모든 필드를 설정할 수 있습니다. 여기에는 다음이 포함됩니다.

  • 메시지를 수신한 모든 앱 인스턴스에서 해석하는 공통 필드 모음
  • 지정된 플랫폼에서 실행되는 앱 인스턴스에서만 해석되는 AndroidConfigWebpushConfig와 같은 플랫폼별 필드 집합

플랫폼별 블록을 사용하면 수신 시 올바르게 처리할 수 있도록 다양한 플랫폼에 맞게 메시지를 유연하게 맞춤설정할 수 있습니다. FCM 백엔드는 지정된 모든 매개변수를 고려하여 각 플랫폼에 맞게 메시지를 맞춤설정합니다.

공통 필드를 사용해야 하는 경우

다음 작업에 공통 필드를 사용합니다.

  • 모든 플랫폼에 필드 전송
  • 주제로 메시지 전송

플랫폼에 관계없이 모든 앱 인스턴스가 다음 공통 필드를 해석할 수 있습니다.

플랫폼별 필드를 사용해야 하는 경우

다음 작업을 하려면 플랫폼별 필드를 사용합니다.

  • 특정 플랫폼에만 필드 전송
  • 공통 필드 외에도 플랫폼별 필드 전송

특정 플랫폼에만 값을 보내려면 플랫폼별 필드를 사용하세요. 예를 들어 Android를 제외한 Apple 및 웹 플랫폼에만 알림을 보내려면 Apple 및 웹용으로 각각 하나씩 2개의 개별 필드 모음을 사용해야 합니다.

특정 전송 옵션으로 메시지를 보내는 경우에는 플랫폼별 필드를 사용하여 설정합니다. 원하는 경우 플랫폼별로 다른 값을 지정할 수 있습니다. 여러 플랫폼에 근본적으로 동일한 값을 설정하는 경우에도 플랫폼별 필드를 사용해야 합니다. 그 이유는 각 플랫폼에서 값을 약간씩 다르게 해석할 수 있기 때문입니다. 예를 들어 TTL(수명)이 Android에서는 만료 시간(초 단위)으로 설정되지만 Apple에서는 만료 날짜로 설정됩니다.

플랫폼별 전송 옵션이 있는 알림 메시지

다음 HTTP v1 API 전송 요청은 모든 플랫폼에 공통 알림 제목과 콘텐츠를 보내지만 일부 플랫폼별 재정의도 보냅니다. 이 요청은 특히 다음과 같이 설정합니다.

  • Android와 웹 플랫폼의 경우 TTL(수명)을 길게 설정하지만 APN(Apple 플랫폼) 메시지 우선순위는 낮게 설정합니다.
  • 사용자가 Android와 Apple의 알림을 탭할 경우의 결과를 정의하기 위해 각각 click_actioncategory의 적절한 키를 설정합니다.
{
  "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 앱에 로컬인 드로어블 아이콘 리소스여야 합니다.

다음은 사용자 기기에 표시되는 시각 효과의 예입니다.

두 대의 기기 중 하나는 맞춤 아이콘과 색상을 표시하는 간단한 그림

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