Firebase Admin SDK または FCM アプリ サーバー プロトコルを使用して、メッセージ リクエストを作成し、次のタイプのターゲットに送信できます。
- トピック名
- 状態
- デバイス登録トークン
- デバイス グループ名(レガシー プロトコルと Firebase Admin SDK for Node.js のみ)
定義済みフィールドで構成される通知ペイロード、独自のユーザー定義フィールドのデータ ペイロード、または両方のタイプのペイロードを含むメッセージを含むメッセージを送信できます。詳細については、メッセージの種類を参照してください。
このページの例では、Firebase Admin SDK ( Node 、 Java 、 Python 、 C# 、 Goをサポート) とv1 HTTP プロトコルを使用して通知メッセージを送信する方法を示します。従来の HTTP および XMPP プロトコルを介してメッセージを送信するためのガイダンスもあります。
特定のデバイスにメッセージを送信する
単一の特定のデバイスに送信するには、示されているようにデバイスの登録トークンを渡します。登録トークンの詳細については、プラットフォームのクライアント セットアップ情報を参照してください。
Node.js
// This registration token comes from the client FCM SDKs.
const registrationToken = 'YOUR_REGISTRATION_TOKEN';
const message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
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);
});
ジャワ
// This registration token comes from the client FCM SDKs.
String registrationToken = "YOUR_REGISTRATION_TOKEN";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setToken(registrationToken)
.build();
// Send a message to the device corresponding to the provided
// registration token.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
パイソン
# This registration token comes from the client FCM SDKs.
registration_token = 'YOUR_REGISTRATION_TOKEN'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
token=registration_token,
)
# Send a message to the device corresponding to the provided
# registration token.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
行け
// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
log.Fatalf("error getting Messaging client: %v\n", err)
}
// This registration token comes from the client FCM SDKs.
registrationToken := "YOUR_REGISTRATION_TOKEN"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Token: registrationToken,
}
// Send a message to the device corresponding to the provided
// registration token.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
C#
// This registration token comes from the client FCM SDKs.
var registrationToken = "YOUR_REGISTRATION_TOKEN";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Token = registrationToken,
};
// Send a message to the device corresponding to the provided
// registration token.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
残り
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":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"body":"This is an FCM notification message!",
"title":"FCM Message"
}
}
}
cURL コマンド:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
"notification":{
"title":"FCM Message",
"body":"This is an FCM Message"
},
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
成功すると、各 send メソッドはメッセージ ID を返します。 Firebase Admin SDK は、 projects/{project_id}/messages/{message_id}
の形式で ID 文字列を返します。 HTTP プロトコルの応答は、単一の JSON キーです。
{
"name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
}
複数のデバイスにメッセージを送信する
REST API と Admin FCM API を使用すると、メッセージをデバイス登録トークンのリストにマルチキャストできます。呼び出しごとに最大 500 個のデバイス登録トークンを指定できます。
Node.js
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
const message = {
data: {score: '850', time: '2:45'},
tokens: registrationTokens,
};
getMessaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
ジャワ
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
MulticastMessage message = MulticastMessage.builder()
.putData("score", "850")
.putData("time", "2:45")
.addAllTokens(registrationTokens)
.build();
BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
パイソン
# Create a list containing up to 500 registration tokens.
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_N',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
tokens=registration_tokens,
)
response = messaging.send_multicast(message)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))
行け
// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Tokens: registrationTokens,
}
br, err := client.SendMulticast(context.Background(), message)
if err != nil {
log.Fatalln(err)
}
// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)
C#
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
var message = new MulticastMessage()
{
Tokens = registrationTokens,
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
};
var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
残り
HTTP バッチ リクエストを作成します。
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message!"
}
}
}
...
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...",
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message!"
}
}
}
--subrequest_boundary--
要求をファイルに保存します (この例では、batch_request.txt)。次に、cURL コマンドを使用します。
curl --data-binary @batch_request.txt -H 'Content-Type: multipart/mixed; boundary="subrequest_boundary"' -H 'Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA' https://fcm.googleapis.com/batch
Firebase Admin SDK の場合、例に示すように、この操作は内部でsendAll()
API を使用します。戻り値は、応答リストが入力トークンの順序に対応するBatchResponse
です。これは、どのトークンがエラーになったかを確認したい場合に便利です。
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
const message = {
data: {score: '850', time: '2:45'},
tokens: registrationTokens,
};
getMessaging().sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
});
ジャワ
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
MulticastMessage message = MulticastMessage.builder()
.putData("score", "850")
.putData("time", "2:45")
.addAllTokens(registrationTokens)
.build();
BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
if (response.getFailureCount() > 0) {
List<SendResponse> responses = response.getResponses();
List<String> failedTokens = new ArrayList<>();
for (int i = 0; i < responses.size(); i++) {
if (!responses.get(i).isSuccessful()) {
// The order of responses corresponds to the order of the registration tokens.
failedTokens.add(registrationTokens.get(i));
}
}
System.out.println("List of tokens that caused failures: " + failedTokens);
}
パイソン
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_N',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
tokens=registration_tokens,
)
response = messaging.send_multicast(message)
if response.failure_count > 0:
responses = response.responses
failed_tokens = []
for idx, resp in enumerate(responses):
if not resp.success:
# The order of responses corresponds to the order of the registration tokens.
failed_tokens.append(registration_tokens[idx])
print('List of tokens that caused failures: {0}'.format(failed_tokens))
行け
// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Tokens: registrationTokens,
}
br, err := client.SendMulticast(context.Background(), message)
if err != nil {
log.Fatalln(err)
}
if br.FailureCount > 0 {
var failedTokens []string
for idx, resp := range br.Responses {
if !resp.Success {
// The order of responses corresponds to the order of the registration tokens.
failedTokens = append(failedTokens, registrationTokens[idx])
}
}
fmt.Printf("List of tokens that caused failures: %v\n", failedTokens)
}
C#
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
var message = new MulticastMessage()
{
Tokens = registrationTokens,
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
};
var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
if (response.FailureCount > 0)
{
var failedTokens = new List<string>();
for (var i = 0; i < response.Responses.Count; i++)
{
if (!response.Responses[i].IsSuccess)
{
// The order of responses corresponds to the order of the registration tokens.
failedTokens.Add(registrationTokens[i]);
}
}
Console.WriteLine($"List of tokens that caused failures: {failedTokens}");
}
残り
各送信サブ送信は応答を返します。応答は、 --batch_
で始まる応答境界文字列で区切られます。
--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q
Content-Type: application/http
Content-ID: response-
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Vary: Origin
Vary: X-Origin
Vary: Referer
{
"name": "projects/35006771263/messages/0:1570471792141125%43c11b7043c11b70"
}
...
--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q
Content-Type: application/http
Content-ID: response-
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Vary: Origin
Vary: X-Origin
Vary: Referer
{
"name": "projects/35006771263/messages/0:1570471792141696%43c11b7043c11b70"
}
--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q--
トピックにメッセージを送信
トピックを作成したら、クライアント アプリ インスタンスをクライアント側のトピックにサブスクライブするか、サーバー APIを介してトピックにメッセージを送信できます。 FCM の送信リクエストを初めて作成する場合は、重要な背景情報とセットアップ情報について、サーバー環境と FCM のガイドを参照してください。
バックエンドの送信ロジックで、次のように目的のトピック名を指定します。
Node.js
// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';
const message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
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);
});
ジャワ
// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic(topic)
.build();
// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
パイソン
# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
topic=topic,
)
# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
行け
// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Topic: topic,
}
// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
C#
// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
残り
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" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
cURL コマンド:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message": {
"topic" : "foo-bar",
"notification": {
"body": "This is a Firebase Cloud Messaging Topic Message!",
"title": "FCM Message"
}
}
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
トピックの組み合わせにメッセージを送信するには、条件を指定します。これは、ターゲット トピックを指定するブール式です。たとえば、次の条件は、 TopicA
とTopicB
またはTopicC
のいずれかにサブスクライブしているデバイスにメッセージを送信します。
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM は、最初に括弧内の条件を評価し、次に式を左から右に評価します。上記の式では、単一のトピックにサブスクライブしているユーザーはメッセージを受信しません。同様に、 TopicA
に登録していないユーザーはメッセージを受信しません。これらの組み合わせはそれを受け取ります:
-
TopicA
とTopicB
-
TopicA
とTopicC
条件式には最大 5 つのトピックを含めることができます。
条件に送信するには:
Node.js
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';
// See documentation on defining a message payload.
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.'
},
condition: condition
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
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);
});
ジャワ
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
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())
.setCondition(condition)
.build();
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
パイソン
# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"
# See documentation on defining a message payload.
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.',
),
condition=condition,
)
# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
行け
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Condition: condition,
}
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
C#
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
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.",
},
Condition = condition,
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
残り
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":{
"condition": "'dogs' in topics || 'cats' in topics",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
}
cURL コマンド:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"notification": {
"title": "FCM Message",
"body": "This is a Firebase Cloud Messaging Topic Message!",
},
"condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
メッセージのバッチを送信する
REST API および Admin SDK は、バッチでのメッセージの送信をサポートしています。最大 500 個のメッセージを 1 つのバッチにグループ化し、それらすべてを 1 回の API 呼び出しで送信できます。メッセージごとに個別の HTTP リクエストを送信するよりもパフォーマンスが大幅に向上します。
この機能を使用して、カスタマイズされた一連のメッセージを作成し、トピックや特定のデバイス登録トークンを含むさまざまな受信者に送信できます。この機能は、たとえば、メッセージ本文の詳細がわずかに異なる複数の対象者にメッセージを同時に送信する必要がある場合に使用します。
Node.js
// Create a list containing up to 500 messages.
const messages = [];
messages.push({
notification: { title: 'Price drop', body: '5% off all electronics' },
token: registrationToken,
});
messages.push({
notification: { title: 'Price drop', body: '2% off all books' },
topic: 'readers-club',
});
getMessaging().sendAll(messages)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
ジャワ
// Create a list containing up to 500 messages.
List<Message> messages = Arrays.asList(
Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("5% off all electronics")
.build())
.setToken(registrationToken)
.build(),
// ...
Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("2% off all books")
.build())
.setTopic("readers-club")
.build()
);
BatchResponse response = FirebaseMessaging.getInstance().sendAll(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
パイソン
# Create a list containing up to 500 messages.
messages = [
messaging.Message(
notification=messaging.Notification('Price drop', '5% off all electronics'),
token=registration_token,
),
# ...
messaging.Message(
notification=messaging.Notification('Price drop', '2% off all books'),
topic='readers-club',
),
]
response = messaging.send_all(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))
行け
// Create a list containing up to 500 messages.
messages := []*messaging.Message{
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "5% off all electronics",
},
Token: registrationToken,
},
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "2% off all books",
},
Topic: "readers-club",
},
}
br, err := client.SendAll(context.Background(), messages)
if err != nil {
log.Fatalln(err)
}
// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)
C#
// Create a list containing up to 500 messages.
var messages = new List<Message>()
{
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "5% off all electronics",
},
Token = registrationToken,
},
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "2% off all books",
},
Topic = "readers-club",
},
};
var response = await FirebaseMessaging.DefaultInstance.SendAllAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
残り
サブ リクエストのリストを組み合わせて、HTTP バッチ リクエストを作成します。
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message to device 0!"
}
}
}
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"topic":"readers-club",
"notification":{
"title":"Price drop",
"body":"2% off all books"
}
}
}
...
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...",
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message to device N!"
}
}
}
--subrequest_boundary--
返されたBatchResponse
をクエリして、FCM に正常にハンドオフされたメッセージの数を確認できます。また、個々のメッセージの状態を確認するために使用できる応答のリストも公開します。応答の順序は、入力リスト内のメッセージの順序に対応しています。
ダイレクト ブート対応メッセージの送信 (Android のみ)
HTTP v1 またはレガシー HTTP API を使用して、ダイレクト ブート モードでデバイスにメッセージを送信できます。ダイレクト ブート モードでデバイスに送信する前に、クライアント デバイスがダイレクト ブート モードで FCM メッセージを受信できるようにする手順を完了していることを確認してください。
FCM v1 HTTP API を使用して送信する
メッセージ リクエストには、リクエスト本文のAndroidConfig
オプションにキー"direct_boot_ok" : true
を含める必要があります。例えば:
https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
Content-Type:application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
"data": {
"score": "5x1",
"time": "15:10"
},
"android": {
"direct_boot_ok": true,
},
}
FCM レガシー HTTP API を使用して送信する
メッセージ リクエストには、リクエスト本文のトップ レベルにキー"direct_boot_ok" : true
を含める必要があります。例えば:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
"direct_boot_ok" : true
}
リクエスト本文でこのキーを使用して送信されたメッセージは、現在ダイレクト ブート モードになっているデバイスのアプリで処理できます (そのモードでない場合も同様です)。
プラットフォーム間でメッセージをカスタマイズする
Firebase Admin SDK と FCM v1 HTTP プロトコルの両方を使用すると、メッセージ リクエストで、 message
オブジェクトで使用可能なすべてのフィールドを設定できます。これも:
- メッセージを受信するすべてのアプリ インスタンスによって解釈される共通のフィールド セット。
-
AndroidConfig
やWebpushConfig
などのプラットフォーム固有のフィールド セットは、指定されたプラットフォームで実行されているアプリ インスタンスによってのみ解釈されます。
プラットフォーム固有のブロックにより、さまざまなプラットフォームのメッセージを柔軟にカスタマイズして、受信時にメッセージが正しく処理されるようにすることができます。 FCM バックエンドは、指定されたすべてのパラメーターを考慮して、プラットフォームごとにメッセージをカスタマイズします。
共通フィールドを使用する場合
次の場合に共通フィールドを使用します。
- Apple、Android、Web など、すべてのプラットフォームのアプリ インスタンスをターゲットにする
- トピックへのメッセージの送信
プラットフォームに関係なく、すべてのアプリ インスタンスは、次の共通フィールドを解釈できます。
プラットフォーム固有のフィールドをいつ使用するか
次の場合は、プラットフォーム固有のフィールドを使用します。
- フィールドを特定のプラットフォームにのみ送信する
- 共通フィールドに加えてプラットフォーム固有のフィールドを送信する
特定のプラットフォームにのみ値を送信する場合は、共通フィールドを使用しないでください。プラットフォーム固有のフィールドを使用します。たとえば、通知を Apple プラットフォームと Web のみに送信し、Android には送信しない場合は、Apple 用と Web 用の 2 つの別個のフィールド セットを使用する必要があります。
特定の配信オプションを使用してメッセージを送信する場合は、プラットフォーム固有のフィールドを使用して設定します。必要に応じて、プラットフォームごとに異なる値を指定できます。ただし、プラットフォーム間で基本的に同じ値を設定する場合でも、プラットフォーム固有のフィールドを使用する必要があります。これは、プラットフォームごとに値の解釈が若干異なる可能性があるためです。たとえば、time-to-live は、Android では秒単位の有効期限として設定されますが、Apple では有効期限として設定されます。
例: 色とアイコンのオプションを含む通知メッセージ
この送信リクエストの例では、共通の通知タイトルとコンテンツをすべてのプラットフォームに送信しますが、プラットフォーム固有のオーバーライドも 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);
});
ジャワ
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();
パイソン
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',
)
行け
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",
};
残り
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);
});
残り
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);
});
残り
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":"Breaking News...",
},
"android":{
"notification":{
"click_action":"news_intent"
}
},
"apns":{
"payload":{
"aps":{
"category" : "INVITE_CATEGORY"
}
},
},
"webpush":{
"fcm_options":{
"link":"breakingnews.html"
}
}
}
}
メッセージ本文のプラットフォーム固有のブロックで使用できるキーの詳細については、 HTTP v1 リファレンス ドキュメントを参照してください。
例: ローカライズ オプションを含む通知メッセージ
次の送信リクエストの例では、クライアントがローカライズされたメッセージを表示するためのローカライズ オプションを送信します。ユーザーのデバイスでの視覚効果の概算は次のとおりです。
Node.js
var topicName = 'industry-tech';
var message = {
android: {
ttl: 3600000,
notification: {
bodyLocKey: 'STOCK_NOTIFICATION_BODY',
bodyLocArgs: ['FooCorp', '11.80', '835.67', '1.43']
}
},
apns: {
payload: {
aps: {
alert: {
locKey: 'STOCK_NOTIFICATION_BODY',
locArgs: ['FooCorp', '11.80', '835.67', '1.43']
}
}
}
},
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);
});
残り
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":"Tech",
"android":{
"ttl":"3600s",
"notification":{
"body_loc_key": "STOCK_NOTIFICATION_BODY",
"body_loc_args": ["FooCorp", "11.80", "835.67", "1.43"],
},
},
"apns":{
"payload":{
"aps":{
"alert" : {
"loc-key": "STOCK_NOTIFICATION_BODY",
"loc-args": ["FooCorp", "11.80", "835.67", "1.43"],
},
},
},
},
},
}'
メッセージ本文のプラットフォーム固有のブロックで使用できるキーの詳細については、 HTTP v1 リファレンス ドキュメントを参照してください。
管理者エラー コード
次の表に、Firebase Admin FCM API エラー コードとその説明、および推奨される解決手順を示します。
エラーコード | 説明と解決手順 |
---|---|
messaging/invalid-argument | FCM メソッドに無効な引数が指定されました。エラー メッセージには、追加情報が含まれている必要があります。 |
messaging/invalid-recipient | 意図したメッセージ受信者が無効です。エラー メッセージには、追加情報が含まれている必要があります。 |
messaging/invalid-payload | 無効なメッセージ ペイロード オブジェクトが提供されました。エラー メッセージには、追加情報が含まれている必要があります。 |
messaging/invalid-data-payload-key | データ メッセージのペイロードに無効なキーが含まれています。制限されたキーについては、 DataMessagePayload のリファレンス ドキュメントを参照してください。 |
messaging/payload-size-limit-exceeded | 指定されたメッセージ ペイロードが FCM のサイズ制限を超えています。ほとんどのメッセージの制限は 4096 バイトです。トピックに送信されるメッセージの場合、制限は 2048 バイトです。ペイロードの合計サイズには、キーと値の両方が含まれます。 |
messaging/invalid-options | 無効なメッセージ オプション オブジェクトが提供されました。エラー メッセージには、追加情報が含まれている必要があります。 |
messaging/invalid-registration-token | 指定された登録トークンが無効です。クライアント アプリが FCM への登録から受け取る登録トークンと一致することを確認します。文字を切り詰めたり追加したりしないでください。 |
messaging/registration-token-not-registered | 指定された登録トークンは登録されていません。以前に有効だった登録トークンは、次のようなさまざまな理由で登録解除される可能性があります。
|
messaging/invalid-package-name | メッセージは、パッケージ名が指定されたrestrictedPackageName オプションと一致しない登録トークンに宛てられました。 |
messaging/message-rate-exceeded | 特定のターゲットへのメッセージのレートが高すぎます。このデバイスまたはトピックに送信されるメッセージの数を減らし、このターゲットへの送信をすぐに再試行しないでください。 |
messaging/device-message-rate-exceeded | 特定のデバイスへのメッセージのレートが高すぎます。このデバイスに送信されるメッセージの数を減らし、このデバイスへの送信をすぐに再試行しないでください。 |
messaging/topics-message-rate-exceeded | 特定のトピックのサブスクライバーへのメッセージの割合が高すぎます。このトピックに送信されるメッセージの数を減らし、このトピックへの送信をすぐに再試行しないでください。 |
messaging/too-many-topics | 登録トークンは最大数のトピックにサブスクライブされており、これ以上サブスクライブすることはできません。 |
messaging/invalid-apns-credentials | 必要な APNs SSL 証明書がアップロードされていないか、有効期限が切れているため、Apple デバイスを対象とするメッセージを送信できませんでした。開発証明書と本番証明書の有効性を確認してください。 |
messaging/mismatched-credential | この SDK の認証に使用される資格情報には、提供された登録トークンに対応するデバイスにメッセージを送信する権限がありません。認証情報と登録トークンの両方が同じ Firebase プロジェクトに属していることを確認してください。 Firebase Admin SDK を認証する方法に関するドキュメントについては、「アプリに Firebase を追加する」をご覧ください。 |
messaging/authentication-error | SDK は FCM サーバーに対して認証できませんでした。 FCM メッセージを送信するための適切な権限を持つ認証情報を使用して、Firebase Admin SDK を認証していることを確認してください。 Firebase Admin SDK を認証する方法に関するドキュメントについては、「アプリに Firebase を追加する」をご覧ください。 |
messaging/server-unavailable | FCM サーバーは要求を時間内に処理できませんでした。同じリクエストを再試行する必要がありますが、次のことを行う必要があります。
|
messaging/internal-error | リクエストの処理中に FCM サーバーでエラーが発生しました。上記のmessaging/server-unavailable 行に記載されている要件に従って、同じリクエストを再試行できます。エラーが続く場合は、バグ レポートサポート チャネルに問題を報告してください。 |
messaging/unknown-error | 不明なサーバー エラーが返されました。詳細については、エラー メッセージ内の生のサーバー レスポンスを参照してください。このエラーが発生した場合は、エラー メッセージ全体をBug Reportサポート チャネルに報告してください。 |
従来のアプリ サーバー プロトコルを使用してメッセージを送信する
レガシー プロトコルを使用する場合は、このセクションに示すようにメッセージ リクエストを作成します。 HTTP 経由で複数のプラットフォームに送信する場合、v1 プロトコルはメッセージ リクエストを簡素化できることに注意してください。
特定のデバイスにメッセージを送信する
特定のデバイスにメッセージを送信するには、 to
キーを特定のアプリ インスタンスの登録トークンに設定します。登録トークンの詳細については、プラットフォームのクライアント セットアップ情報を参照してください。
HTTP POST リクエスト
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
HTTP レスポンス
{ "multicast_id": 108, "success": 1, "failure": 0, "results": [ { "message_id": "1:08" } ] }
XMPP メッセージ
<message id="">
<gcm xmlns="google:mobile:data">
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
</gcm>
</message>
XMPP レスポンス
<message id=""> <gcm xmlns="google:mobile:data"> { "from":"REGID", "message_id":"m-1366082849205" "message_type":"ack" } </gcm> </message>
XMPP 接続サーバーには、応答用のその他のオプションがいくつか用意されています。サーバー応答フォーマットを参照してください。
ダウンストリーム メッセージをクライアント アプリに送信するときに使用できるメッセージ オプションの完全なリストについては、選択した接続サーバー プロトコル、 HTTPまたはXMPPの参照情報を参照してください。
トピックにメッセージを送信
Firebase Cloud Messaging トピックへのメッセージの送信は、個々のデバイスまたはユーザー グループへのメッセージの送信と非常によく似ています。アプリ サーバーはto
キーに/topics/yourTopic
のような値を設定します。開発者は、正規表現"/topics/[a-zA-Z0-9-_.~%]+"
に一致する任意のトピック名を選択できます。
複数のトピックの組み合わせに送信するには、アプリ サーバーは、( to
キーではなく) condition
キーを、ターゲット トピックを指定するブール条件に設定する必要があります。たとえば、 TopicA
とTopicB
またはTopicC
のいずれかにサブスクライブしているデバイスにメッセージを送信するには、次のようにします。
'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)
FCM は、最初に括弧内の条件を評価し、次に式を左から右に評価します。上記の式では、単一のトピックにサブスクライブしているユーザーはメッセージを受信しません。同様に、TopicA に登録していないユーザーはメッセージを受信しません。これらの組み合わせはそれを受け取ります:
- トピックAとトピックB
- トピックAとトピックC
条件式には最大 5 つのトピックを含めることができ、括弧がサポートされています。サポートされている演算子: &&
、 ||
.
トピック HTTP POST リクエスト
単一のトピックに送信:
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
トピック「犬」または「猫」にサブスクライブしているデバイスに送信:
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
トピックの HTTP 応答
//Success example: { "message_id": "1023456" } //failure example: { "error": "TopicsMessageRateExceeded" }
トピック XMPP メッセージ
単一のトピックに送信:
<message id="">
<gcm xmlns="google:mobile:data">
</gcm>
</message>
トピック「犬」または「猫」にサブスクライブしているデバイスに送信:
<message id=""> <gcm xmlns="google:mobile:data"> </gcm> </message>
トピック XMPP レスポンス
//Success example: { "message_id": "1023456" } //failure example: { "error": "TopicsMessageRateExceeded" }
FCM サーバーがトピック送信要求に対して成功または失敗の応答を返すまでに、最大 30 秒の遅延が予想されます。それに応じて、リクエストでアプリサーバーのタイムアウト値を設定してください。
デバイス グループにメッセージを送信する
デバイス グループへのメッセージの送信は、個々のデバイスへのメッセージの送信と非常によく似ています。 to
パラメータをデバイス グループの一意の通知キーに設定します。ペイロード サポートの詳細については、メッセージ タイプを参照してください。このページの例では、従来の HTTP および XMPP プロトコルでデバイス グループにデータ メッセージを送信する方法を示します。
デバイス グループの HTTP POST 要求
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA { "to": "aUniqueKey", "data": { "hello": "This is a Firebase Cloud Messaging Device Group Message!", } }
デバイス グループの HTTP 応答
「成功」の例を次に示しますnotification_key
には 2 つの登録トークンが関連付けられており、メッセージは両方に正常に送信されました。
{ "success": 2, "failure": 0 }
これは「部分的な成功」の例ですnotification_key
には 3 つの登録トークンが関連付けられています。メッセージは、1 つの登録トークンのみに正常に送信されました。応答メッセージには、メッセージの受信に失敗した登録トークン ( registration_ids
) が一覧表示されます。
{ "success":1, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
notification_key
に関連付けられた 1 つ以上の登録トークンへのメッセージの配信に失敗した場合、アプリ サーバーは再試行の間にバックオフを使用して再試行する必要があります。
サーバーがメンバーを持たないデバイス グループにメッセージを送信しようとすると、応答は次のようになり、成功は 0、失敗は 0 になります。
{ "success": 0, "failure": 0 }
デバイス グループ XMPP メッセージ
<message id=""> <gcm xmlns="google:mobile:data"> { "to": "aUniqueKey", "message_id": "m-1366082849205" , "data": { "hello":"This is a Firebase Cloud Messaging Device Group Message!" } } </gcm> </message>
デバイス グループの XMPP 応答
メッセージがグループ内のいずれかのデバイスに正常に送信されると、XMPP 接続サーバーは ACK で応答します。グループ内のすべてのデバイスに送信されたすべてのメッセージが失敗した場合、XMPP 接続サーバーは NACK で応答します。
「成功」の例を次に示しますnotification_key
には 3 つの登録トークンが関連付けられており、メッセージはそれらすべてに正常に送信されました。
{ "from": "aUniqueKey", "message_type": "ack", "success": 3, "failure": 0, "message_id": "m-1366082849205" }
これは「部分的な成功」の例ですnotification_key
には 3 つの登録トークンが関連付けられています。メッセージは、1 つの登録トークンのみに正常に送信されました。応答メッセージには、メッセージの受信に失敗した登録トークンが一覧表示されます。
{ "from": "aUniqueKey", "message_type": "ack", "success":1, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
FCM 接続サーバーがグループ内のすべてのデバイスへの配信に失敗した場合。アプリ サーバーは nack 応答を受け取ります。
メッセージ オプションの完全なリストについては、選択した接続サーバー プロトコル、 HTTPまたはXMPPの参照情報を参照してください。
Firebase Admin SDK の従来の送信方法
Firebase Admin Node.js SDK は、レガシー FCM サーバー APIに基づいて (FCM) メッセージを送信するためのメソッドをサポートしています。これらのメソッドは、 send()
メソッドとは異なる引数を受け入れます。個々のデバイスまたはデバイス グループにメッセージを送信する場合は、可能な限りsend()
メソッドを使用し、このページで説明されているメソッドのみを使用してください。
個々のデバイスに送信
登録トークンをsendToDevice()
メソッドに渡して、そのデバイスにメッセージを送信できます。
Node.js
// This registration token comes from the client FCM SDKs.
const registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';
// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
data: {
score: '850',
time: '2:45'
}
};
// Send a message to the device corresponding to the provided
// registration token.
getMessaging().sendToDevice(registrationToken, payload)
.then((response) => {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
sendToDevice()
メソッドは、単一の登録トークンではなく、登録トークンの配列を渡すことによって、マルチキャストメッセージ (つまり、複数のデバイスへのメッセージ) を送信することもできます。
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
// ...
'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...'
];
// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
data: {
score: '850',
time: '2:45'
}
};
// Send a message to the devices corresponding to the provided
// registration tokens.
getMessaging().sendToDevice(registrationTokens, payload)
.then((response) => {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
sendToDevice()
メソッドは、FCM からの応答を含むMessagingDevicesResponse
オブジェクトで解決される promise を返します。単一の登録トークンまたは登録トークンの配列を渡す場合、戻り値の型は同じ形式になります。
認証エラーやレート制限などによって、メッセージ全体の処理が失敗する場合があります。このような場合、 sendToDevice()
によって返される promise はエラーで拒否されます。説明と解決手順を含むエラー コードの完全なリストについては、 Admin FCM API Errorsを参照してください。
デバイス グループに送信する
デバイス グループ メッセージングを使用すると、複数のデバイスを 1 つのグループに追加できます。これはトピック メッセージングに似ていますが、グループ メンバーシップがサーバーによってのみ管理されるようにするための認証が含まれています。たとえば、異なる電話モデルに異なるメッセージを送信する場合、サーバーは適切なグループへの登録を追加/削除し、適切なメッセージを各グループに送信できます。デバイス グループ メッセージングは、アプリケーション内で直接ではなく、サーバーからデバイス グループを管理するという点で、トピック メッセージングとは異なります。
アプリ サーバーで従来のXMPPまたはHTTPプロトコルを介してデバイス グループ メッセージングを使用できます。 Node.js 用 Firebase Admin SDKの古いバージョンは、レガシー プロトコルに基づいており、デバイス グループ メッセージング機能も提供します。通知キーに許可されるメンバーの最大数は 20 です。
デバイス グループを作成し、アプリ サーバーまたは Android クライアントを介して通知キーを生成できます。詳細については、デバイス グループの管理を参照してください。
sendToDeviceGroup()
メソッドを使用すると、デバイス グループの通知キーを指定して、デバイス グループにメッセージを送信できます。
Node.js
// See the "Managing device groups" link above on how to generate a
// notification key.
const notificationKey = 'some-notification-key';
// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
data: {
score: '850',
time: '2:45'
}
};
// Send a message to the device group corresponding to the provided
// notification key.
getMessaging().sendToDeviceGroup(notificationKey, payload)
.then((response) => {
// See the MessagingDeviceGroupResponse reference documentation for
// the contents of response.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
sendToDeviceGroup()
メソッドは、FCM からの応答を含むMessagingDevicesResponse
オブジェクトで解決される promise を返します。
認証エラーやレート制限などによって、メッセージ全体の処理が失敗する場合があります。このような場合、 sendToDeviceGroup()
によって返される promise はエラーで拒否されます。説明と解決手順を含むエラー コードの完全なリストについては、 Admin FCM API Errorsを参照してください。
メッセージ ペイロードの定義
FCM レガシー プロトコルに基づく上記のメソッドは、2 番目の引数としてメッセージ ペイロードを受け入れ、通知メッセージとデータ メッセージの両方をサポートします。 data
および/またはnotification
キーを使用してオブジェクトを作成することにより、一方または両方のメッセージ タイプを指定できます。たとえば、さまざまなタイプのメッセージ ペイロードを定義する方法を次に示します。
通知メッセージ
const payload = {
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.'
}
};
データメッセージ
const payload = {
data: {
score: '850',
time: '2:45'
}
};
複合メッセージ
const payload = {
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.'
},
data: {
stock: 'GOOG',
open: '829.62',
close: '635.67'
}
};
通知メッセージのペイロードには、有効なプロパティの事前定義されたサブセットがあり、ターゲットにしているモバイル オペレーティング システムによって若干異なります。完全なリストについては、 NotificationMessagePayload
のリファレンス ドキュメントを参照してください。
データ メッセージ ペイロードは、すべての値が文字列でなければならないなど、いくつかの制限があるカスタム キーと値のペアで構成されます。制限の完全なリストについては、 DataMessagePayload
のリファレンス ドキュメントを参照してください。
メッセージ オプションの定義
FCM レガシー プロトコルに基づく上記のメソッドは、メッセージのいくつかのオプションを指定するオプションの 3 番目の引数を受け入れます。たとえば、次の例では、24 時間後に有効期限が切れる優先度の高いメッセージをデバイスに送信します。
Node.js
// This registration token comes from the client FCM SDKs.
const registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';
// See the "Defining the message payload" section above for details
// on how to define a message payload.
const payload = {
notification: {
title: 'Urgent action needed!',
body: 'Urgent action is needed to prevent your account from being disabled!'
}
};
// Set the message as high priority and have it expire after 24 hours.
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24
};
// Send a message to the device corresponding to the provided
// registration token with the provided options.
getMessaging().sendToDevice(registrationToken, payload, options)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
使用可能なオプションの完全なリストについては、 MessagingOptions
のリファレンス ドキュメントを参照してください。