使用 Firebase Admin SDK 或 FCM 应用服务器协议,您可以构建消息请求并将其发送到以下各类目标:
- 主题名称
- 条件
- 设备注册令牌
- 设备组名称(仅限协议)
您可以发送包含通知载荷(由预定义字段组成)的消息、包含数据载荷(由您自己的用户定义字段组成)的消息,或者包含这两种载荷的消息。 如需了解详情,请参阅消息类型。
本页面中的示例说明了如何使用 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);
});
Java
// 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);
Python
# 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)
Go
// 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);
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":{
"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
运行成功后,每种发送方法都将返回一个消息 ID。Firebase Admin SDK 会返回 projects/{project_id}/messages/{message_id}
格式的消息 ID 字符串。HTTP 协议响应为单个 JSON 键:
{
"name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
}
向多台设备发送消息
借助 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');
});
Java
// 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");
Python
# 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))
Go
// 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.SendEachForMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
返回值是令牌列表,与输入令牌的顺序对应。您可以使用此操作检查哪些令牌导致了错误。
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);
}
});
Java
// 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);
}
Python
# 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))
Go
// 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.SendEachForMulticastAsync(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}");
}
向主题发送消息
创建主题后,您可以通过两种方法向主题发送消息:一种是在客户端为客户端应用实例订阅该主题,另一种是使用服务器 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);
});
Java
// 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);
Python
# 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)
Go
// 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);
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" : "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
您最多可以在条件表达式中包含五个主题。
根据条件发送消息:
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);
});
Java
// 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);
Python
# 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)
Go
// 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);
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":{
"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
向设备组发送消息
如需向设备组发送消息,请使用 HTTP v1 API。如果您目前使用已弃用的适用于 HTTP 或 XMPP 的旧版发送 API,或者使用基于旧版协议的任何更低版本的 Firebase Admin SDK for Node.js 向设备组发送消息,我们强烈建议您尽早迁移到 HTTP v1 API。旧版发送 API 将于 2024 年 6 月停用并移除。
向设备组发送消息的过程与向单台设备发送消息十分类似,都使用相同的方法来授权发送请求。将 token
字段设置为组通知键:
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":{
"token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ",
"data":{
"hello": "This is a Firebase Cloud Messaging device group message!"
}
}
}
cURL 命令
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
"data":{
"hello": "This is a Firebase Cloud Messaging device group message!"
},
"token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ"
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
批量发送消息
Admin SDK 支持批量发送消息。您最多可以将 500 条消息组成一个批次,并在单个 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');
});
Java
// 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");
Python
# 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))
Go
// 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.SendEachAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
发送支持直接启动的消息(仅限 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 各使用一组字段。
当您发送包含特定递送选项的消息时,请使用针对具体平台的字段进行设置。 您可以根据需要为每个平台指定不同的值。即使您想为各平台设置的值实质上是相同的,也必须使用针对具体平台的字段。这是因为每种平台对值的解读方式可能会略有不同 - 例如,存留时间在 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);
});
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
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);
});
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":"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 参考文档。
HTTP v1 API 的 REST 错误代码
HTTP v1 API 的 HTTP 错误响应包含错误代码、错误消息和错误状态。它们可能还包含一个 details
数组,其中带有有关错误的更多详细信息。
以下是两个错误响应示例:
示例 1:数据消息中包含无效值的 HTTP v1 API 请求的错误响应
{
"error": {
"code": 400,
"message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "message.data[0].value",
"description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
}
]
}
]
}
}
示例 2:注册令牌无效的 HTTP v1 API 请求的错误响应
{
"error": {
"code": 400,
"message": "The registration token is not a valid FCM registration token",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
"errorCode": "INVALID_ARGUMENT"
}
]
}
}
请注意,这两条消息的代码和状态相同,但详细信息数组包含不同类型的值。第一个示例的类型为 type.googleapis.com/google.rpc.BadRequest
,表示请求值存在错误。第二个示例的类型为 type.googleapis.com/google.firebase.fcm.v1.FcmError
,存在 FCM 特定错误。对于许多错误,详细信息数组包含您调试和找到解决方案所需的信息。
下表列出了 FCM v1 REST API 错误代码及其说明。
错误代码 | 说明和解决步骤 |
---|---|
UNSPECIFIED_ERROR 无法提供有关此错误的更多信息。 |
无。 |
INVALID_ARGUMENT (HTTP 错误代码 = 400)请求参数无效。系统会返回类型为 google.rpc.BadRequest 的扩展程序,以指定哪个字段无效。 |
可能的原因包括注册无效、软件包名称无效、消息过大、数据键无效、TTL 无效或其他参数无效。 注册无效:请检查您传递到服务器的注册令牌的格式。请确保它与客户端应用在注册 FCM 时获得的注册令牌相符。请勿截断令牌或添加其他字符。 软件包名称无效:请确保消息发送至软件包名称与请求中传递的值相匹配的注册令牌。 消息过大:请确保消息中包含的载荷数据的总大小不超过 FCM 限制:大多数消息的上限是 4096 字节;如果是主题消息,则上限为 2048 字节。这包括键和值。 数据键无效:请确保载荷数据不包含由 FCM 内部使用的键(例如 from、gcm 或任何以 google 为前缀的值)。请注意,FCM 使用的某些字词(例如 collapse_key)也允许在载荷中使用,在这种情况下,FCM 值会覆盖载荷值。 TTL 无效:请确保 ttl 中使用的值是表示时长(以秒为单位)的整数值,且介于 0 到 2,419,200(即 4 周)之间。 参数无效:请确保提供的参数具有正确的名称和类型。 |
UNREGISTERED (HTTP 错误代码 = 404)应用实例已从 FCM 取消注册。这通常意味着所使用的令牌不再有效,必须使用新令牌。 |
此错误可能是由于缺少注册令牌或令牌未注册所导致。 缺少注册:如果消息的目标是 token 值,请检查请求是否包含注册令牌。未注册:现有注册令牌在很多情况下都可能会失效,包括: - 客户端应用取消 FCM 注册。 - 客户端应用自动取消注册(用户卸载应用时可能发生此情况)。例如,在 iOS 中,APNs 反馈服务报告称 APNs 令牌无效。 - 注册令牌过期(例如 Google 可能决定更新注册令牌,或者 iOS 设备的 APNs 令牌已过期)。 - 客户端应用已更新,但新版本未配置为接收消息。 对于所有这些情况,请从应用服务器中移除此注册令牌,并停止用其发送消息。 |
SENDER_ID_MISMATCH (HTTP 错误代码 = 403)进行身份验证的发送者 ID 与注册令牌的发送者 ID 不同。 |
一个注册令牌与一组特定的发送者关联。当客户端应用注册 FCM 时,必须指定允许哪些发送者发送消息。在向客户端应用发送消息时,您应当使用这些发送者 ID 之一。如果您改用其他发送者,则现有的注册令牌将不起作用。 |
QUOTA_EXCEEDED (HTTP 错误代码 = 429)超出消息目标的发送上限。系统会返回类型为 google.rpc.QuotaFailure 的扩展程序,以指定超出的配额。 |
超出消息投递率配额、超出设备消息投递率配额或超出主题消息投递率配额可能会导致此错误。 超出消息投递率:消息发送速率过高。您必须降低发送消息的总速率。使用指数退避算法(初始延迟时间至少为 1 分钟)重试被拒绝的消息。 超出设备消息投递率:向特定设备发送消息的速率过高。请参阅向单一设备发送消息的最大速率。请减少发送到此设备的消息数量,并使用指数退避算法重试发送。 超出主题消息投递率:向特定主题的订阅者发送消息的速率过高。请减少针对此主题发送的消息数量,并使用指数退避算法(最小初始延迟时间为 1 分钟)重试发送。 |
UNAVAILABLE (HTTP 错误代码 = 503)服务器过载。 |
服务器无法及时处理请求。重试同一请求,但您必须: - 如果 FCM 连接服务器发出的响应中包含 Retry-After 标头,则应在该标头指明的间隔后重试。 - 在您的重试机制中实现指数退避算法。(例如,如果等待一秒钟后进行第一次重试,则至少要等待两秒钟再进行下一次重试,然后等待四秒钟,依此类推)。如果您要发送多条消息,请考虑应用抖动。如需了解详情,请参阅处理重试。导致出现问题的发送者有可能会被列入拒绝名单。 |
INTERNAL (HTTP 错误代码 = 500)发生了未知内部错误。 |
服务器在尝试处理请求时遇到错误。您可以按照处理重试中的建议重试同一请求。如果错误仍然存在,请联系 Firebase 支持团队。 |
THIRD_PARTY_AUTH_ERROR (HTTP 错误代码 = 401)APNs 证书或 Web 推送身份验证密钥无效或缺失。 |
无法发送以 iOS 设备或 Web 推送注册为目标的消息。请检查您的开发和生产环境凭据是否有效。 |
Admin 错误代码
下表列出了 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 |
返回了未知的服务器错误。如需了解详情,请参阅错误消息中的原始服务器响应。如果您看到此错误,请向我们的错误报告支持渠道报告完整的错误消息。 |
使用旧版应用服务器协议发送消息
如果您目前使用的是旧版协议,请按本部分所示方法构建消息请求。请注意,如果您通过 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-_.~%]+"
。
如需向多个主题的组合发送消息,应用服务器必须将 condition
键(而非 to
键)设为指定目标主题的布尔型条件。例如,如需向已订阅 TopicA
和 TopicB
或 TopicC
的设备发送消息,应设置如下条件:
'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)
FCM 首先对括号中的所有条件求值,然后从左至右对表达式求值。在上述表达式中,只订阅某个单一主题的用户将不会接收到消息。同样地,未订阅 TopicA 的用户也不会接收到消息。订阅下列组合的用户才会接收到消息:
- TopicA 和 TopicB
- TopicA 和 TopicC
您最多可以在条件表达式中添加五个主题,并且可使用括号。支持的运算符:&&
、||
。
主题 HTTP POST 请求
发送至一个主题:
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
发送至已订阅“dogs”或“cats”主题的设备:
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>
发送至已订阅“dogs”或“cats”主题的设备:
<message id=""> <gcm xmlns="google:mobile:data"> </gcm> </message>
主题 XMPP 响应
// Success example: { "message_id": "1023456" } // failure example: { "error": "TopicsMessageRateExceeded" }
FCM 服务器对主题发送请求返回成功或失败响应前,可能会有最长 30 秒的延迟。请务必在请求中相应地设置应用服务器的超时值。
向设备组发送消息
使用已弃用的旧版 API 向设备组发送消息与向单台设备发送消息十分类似。您需要将 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 个关联的注册令牌。消息仅成功发送至其中一个注册令牌。响应消息列出了未收到消息的注册令牌 (registration_ids
):
{ "success":1, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
当消息未能发送至与某个 notification_key
关联的一个或多个注册令牌时,应用服务器应按退避时间重试。
如果服务器尝试向没有成员的设备组发送消息,则响应如下所示(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 个关联的注册令牌,且消息已成功发送至这 3 个令牌:
{ "from": "aUniqueKey", "message_type": "ack", "success": 3, "failure": 0, "message_id": "m-1366082849205" }
以下是一个“部分成功”的示例:notification_key
有 3 个关联的注册令牌。消息仅成功发送至其中一个注册令牌。响应消息列出了未收到消息的注册令牌:
{ "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()
方法将返回一个 promise,由包含 FCM 响应的 MessagingDevicesResponse
对象来解析。无论传递单个注册令牌还是一个包含注册令牌的数组,返回类型的格式都是相同的。
有些情况(如身份验证错误或速率限制)会导致整个消息无法处理。在这些情况下,sendToDevice()
返回的 promise 将被拒绝并报错。如需查看错误代码的完整列表(包括说明和解决步骤),请参阅 Admin FCM API 错误。
向设备组发送消息
借助 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()
方法将返回一个 promise,由包含 FCM 响应的 MessagingDevicesResponse
对象来解析。
有些情况(如身份验证错误或速率限制)会导致整个消息无法处理。在这些情况下,sendToDeviceGroup()
返回的 promise 将被拒绝并报错。如需查看错误代码的完整列表(包括说明和解决步骤),请参阅 Admin FCM API 错误。
定义消息载荷
上述基于 FCM 旧版协议的方法允许将消息载荷作为其第二个参数,并支持通知消息和数据消息。您可以创建一个含有 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 旧版协议的方法接受第三个参数(可选),用于指定消息的一些选项。例如,以下示例会向设备发送将于 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
的参考文档。