สร้างเซิร์ฟเวอร์แอปส่งคำขอ

เมื่อใช้โปรโตคอลเซิร์ฟเวอร์แอป Firebase Admin SDK หรือ FCM คุณจะสร้างคำขอข้อความและส่งไปยังเป้าหมายประเภทต่อไปนี้ได้

  • ชื่อกระทู้
  • เงื่อนไข
  • โทเค็นการลงทะเบียนอุปกรณ์
  • ชื่อกลุ่มอุปกรณ์ (โปรโตคอลเท่านั้น)

คุณสามารถส่งข้อความที่มีเพย์โหลดการแจ้งเตือนซึ่งประกอบด้วยฟิลด์ที่กำหนดไว้ล่วงหน้า เพย์โหลดข้อมูลของฟิลด์ที่คุณกำหนดเอง หรือข้อความที่มีเพย์โหลดทั้งสองประเภท ดู ประเภทข้อความ สำหรับข้อมูลเพิ่มเติม

ตัวอย่างในหน้านี้แสดงวิธีส่งข้อความแจ้งเตือนโดยใช้ Firebase Admin SDK (ซึ่งรองรับ Node , Java , Python , C# และ Go ) และ โปรโตคอล v1 HTTP นอกจากนี้ยังมีคำแนะนำสำหรับการส่งข้อความผ่าน โปรโตคอล HTTP และ XMPP รุ่น เก่าที่เลิกใช้งานแล้ว

ส่งข้อความไปยังอุปกรณ์เฉพาะ

หากต้องการส่งไปยังอุปกรณ์เฉพาะเพียงเครื่องเดียว ให้ส่งโทเค็นการลงทะเบียนของอุปกรณ์ตามที่แสดง ดูข้อมูลการตั้งค่าไคลเอนต์สำหรับแพลตฟอร์มของคุณเพื่อเรียนรู้เพิ่มเติมเกี่ยวกับโทเค็นการลงทะเบียน

โหนด 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)

ค#

// 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 -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

เมื่อสำเร็จ วิธีการส่งแต่ละวิธีจะส่งคืนรหัสข้อความ Firebase Admin SDK ส่งคืนสตริงรหัสในรูปแบบ projects/{project_id}/messages/{message_id} การตอบสนองโปรโตคอล HTTP เป็นคีย์ JSON เดียว:

    {
      "name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
    }

ส่งข้อความไปยังอุปกรณ์หลายเครื่อง

Admin FCM APIs ช่วยให้คุณมัลติคาสต์ข้อความไปยังรายการโทเค็นการลงทะเบียนอุปกรณ์ คุณสามารถระบุได้ถึง 500 โทเค็นการลงทะเบียนอุปกรณ์ต่อการเรียกใช้

โหนด 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)

ค#

// 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");

ค่าส่งกลับเป็นรายการของโทเค็นที่สอดคล้องกับลำดับของโทเค็นอินพุต สิ่งนี้มีประโยชน์เมื่อคุณต้องการตรวจสอบว่าโทเค็นใดทำให้เกิดข้อผิดพลาด

โหนด 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)
}

ค#

// 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 ของคุณ สำหรับข้อมูลเบื้องหลังและการตั้งค่าที่สำคัญ

ในตรรกะการส่งของคุณที่แบ็กเอนด์ ให้ระบุชื่อหัวข้อที่ต้องการตามที่แสดง:

โหนด 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)

ค#

// 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 -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

คุณสามารถใส่หัวข้อในนิพจน์เงื่อนไขได้สูงสุดห้าหัวข้อ

หากต้องการส่งไปยังเงื่อนไข:

โหนด 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)

ค#

// 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 -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 หากคุณกำลังส่งไปยังกลุ่มอุปกรณ์โดยใช้ API การส่งแบบดั้งเดิมที่เลิกใช้แล้วสำหรับ HTTP หรือ XMPP หรือเวอร์ชันเก่าของ Firebase Admin SDK สำหรับ Node.js ตามโปรโตคอลดั้งเดิม เราขอแนะนำอย่างยิ่งให้คุณ ย้ายไปยัง HTTP v1 API โดยเร็วที่สุด API การส่งแบบเดิมจะถูกปิดใช้งานและนำออกในเดือนมิถุนายน 2024

การส่งข้อความไปยังกลุ่มอุปกรณ์จะคล้ายกับการส่งข้อความไปยังอุปกรณ์แต่ละเครื่อง โดยใช้วิธีเดียวกันในการ ให้สิทธิ์คำขอส่ง ตั้งค่า token เค็นเป็นคีย์การแจ้งเตือนกลุ่ม:

พักผ่อน

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 -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

ส่งข้อความเป็นชุด

REST API และ Admin SDK รองรับการส่งข้อความเป็นกลุ่ม คุณสามารถจัดกลุ่มข้อความได้สูงสุด 500 ข้อความเป็นแบทช์เดียว และส่งทั้งหมดในการเรียก API ครั้งเดียว พร้อมการปรับปรุงประสิทธิภาพที่เหนือกว่าการส่งคำขอ HTTP แยกต่างหากสำหรับแต่ละข้อความ

คุณลักษณะนี้สามารถใช้เพื่อสร้างชุดข้อความที่กำหนดเองและส่งไปยังผู้รับต่างๆ รวมถึงหัวข้อหรือโทเค็นการลงทะเบียนอุปกรณ์เฉพาะ ใช้คุณสมบัตินี้ ตัวอย่างเช่น เมื่อคุณต้องการส่งข้อความไปยังผู้ชมที่แตกต่างกันพร้อมรายละเอียดที่แตกต่างกันเล็กน้อยในเนื้อหาข้อความ

โหนด 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)

ค#

// 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");

พักผ่อน

สร้างคำขอแบทช์ 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

คำขอข้อความต้องมีคีย์ "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,
    },
}

ส่งโดยใช้ HTTP API ดั้งเดิมของ FCM

คำขอข้อความต้องมีคีย์ "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
}

ข้อความที่ส่งด้วยคีย์นี้ในเนื้อหาคำขอสามารถจัดการได้โดยแอปบนอุปกรณ์ที่อยู่ในโหมดบูตโดยตรง (และเมื่อไม่ได้อยู่ในโหมดนั้น)

ปรับแต่งข้อความข้ามแพลตฟอร์ม

ทั้ง SDK ผู้ดูแลระบบ Firebase และโปรโตคอล FCM v1 HTTP อนุญาตให้คำขอข้อความของคุณตั้งค่าฟิลด์ทั้งหมดที่มีในวัตถุ message ซึ่งรวมถึง:

  • ชุดของฟิลด์ทั่วไปที่อินสแตนซ์ของแอป ทั้งหมด ที่ได้รับข้อความจะตีความ
  • ชุดฟิลด์เฉพาะแพลตฟอร์ม เช่น AndroidConfig และ WebpushConfig ตีความโดยอินสแตนซ์ของแอปที่ทำงานบนแพลตฟอร์มที่ระบุเท่านั้น

บล็อกเฉพาะแพลตฟอร์มช่วยให้คุณมีความยืดหยุ่นในการปรับแต่งข้อความสำหรับแพลตฟอร์มต่างๆ เพื่อให้แน่ใจว่าข้อความจะได้รับการจัดการอย่างถูกต้องเมื่อได้รับ แบ็กเอนด์ FCM จะนำพารามิเตอร์ที่ระบุทั้งหมดมาพิจารณาและปรับแต่งข้อความสำหรับแต่ละแพลตฟอร์ม

เมื่อใดควรใช้ฟิลด์ทั่วไป

ใช้ฟิลด์ทั่วไปเมื่อคุณ:

  • การกำหนดเป้าหมายอินสแตนซ์ของแอปใน ทุก แพลตฟอร์ม — Apple, Android และเว็บ
  • การส่งข้อความไปยังหัวข้อ

อินสแตนซ์ของแอปทั้งหมด โดยไม่คำนึงถึงแพลตฟอร์ม สามารถตีความฟิลด์ทั่วไปต่อไปนี้:

เมื่อใดควรใช้ฟิลด์เฉพาะแพลตฟอร์ม

ใช้ฟิลด์เฉพาะแพลตฟอร์มเมื่อคุณต้องการ:

  • ส่งฟิลด์ไปยังแพลตฟอร์มเฉพาะเท่านั้น
  • ส่งฟิลด์เฉพาะแพลตฟอร์ม นอกเหนือจาก ฟิลด์ทั่วไป

เมื่อใดก็ตามที่คุณต้องการส่งค่าไปยังแพลตฟอร์มใดแพลตฟอร์มหนึ่งเท่านั้น อย่า ใช้ฟิลด์ทั่วไป ใช้ฟิลด์เฉพาะแพลตฟอร์ม ตัวอย่างเช่น หากต้องการส่งการแจ้งเตือนไปยังแพลตฟอร์มและเว็บของ Apple เท่านั้น แต่จะส่งไปยัง Android ไม่ได้ คุณต้องใช้ฟิลด์สองชุดแยกกัน ชุดหนึ่งสำหรับ Apple และอีกหนึ่งชุดสำหรับเว็บ

เมื่อคุณส่งข้อความด้วย ตัวเลือกการส่ง เฉพาะ ให้ใช้ฟิลด์เฉพาะแพลตฟอร์มเพื่อตั้งค่า คุณสามารถระบุค่าที่แตกต่างกันสำหรับแต่ละแพลตฟอร์มได้หากต้องการ อย่างไรก็ตาม แม้ว่าคุณจะต้องการตั้งค่าโดยพื้นฐานให้เหมือนกันในทุกแพลตฟอร์ม คุณก็ต้องใช้ฟิลด์เฉพาะแพลตฟอร์ม ทั้งนี้เนื่องจากแต่ละแพลตฟอร์มอาจตีความค่าแตกต่างกันเล็กน้อย ตัวอย่างเช่น เวลาที่จะใช้งานบน Android ถูกกำหนดเป็นเวลาหมดอายุเป็นวินาที ในขณะที่ Apple ถูกกำหนดเป็น วัน หมดอายุ

ตัวอย่าง: ข้อความแจ้งเตือนพร้อมตัวเลือกสีและไอคอน

คำขอส่งตัวอย่างนี้ส่งชื่อการแจ้งเตือนทั่วไปและเนื้อหาไปยังทุกแพลตฟอร์ม แต่ยังส่งการแทนที่เฉพาะบางแพลตฟอร์มไปยังอุปกรณ์ Android

สำหรับ Android คำขอจะตั้งค่าไอคอนและสีพิเศษเพื่อแสดงบนอุปกรณ์ Android ตามที่ระบุไว้ในข้อมูลอ้างอิงสำหรับ AndroidNotification มีการระบุสีในรูปแบบ #rrggbb และรูปภาพต้องเป็นทรัพยากรไอคอนที่วาดได้ภายในเครื่องของแอป Android

นี่คือค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:

การวาดอุปกรณ์สองเครื่องอย่างง่าย โดยเครื่องหนึ่งแสดงไอคอนและสีแบบกำหนดเอง

โหนด 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",
}

ค#

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 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ

ตัวอย่าง: ข้อความแจ้งเตือนพร้อมรูปภาพที่กำหนดเอง

ตัวอย่างต่อไปนี้ส่งคำขอส่งชื่อการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ยังส่งรูปภาพด้วย นี่คือค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:

การวาดภาพอย่างง่ายในการแจ้งเตือนการแสดงผล

โหนด 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 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ

ตัวอย่าง: ข้อความแจ้งเตือนที่มีการคลิกที่เกี่ยวข้อง

ตัวอย่างต่อไปนี้ส่งคำขอส่งชื่อการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ยังส่งการดำเนินการสำหรับแอปเพื่อตอบสนองต่อผู้ใช้ที่โต้ตอบกับการแจ้งเตือน นี่คือค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:

การวาดภาพง่ายๆ ของผู้ใช้แตะเปิดหน้าเว็บ

โหนด 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 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ

ตัวอย่าง: ข้อความแจ้งเตือนพร้อมตัวเลือกการแปล

ตัวอย่างต่อไปนี้ส่งคำขอส่งตัวเลือกการแปลสำหรับไคลเอนต์เพื่อแสดงข้อความแปล นี่คือค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:

การวาดภาพอย่างง่ายของอุปกรณ์สองเครื่องที่แสดงข้อความเป็นภาษาอังกฤษและสเปน

โหนด 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 ไม่ได้ลงทะเบียนโทเค็นการลงทะเบียนที่ระบุ โทเค็นการลงทะเบียนที่ถูกต้องก่อนหน้านี้สามารถยกเลิกการลงทะเบียนได้ด้วยเหตุผลหลายประการ รวมถึง:
  • แอปไคลเอนต์ยกเลิกการลงทะเบียนจาก FCM
  • แอปไคลเอ็นต์ไม่ได้ลงทะเบียนโดยอัตโนมัติ กรณีนี้อาจเกิดขึ้นได้หากผู้ใช้ถอนการติดตั้งแอปพลิเคชัน หรือบนแพลตฟอร์มของ Apple หาก APNs Feedback Service รายงานว่าโทเค็น APNs ไม่ถูกต้อง
  • โทเค็นการลงทะเบียนหมดอายุ ตัวอย่างเช่น Google อาจตัดสินใจรีเฟรชโทเค็นการลงทะเบียน หรือโทเค็น APN อาจหมดอายุสำหรับอุปกรณ์ 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 ในแอปของคุณ สำหรับเอกสารเกี่ยวกับวิธีตรวจสอบสิทธิ์ Firebase Admin SDK
messaging/authentication-error SDK ไม่สามารถรับรองความถูกต้องกับเซิร์ฟเวอร์ FCM ตรวจสอบว่าคุณตรวจสอบสิทธิ์ Firebase Admin SDK ด้วยข้อมูลประจำตัวที่มีสิทธิ์ที่เหมาะสมในการส่งข้อความ FCM ดู เพิ่ม Firebase ในแอปของคุณ สำหรับเอกสารเกี่ยวกับวิธีตรวจสอบสิทธิ์ Firebase Admin SDK
messaging/server-unavailable เซิร์ฟเวอร์ FCM ไม่สามารถประมวลผลคำขอได้ทันเวลา คุณควรลองคำขอเดิมอีกครั้ง แต่คุณต้อง:
  • ให้เกียรติส่วนหัว Retry-After หากรวมอยู่ในการตอบสนองจาก FCM Connection Server
  • ใช้ exponential back-off ในกลไกการลองใหม่ของคุณ ตัวอย่างเช่น หากคุณรอหนึ่งวินาทีก่อนที่จะลองใหม่ครั้งแรก ให้รออย่างน้อยสองวินาทีก่อนที่จะลองครั้งถัดไป จากนั้นให้รอสี่วินาที ไปเรื่อยๆ หากคุณกำลังส่งข้อความหลายข้อความ ให้เลื่อนแต่ละข้อความให้ช้าลงด้วยจำนวนสุ่มเพิ่มเติมเพื่อหลีกเลี่ยงการออกคำขอใหม่สำหรับข้อความทั้งหมดในเวลาเดียวกัน
ผู้ส่งที่ทำให้เกิดปัญหาเสี่ยงต่อการถูกขึ้นบัญชีดำ
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 จะไม่ได้รับข้อความ ชุดค่าผสมเหล่านี้จะได้รับ:

  • หัวข้อ 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"
}

คาดว่าจะมีความล่าช้าสูงสุด 30 วินาทีก่อนที่เซิร์ฟเวอร์ FCM จะส่งคืนการตอบสนองที่สำเร็จหรือล้มเหลวต่อคำขอส่งหัวข้อ ตรวจสอบให้แน่ใจว่าได้ตั้งค่าการหมดเวลาของเซิร์ฟเวอร์แอปในคำขอให้สอดคล้องกัน

ส่งข้อความไปยังกลุ่มอุปกรณ์

การส่งข้อความไปยังกลุ่มอุปกรณ์โดยใช้ 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 ไม่สามารถส่งไปยังอุปกรณ์ทั้งหมดในกลุ่ม เซิร์ฟเวอร์แอปจะได้รับการตอบกลับที่ไม่แน่นอน

สำหรับรายการตัวเลือกข้อความทั้งหมด โปรดดูข้อมูลอ้างอิงสำหรับโปรโตคอลเซิร์ฟเวอร์การเชื่อมต่อที่คุณเลือก HTTP หรือ XMPP

วิธีการส่งแบบดั้งเดิมของ Firebase Admin SDK

Firebase Admin Node.js SDK รองรับวิธีการส่งข้อความ (FCM) ตาม API เซิร์ฟเวอร์ FCM เดิม เมธอดเหล่านี้ยอมรับอาร์กิวเมนต์ที่แตกต่างกันเมื่อเทียบกับเมธอด send() คุณควรใช้เมธอด send() ทุกครั้งที่ทำได้ และใช้วิธีการที่อธิบายไว้ในหน้านี้เมื่อส่งข้อความไปยังอุปกรณ์แต่ละเครื่องหรือกลุ่มอุปกรณ์เท่านั้น

ส่งไปยังอุปกรณ์แต่ละเครื่อง

คุณสามารถส่งโทเค็นการลงทะเบียนไปยังเมธอด sendToDevice() เพื่อส่งข้อความไปยังอุปกรณ์นั้น:

โหนด 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() ยังสามารถส่งข้อความ แบบหลายผู้รับ (นั่นคือ ข้อความไปยังอุปกรณ์หลายเครื่อง) โดยผ่านอาร์เรย์ของโทเค็นการลงทะเบียน แทนที่จะเป็นเพียงโทเค็นการลงทะเบียนเดียว:

โหนด 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() ช่วยให้คุณส่งข้อความไปยังกลุ่มอุปกรณ์โดยระบุคีย์การแจ้งเตือนสำหรับกลุ่มอุปกรณ์นั้น:

โหนด 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 ชั่วโมง:

โหนด 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 สำหรับรายการตัวเลือกที่มีอยู่ทั้งหมด