建構應用程式伺服器傳送要求

使用 Firebase Admin SDK 或 FCM 應用程式伺服器通訊協定 您可以建立訊息要求,然後傳送到以下類型的目標:

  • 主題名稱
  • 條件
  • 裝置註冊權杖
  • 裝置群組名稱 (僅限通訊協定)

你可以運用建立的通知酬載傳送訊息 可能是預先定義欄位的資料、自己的使用者定義欄位的資料酬載,或 包含這兩種酬載的訊息。 詳情請見 訊息類型

本頁中的範例會說明如何使用 Firebase Admin SDK (支援 NodeJavaPythonC#、 和 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 會傳回 ID 字串,格式為 projects/{project_id}/messages/{message_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}");
}

傳送訊息至主題

建立主題後,您可以透過訂閱用戶端應用程式執行個體 在用戶端或 server 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

如要傳送訊息給主題的組合, 指定條件,這是一種布林值運算式,可以指定 指定主題。舉例來說,當郵件符合下列條件時, 訂閱 TopicATopicBTopicC 的裝置:

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM 會先評估括號中的任何條件,然後進行評估 運算式則從左到右依序為在上述運算式中,有一位使用者訂閱 任何主題都不會收到訊息。同樣地,如果使用者未 訂閱 TopicA 並未收到訊息。這些組合 收到:

  • TopicATopicB
  • TopicATopicC

條件運算式最多可加入五個主題。

如要傳送至條件:

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,或者是 Node.js 適用的 Firebase Admin SDK 提供舊版通訊協定的更新 遷移至 HTTP v1 API 最先把握舊版 Send 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 傳送

訊息要求必須包含 "direct_boot_ok" : true 鍵的 要求主體的 AndroidConfig 選項。例如:

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 物件。這包括:

  • 一組常用欄位,可供「所有」應用程式執行個體解譯 接收訊息。
  • 平台專屬欄位組合,例如 AndroidConfigWebpushConfig 只由在指定平台上運作的應用程式執行個體解譯

平台特定區塊可讓您靈活自訂 以確保能在收到更新時正確處理 FCM 後端會將所有指定的參數納入考量,然後自訂 訊息。

使用常用欄位的時機

如有下列情況,請使用常用欄位:

  • 指定所有平台上的應用程式執行個體 (Apple、Android 和網頁)
  • 傳送訊息至主題

所有應用程式執行個體 (無論平台為何) 都可以解讀下列常見元素 欄位:

使用平台專屬欄位的時機

使用平台專屬欄位執行下列操作:

  • 僅將欄位傳送至特定平台
  • 除了常用欄位以外,也傳送平台專屬欄位

如果您只想將值傳送到特定平台,請不要使用 常用欄位;使用平台專屬欄位例如傳送通知 只能在 Apple 平台和網路上使用,而不適用於 Android 平台,您 欄位,一個用於 Apple,另一個用於網頁。

您傳送的特定訊息 配送選項 就必須使用平台專屬的欄位來設定這些欄位 您可以為每個平台指定不同的值 您期望的行為但即使您想為各個群組 平台,您必須使用平台專屬欄位。這是因為每個平台 這個值可能無法以略有方式解讀 在 Android 裝置上設為到期時間 (以秒為單位),在 Apple 上則設為 到期日

範例:含有顏色和圖示選項的通知訊息

這個範例傳送要求會將常見的通知標題和內容傳送給所有人員 但也會將部分平台專屬的覆寫值傳送至 Android 裝置。

如果是 Android,要求會設定 Android 裝置顯示的特殊圖示和顏色。如 AndroidNotification 的參考資料所述, 顏色是以 #rrggbb 格式指定,而且圖片必須是可繪項目 圖示資源。

以下是使用者裝置視覺效果的概略說明:

簡單的兩部裝置的繪圖,其中一部顯示自訂圖示和顏色

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 參考說明文件 ,完整瞭解 Ad Exchange 平台中 訊息內文。

範例:含有自訂圖片的通知訊息

以下範例傳送要求會將通用通知標題傳送至所有平台,但同時也會傳送圖片。以下是 使用者裝置上的視覺效果:

在顯示通知中顯示圖片的簡易繪圖功能

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 參考說明文件 ,完整瞭解 Ad Exchange 平台中 訊息內文。

範例:含有相關點擊動作的通知訊息

在以下示例中,傳送要求會將常見的通知標題傳送給 但它也會促使應用程式為了回應 使用者與通知互動的體驗。以下是使用者裝置視覺效果的概略說明:

使用者輕觸開啟網頁的簡易繪圖

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 參考說明文件 ,完整瞭解 Ad Exchange 平台中 訊息內文。

範例:含有本地化選項的通知訊息

以下範例傳送要求會傳送本地化選項,以供用戶端顯示本地化訊息。 以下是使用者裝置視覺效果的概略說明:

簡單插圖:兩部裝置顯示英文和西班牙文文字

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 參考說明文件 ,完整瞭解 Ad Exchange 平台中 訊息內文。

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"
      }
    ]
   }
}

請注意,兩則訊息的代碼和狀態相同,但 details 陣列包含不同型別的值。第一個範例是 type.googleapis.com/google.rpc.BadRequest 類型,表示要求值發生錯誤。第二個為 type.googleapis.com/google.firebase.fcm.v1.FcmError 類型的範例發生 FCM 相關錯誤。針對許多錯誤,details 陣列會包含偵錯及尋找解決方法的資訊。

下表列出了 FCM v1 REST API 錯誤代碼和 這些屬性的說明。

錯誤代碼 說明及解決步驟
UNSPECIFIED_ERROR沒有有關這個錯誤的詳細資訊。
INVALID_ARGUMENT (HTTP 錯誤代碼 = 400) 要求參數無效。系統會傳回 google.rpc.BadRequest 類型的擴充功能,以指出哪個欄位無效。 可能的原因包括註冊無效、套件名稱無效、訊息太大、資料金鑰無效、存留時間無效或其他無效參數。
註冊無效:檢查傳遞至伺服器的註冊權杖格式。請確定這個 ID 與用戶端應用程式註冊 FCM 後收到的註冊權杖相符。請勿截斷符記或新增其他字元。
套件名稱無效:請確認訊息傳送至註冊權杖,其套件名稱與要求中傳送的值相符。
「郵件太大」:確認訊息內含的酬載資料總大小未超過 FCM 限制:大部分訊息為 4096 個位元組,或是訊息傳至主題的 2048 個位元組。這包括鍵和值。
資料鍵無效:請確認酬載資料不包含 FCM 內部使用的鍵 (例如 from 或 gcm,或是任何以 google 開頭的值)。請注意,FCM 也會使用部分字詞 (例如 fold_key),但酬載中允許使用這些字詞,此時 FCM 值將覆寫酬載值。
存留時間無效:檢查 TTl 中使用的值是否為整數,代表介於 0 至 2,419,200 (4 週) 之間的時間長度 (以秒為單位)。
參數無效:請確認提供的參數名稱和類型正確無誤。
UNREGISTERED (HTTP 錯誤代碼 = 404) 應用程式執行個體已從 FCM 取消註冊。這表示使用的權杖已失效,必須改用新的權杖。 這個錯誤的原因可能是缺少註冊權杖或未註冊權杖。
缺少註冊資訊:如果訊息的目標為 token 值,請確認要求包含註冊符記。
未註冊:在許多情況下,現有的註冊權杖可能會失效,包括:
- 如果用戶端應用程式向 FCM 取消註冊。
- 如果用戶端應用程式自動取消註冊,當使用者解除安裝應用程式時,就可能發生這種情況。以 iOS 裝置為例,如果 APNs 意見回饋服務將 APNs 權杖回報為無效,
- 如果註冊權杖過期 (例如,Google 可能會決定更新註冊權杖,或 iOS 裝置的 APN 權杖已過期)。
- 如果用戶端應用程式已更新,但尚未設定新版本以接收訊息。
無論是上述何種情況,請從應用程式伺服器中移除這個註冊權杖,並停止使用該權杖傳送訊息。
SENDER_ID_MISMATCH (HTTP 錯誤代碼 = 403) 已驗證的寄件者 ID 與註冊權杖的寄件者 ID 不同。 註冊權杖會與特定一群寄件者相關聯。用戶端應用程式註冊 FCM 時,必須指定哪些寄件者可以傳送訊息。向用戶端應用程式傳送訊息時,請使用其中一個傳送者 ID。如果您改用其他傳送者,現有的註冊權杖將無法運作。
QUOTA_EXCEEDED (HTTP 錯誤代碼 = 429) 超過訊息目標的傳送上限。系統會傳回 google.rpc.QuotaFailure 類型的擴充功能,指出超過的配額。 造成這項錯誤的原因可能是訊息頻率超出配額、超過裝置訊息頻率配額,或是超過主題訊息頻率配額。
訊息傳送率超過上限:訊息傳送率過高。請務必降低您傳送郵件的整體比率。使用指數輪詢時,至少須有 1 分鐘的初始延遲時間,才能重試遭拒的訊息。
超出裝置訊息比率:傳送到特定裝置的訊息頻率過高。請參閱「對單一裝置的訊息傳送頻率限制」一文。請減少傳送至這部裝置的訊息數量,並使用指數輪詢重試傳送。
超出主題訊息比率:傳送給特定主題的訂閱者訊息比率過高。請減少針對這個主題傳送的訊息數量,並使用指數輪詢功能,並設定最短初始延遲時間 (1 分鐘) 來重試傳送。
UNAVAILABLE (HTTP 錯誤代碼 = 503) 伺服器超載。 伺服器無法及時處理要求。重試相同要求,但你必須:
- 如果 FCM 連線伺服器的回應中包含 重試-After 標頭,請採用該標頭。
- 在重試機制中實作指數輪詢。(舉例來說,如果您在第一次重試前等待了 1 秒,請等待至少 2 秒再進行下一次,接著再等待 4 秒,依此類推)。如果您要傳送多封郵件,建議您套用時基誤差。詳情請參閱處理重試。導致問題風險遭拒絕的寄件者。
INTERNAL (HTTP 錯誤代碼 = 500) 發生不明的內部錯誤。 伺服器嘗試處理要求時發生錯誤。按照「處理重試」中的建議,您可以重試相同要求。如果錯誤持續發生,請與 Firebase 支援團隊聯絡。
THIRD_PARTY_AUTH_ERROR (HTTP 錯誤代碼 = 401) APN 憑證或網站推送驗證金鑰無效或遺失。 無法傳送針對 iOS 裝置或網路推送註冊的訊息。檢查開發和正式環境憑證是否有效。

管理員錯誤代碼

下表列出 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 個位元組。至於傳送給主題的訊息, 上限為 2,048 個位元組 總酬載大小包含鍵與值。
messaging/invalid-options 提供的訊息選項物件無效。錯誤訊息應該 包含其他資訊。
messaging/invalid-registration-token 提供的註冊權杖無效。請確認這個名稱與註冊資料相符 用戶端應用程式註冊 FCM 後收到的符記。禁止事項 截斷或加入其他字元。
messaging/registration-token-not-registered 提供的註冊權杖尚未註冊。先前有效的 註冊權杖可能會因為各種原因而遭到取消 包括:
  • 用戶端應用程式已自行從 FCM 取消註冊。
  • 用戶端應用程式已自動取消註冊。發生這種情況可能是因為 使用者解除安裝應用程式;如果是 APNs 意見回饋,則是在 Apple 平台上 服務將 APN 權杖回報為無效。
  • 註冊權杖已過期。舉例來說,Google 可能會決定 更新註冊權杖或 APNs 權杖可能已過期, Apple 裝置。
  • 用戶端應用程式已更新,但新版本未設為 接收訊息。
在所有情況下,請移除這個註冊權杖並停止使用該註冊權杖 傳送訊息。
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 無法傳送指定 Apple 裝置的訊息,因為 必要的 APNs SSL 憑證未上傳或已過期。查看 確保開發憑證和正式版憑證的有效性。
messaging/mismatched-credential 用來驗證這個 SDK 的憑證沒有以下權限: 將訊息傳送到所註冊的對應裝置 產生下一個符記確認憑證和註冊權杖同時屬於 存取同一項 Firebase 專案詳情請見 將 Firebase 新增至應用程式
messaging/authentication-error SDK 無法驗證 FCM 伺服器。務必 以適當的憑證驗證 Firebase Admin SDK 權限以傳送 FCM 訊息。詳情請見 將 Firebase 新增至應用程式
messaging/server-unavailable FCM 伺服器無法及時處理這項要求。請 重試相同要求,但必須:
  • 如果 Retry-After 標頭包含在 且 FCM 連線伺服器的回應。
  • 在重試機制中實作指數輪詢。例如: 如果在第一次重試前等待一秒,請至少等待兩秒 後面的秒數,然後四秒,依此類推如果您是 傳送多則訊息,逐一延遲 避免對 訊息。
系統會將會造成問題風險的寄件者列入黑名單。
messaging/internal-error 嘗試處理 請求。您可以視情況重新要求相同要求 列於上方 messaging/server-unavailable 列。如果 錯誤持續發生,請將問題回報給 Bug Report 支援管道。
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 雲端通訊主題與 向個別裝置或使用者群組傳送訊息。應用程式 伺服器會使用 /topics/yourTopic 之類的值設定 to 鍵。 開發人員可以 選擇任何符合規則運算式的主題名稱: "/topics/[a-zA-Z0-9-_.~%]+"

為了傳送給多個主題的組合,應用程式伺服器必須設定 將 condition 索引鍵 (而不是 to 鍵) 指派給布林條件 指定目標主題。例如,傳送訊息給訂閱的裝置 傳送給 TopicA,以及 TopicBTopicC:

'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)

FCM 會先評估括號中的任何條件,然後 系統會從左到右計算運算式。在上述運算式中, 使用者訂閱任何單一主題 接收訊息。同樣地,未訂閱 TopicA 的使用者 並未收到這則訊息。下列組合可以獲得採用:

  • 主題 A 和主題 B
  • TopicA 和 TopicC

條件運算式最多可包含五個主題,系統支援括號。 支援的運算子:&&||

主題 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 秒 會針對主題傳送要求,傳回成功或失敗的回應。請確認 相應地在要求中設定應用程式伺服器的逾時值。

傳送訊息至裝置群組

使用已淘汰的舊版 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 個相關聯的註冊權杖 。郵件已成功傳送給註冊的其中 1 封 符記回應訊息會列出註冊權杖 (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 個相關聯的註冊憑證, 傳送給所有人:

{
  "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 回應。

如需完整的訊息選項清單,請參閱參考資訊 HTTPXMPP

Firebase Admin SDK 舊版傳送方法

Firebase Admin Node.js SDK 支援傳送方法 (FCM) 訊息,根據 舊版 FCM 伺服器 API。 這些方法接受的引數與 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() 方法會傳回的承諾, MessagingDevicesResponse 物件,其中包含 FCM 的回應。傳回類型具有相同的 傳遞單一註冊符記或註冊陣列時的格式 符記

某些情況下 (例如驗證錯誤或頻率限制) 會導致 無法處理訊息中的快訊在這些情況下,根據 「sendToDevice()」遭到拒絕,但發生錯誤。如需完整的錯誤代碼清單 並附上說明和解決步驟,詳情請參閱 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() 方法會傳回的承諾, MessagingDevicesResponse 物件,其中包含 FCM 的回應。

某些情況下 (例如驗證錯誤或頻率限制) 會導致 無法處理訊息中的快訊在這些情況下,根據 「sendToDeviceGroup()」遭到拒絕,但發生錯誤。如需完整的錯誤代碼清單 並附上說明和解決步驟,詳情請參閱 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 查看可用選項的完整清單