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

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

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

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

ตัวอย่างในหน้านี้จะแสดงวิธีส่งข้อความแจ้งเตือนโดยใช้ ผู้ดูแลระบบ Firebase SDK (ซึ่งรองรับ โหนด Java Python C# และ Go) และ โปรโตคอล HTTP v1 นอกจากนี้ยังมีคำแนะนำสำหรับการส่งข้อความผ่าน โปรโตคอล 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

เมื่อทำสำเร็จ วิธีการส่งแต่ละวิธีจะแสดงรหัสข้อความ Firebase Admin SDK กลับมาแล้ว สตริงรหัสในรูปแบบ 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}");
}

ส่งข้อความไปยังหัวข้อ

หลังจากสร้างหัวข้อแล้ว ไม่ว่าจะด้วยการสมัครใช้บริการอินสแตนซ์แอปไคลเอ็นต์ หัวข้อในฝั่งไคลเอ็นต์หรือผ่าน 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

หากต้องการส่งข้อความไปยังกลุ่มหัวข้อ ระบุ condition ซึ่งเป็นนิพจน์บูลีนที่ระบุพารามิเตอร์ หัวข้อเป้าหมาย ตัวอย่างเช่น เงื่อนไขต่อไปนี้จะส่งข้อความถึง อุปกรณ์ที่สมัครใช้บริการ TopicA และ TopicB หรือ TopicC

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

FCM จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจึงประเมิน นิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้สมัครรับข้อมูล หัวข้อใดหัวข้อหนึ่งไม่ได้รับข้อความ ในทำนองเดียวกัน ผู้ใช้ที่ไม่ การติดตาม TopicA ไม่ได้รับข้อความ การผสมผสานเหล่านี้ รับเลย

  • TopicA และ TopicB
  • TopicA และ TopicC

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

วิธีส่งไปยังเงื่อนไข

Node.js

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

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

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

ส่งโดยใช้ 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
}

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

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

ทั้ง Firebase Admin SDK และโปรโตคอล HTTP ของ FCM v1 อนุญาตข้อความของคุณ ให้ตั้งค่าฟิลด์ทั้งหมดที่มีอยู่ใน message ออบเจ็กต์ ข้อมูลส่วนตัวดังกล่าวรวมถึงสิ่งต่อไปนี้

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

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

กรณีที่ควรใช้ฟิลด์ทั่วไป

ใช้ฟิลด์ทั่วไปเมื่อคุณทำสิ่งต่อไปนี้

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

อินสแตนซ์ของแอปทั้งหมดไม่ว่าจะเป็นแพลตฟอร์มใดจะตีความอินสแตนซ์ที่พบได้ต่อไปนี้ ฟิลด์:

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

ใช้ฟิลด์เฉพาะแพลตฟอร์มเมื่อต้องการทำสิ่งต่อไปนี้

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

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

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

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

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

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

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

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

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: '`$FooCorp` up 1.43% on the day',
    body: 'FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  android: {
    notification: {
      icon: 'stock_ticker_update',
      color: '#7e55c3'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setAndroidConfig(AndroidConfig.builder()
        .setTtl(3600 * 1000)
        .setNotification(AndroidNotification.builder()
            .setIcon("stock_ticker_update")
            .setColor("#f45342")
            .build())
        .build())
    .setApnsConfig(ApnsConfig.builder()
        .setAps(Aps.builder()
            .setBadge(42)
            .build())
        .build())
    .setTopic("industry-tech")
    .build();

Python

message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    android=messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600),
        priority='normal',
        notification=messaging.AndroidNotification(
            icon='stock_ticker_update',
            color='#f45342'
        ),
    ),
    apns=messaging.APNSConfig(
        payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42),
        ),
    ),
    topic='industry-tech',
)

Go

oneHour := time.Duration(1) * time.Hour
badge := 42
message := &messaging.Message{
	Notification: &messaging.Notification{
		Title: "$GOOG up 1.43% on the day",
		Body:  "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
	},
	Android: &messaging.AndroidConfig{
		TTL: &oneHour,
		Notification: &messaging.AndroidNotification{
			Icon:  "stock_ticker_update",
			Color: "#f45342",
		},
	},
	APNS: &messaging.APNSConfig{
		Payload: &messaging.APNSPayload{
			Aps: &messaging.Aps{
				Badge: &badge,
			},
		},
	},
	Topic: "industry-tech",
}

C#

var message = new Message
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Android = new AndroidConfig()
    {
        TimeToLive = TimeSpan.FromHours(1),
        Notification = new AndroidNotification()
        {
            Icon = "stock_ticker_update",
            Color = "#f45342",
        },
    },
    Apns = new ApnsConfig()
    {
        Aps = new Aps()
        {
            Badge = 42,
        },
    },
    Topic = "industry-tech",
};

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"`$FooCorp` up 1.43% on the day",
       "body":"FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day."
     },
     "android":{
       "notification":{
         "icon":"stock_ticker_update",
         "color":"#7e55c3"
       }
     }
   }
 }

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

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

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

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

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Sparky says hello!'
  },
  android: {
    notification: {
      imageUrl: 'https://foo.bar.pizza-monster.png'
    }
  },
  apns: {
    payload: {
      aps: {
        'mutable-content': 1
      }
    },
    fcm_options: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  webpush: {
    headers: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Sparky says hello!",
     },
     "android":{
       "notification":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "mutable-content":1
         }
       },
       "fcm_options": {
           "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "webpush":{
       "headers":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     }
   }
 }

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

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

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

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

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Breaking News....'
  },
  android: {
    notification: {
      clickAction: 'news_intent'
    }
  },
  apns: {
    payload: {
      aps: {
        'category': 'INVITE_CATEGORY'
      }
    }
  },
  webpush: {
    fcmOptions: {
      link: 'breakingnews.html'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Breaking News...",
     },
     "android":{
       "notification":{
         "click_action":"news_intent"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "category" : "INVITE_CATEGORY"
         }
       },
     },
     "webpush":{
       "fcm_options":{
         "link":"breakingnews.html"
       }
     }
   }
 }

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

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

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

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

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

รหัสข้อผิดพลาด REST สำหรับ HTTP v1 API

การตอบกลับข้อผิดพลาด HTTP สำหรับ HTTP v1 API มีรหัสข้อผิดพลาด ข้อความแสดงข้อผิดพลาด และสถานะข้อผิดพลาด และอาจมีอาร์เรย์ details ที่มีรายละเอียดเพิ่มเติมเกี่ยวกับข้อผิดพลาด

ตัวอย่างการตอบกลับข้อผิดพลาด 2 รายการมีดังนี้

ตัวอย่างที่ 1: การตอบสนองข้อผิดพลาดจากคำขอ HTTP v1 API ที่มีค่าที่ไม่ถูกต้องในข้อความข้อมูล

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

ตัวอย่างที่ 2: การตอบกลับข้อผิดพลาดจากคำขอ HTTP v1 API ที่มีโทเค็นการลงทะเบียนที่ไม่ถูกต้อง

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

โปรดทราบว่าข้อความทั้งสองมีรหัสและสถานะเดียวกัน แต่อาร์เรย์รายละเอียดมีค่าในประเภทเดียวกัน ตัวอย่างแรกมีประเภท type.googleapis.com/google.rpc.BadRequest ซึ่งระบุข้อผิดพลาดในค่าของคำขอ ตัวอย่างที่ 2 ประเภท type.googleapis.com/google.firebase.fcm.v1.FcmError มีข้อผิดพลาดเฉพาะ FCM สำหรับข้อผิดพลาดจำนวนมาก อาร์เรย์รายละเอียดจะมีข้อมูลที่คุณต้องแก้ไขข้อบกพร่องและค้นหาวิธีแก้ไข

ตารางต่อไปนี้แสดงรหัสข้อผิดพลาด API ของ REST v1 ของ FCM และ คำอธิบายของพวกเขา

รหัสข้อผิดพลาด ขั้นตอนคำอธิบายและการแก้ปัญหา
UNSPECIFIED_ERROR ไม่มีข้อมูลเพิ่มเติมเกี่ยวกับข้อผิดพลาดนี้ ไม่มี
INVALID_ARGUMENT (รหัสข้อผิดพลาด HTTP = 400) พารามิเตอร์คำขอไม่ถูกต้อง ส่วนขยายประเภท google.rpc.BadRequest จะแสดงผลเพื่อระบุช่องที่ไม่ถูกต้อง สาเหตุที่เป็นไปได้ ได้แก่ การลงทะเบียนที่ไม่ถูกต้อง, ชื่อแพ็กเกจไม่ถูกต้อง, ข้อความใหญ่เกินไป, คีย์ข้อมูลไม่ถูกต้อง, TTL ไม่ถูกต้อง หรือพารามิเตอร์อื่นๆ ไม่ถูกต้อง
การลงทะเบียนไม่ถูกต้อง: ตรวจสอบรูปแบบของโทเค็นการลงทะเบียนที่คุณส่งไปยังเซิร์ฟเวอร์ ตรวจสอบว่าโทเค็นดังกล่าวตรงกับโทเค็นการลงทะเบียนที่แอปไคลเอ็นต์ได้รับจากการลงทะเบียนกับ FCM อย่าตัดโทเค็นหรือเพิ่มอักขระอื่น
ชื่อแพ็กเกจไม่ถูกต้อง: ตรวจสอบว่าข้อความส่งถึงโทเค็นการลงทะเบียนที่มีชื่อแพ็กเกจตรงกับค่าที่ส่งไปในคำขอ
ข้อความใหญ่เกินไป: ตรวจสอบว่าขนาดข้อมูลเพย์โหลดที่รวมอยู่ในข้อความมีขนาดไม่เกิน FCM นั่นคือ 4, 096 ไบต์สําหรับข้อความส่วนใหญ่ หรือ 2048 ไบต์ในกรณีที่ส่งข้อความไปยังหัวข้อ ซึ่งจะมีทั้งคีย์และค่า
คีย์ข้อมูลไม่ถูกต้อง: ตรวจสอบว่าข้อมูลเพย์โหลดไม่มีคีย์ (เช่น จาก หรือ gcm หรือค่าใดๆ ที่นำหน้าด้วย Google) ที่ FCM ใช้ภายใน โปรดทราบว่า FCM มีการใช้คำบางคำ (เช่น collapse_key) ด้วยแต่อนุญาตให้ใช้ในเพย์โหลด ซึ่งในกรณีนี้ค่าเพย์โหลดจะถูกแทนที่โดยค่า FCM
TTL ไม่ถูกต้อง: ตรวจสอบว่าค่าที่ใช้ใน ttl เป็นจำนวนเต็มที่แสดงระยะเวลาเป็นวินาทีระหว่าง 0 ถึง 2,419,200 (4 สัปดาห์)
พารามิเตอร์ไม่ถูกต้อง: ตรวจสอบว่าพารามิเตอร์ที่ระบุมีชื่อและประเภทที่ถูกต้อง
UNREGISTERED (รหัสข้อผิดพลาด HTTP = 404) อินสแตนซ์ของแอปถูกยกเลิกการลงทะเบียนจาก FCM โดยปกติแล้วหมายความว่าโทเค็นที่ใช้จะใช้งานไม่ได้อีกต่อไปและจะต้องใช้โทเค็นใหม่ ข้อผิดพลาดนี้อาจเกิดจากโทเค็นการลงทะเบียนขาดหายไปหรือโทเค็นที่ไม่ได้ลงทะเบียน
ไม่มีการลงทะเบียน: หากเป้าหมายของข้อความคือค่า token ให้ตรวจสอบว่าคำขอมีโทเค็นการลงทะเบียน
ไม่ได้ลงทะเบียน: โทเค็นการลงทะเบียนที่มีอยู่อาจใช้ไม่ได้ในบางสถานการณ์ เช่น
- หากแอปไคลเอ็นต์ยกเลิกการลงทะเบียนกับ FCM
- หากแอปไคลเอ็นต์ถูกยกเลิกการลงทะเบียนโดยอัตโนมัติ ซึ่งอาจเกิดขึ้นได้หากผู้ใช้ถอนการติดตั้งแอปพลิเคชัน เช่น ใน iOS หากบริการฟีดแบ็ก APN รายงานว่าโทเค็น APN ไม่ถูกต้อง
- หากโทเค็นการลงทะเบียนหมดอายุ (เช่น Google อาจตัดสินใจรีเฟรชโทเค็นการลงทะเบียน หรือโทเค็น APN หมดอายุสําหรับอุปกรณ์ iOS)
- หากอัปเดตแอปไคลเอ็นต์แล้ว แต่ไม่มีการกำหนดค่าเวอร์ชันใหม่ให้รับข้อความ
สำหรับทุกกรณี ให้นำโทเค็นการลงทะเบียนนี้ออกจากเซิร์ฟเวอร์แอปและหยุดใช้ในการส่งข้อความ
SENDER_ID_MISMATCH (รหัสข้อผิดพลาด HTTP = 403) รหัสผู้ส่งที่ได้รับการตรวจสอบสิทธิ์จะแตกต่างจากรหัสผู้ส่งสำหรับโทเค็นการลงทะเบียน โทเค็นการลงทะเบียนจะผูกกับกลุ่มผู้ส่งบางกลุ่ม เมื่อแอปไคลเอ็นต์ลงทะเบียนสำหรับ FCM แอปต้องระบุผู้ส่งที่ได้รับอนุญาตให้ส่งข้อความ คุณควรใช้รหัสผู้ส่งรหัสใดรหัสหนึ่งเมื่อส่งข้อความไปยังแอปไคลเอ็นต์ หากคุณเปลี่ยนไปใช้ผู้ส่งรายอื่น โทเค็นการลงทะเบียนที่มีอยู่จะไม่ทำงาน
QUOTA_EXCEEDED (รหัสข้อผิดพลาด HTTP = 429) เกินขีดจำกัดการส่งสำหรับเป้าหมายข้อความ ส่วนขยายประเภท google.rpc.QuotaFailure จะแสดงผลเพื่อระบุโควต้าที่เกินโควต้า ข้อผิดพลาดนี้อาจเกิดจากการเกินโควต้าอัตราข้อความ เกินโควต้าอัตราข้อความในอุปกรณ์ หรือเกินโควต้าอัตราข้อความหัวข้อ
เกินอัตราข้อความ: อัตราการส่งข้อความสูงเกินไป คุณต้องลดอัตราโดยรวมของการส่งข้อความ ใช้ Exponential Backoff โดยมีความล่าช้าเริ่มต้นอย่างน้อย 1 นาทีเพื่อลองส่งข้อความที่ถูกปฏิเสธอีกครั้ง
อัตราการส่งข้อความในอุปกรณ์เกินกำหนด: อัตราการส่งข้อความไปยังอุปกรณ์เครื่องใดเครื่องหนึ่งสูงเกินไป โปรดดูขีดจำกัดอัตราคำขอส่งข้อความสำหรับอุปกรณ์ 1 เครื่อง โปรดลดจำนวนข้อความที่ส่งไปยังอุปกรณ์นี้และใช้ Exponential Backoff เพื่อลองส่งอีกครั้ง
มีอัตราการส่งข้อความหัวข้อเกิน: อัตราการส่งข้อความไปยังหัวข้อใดหัวข้อหนึ่งสูงเกินไป ลดจำนวนข้อความที่ส่งสำหรับหัวข้อนี้และใช้ Exponential Backoff โดยมีความล่าช้าเริ่มต้นอย่างน้อย 1 นาทีเพื่อลองส่งอีกครั้ง
UNAVAILABLE (รหัสข้อผิดพลาด HTTP = 503) เซิร์ฟเวอร์ทำงานหนักเกินไป เซิร์ฟเวอร์ประมวลผลคำขอได้ไม่ทันเวลา ลองส่งคำขอเดิมอีกครั้ง แต่คุณต้องทำดังนี้
- ทำตามส่วนหัว Retry-After หากรวมอยู่ในการตอบกลับจากเซิร์ฟเวอร์การเชื่อมต่อ FCM
- ใช้ Exponential Backoff ในกลไกการลองใหม่ (เช่น หากคุณรอ 1 วินาทีก่อนลองอีกครั้งครั้งแรก ให้รออย่างน้อย 2 วินาทีก่อนเกมถัดไป จากนั้น 4 วินาที แล้วทำแบบนี้ไปเรื่อยๆ) หากคุณส่งหลายข้อความ ให้พิจารณาใช้การกระตุก โปรดดูข้อมูลเพิ่มเติมที่หัวข้อการจัดการการลองใหม่ ผู้ส่งที่ทำให้เกิดปัญหามีความเสี่ยงที่จะถูกปฏิเสธเป็นรายชื่อผู้ส่ง
INTERNAL (รหัสข้อผิดพลาด HTTP = 500) เกิดข้อผิดพลาดภายในที่ไม่รู้จัก เซิร์ฟเวอร์พบข้อผิดพลาดขณะพยายามประมวลผลคำขอ คุณสามารถลองทำตามคำขอเดิมอีกครั้งตามคำแนะนำในการจัดการการลองใหม่ หากข้อผิดพลาดยังคงอยู่ โปรดติดต่อทีมสนับสนุน Firebase
THIRD_PARTY_AUTH_ERROR (รหัสข้อผิดพลาด HTTP = 401) ใบรับรอง APN หรือคีย์การตรวจสอบสิทธิ์พุชจากเว็บไม่ถูกต้องหรือขาดหายไป ไม่สามารถส่งข้อความที่กำหนดเป้าหมายไปยังอุปกรณ์ iOS หรือการลงทะเบียนพุชจากเว็บได้ ตรวจสอบความถูกต้องของข้อมูลเข้าสู่ระบบการพัฒนาและเวอร์ชันที่ใช้งานจริง

รหัสข้อผิดพลาดของผู้ดูแลระบบ

ตารางต่อไปนี้แสดงรหัสข้อผิดพลาด FCM API ของผู้ดูแลระบบ Firebase และ คำอธิบาย รวมถึงขั้นตอนการแก้ปัญหาที่แนะนำ

รหัสข้อผิดพลาด ขั้นตอนคำอธิบายและการแก้ปัญหา
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 บริการรายงานว่าโทเค็น 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 เนื่องจาก ใบรับรอง SSL ของ APNs ที่จำเป็นยังไม่ได้อัปโหลดหรือหมดอายุแล้ว ตรวจสอบ ความถูกต้องของใบรับรองการพัฒนาและการผลิตของคุณ
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
  • ใช้ Exponential Backoff ในกลไกการลองใหม่ ตัวอย่างเช่น หากคุณรอ 1 วินาทีก่อนการลองอีกครั้งครั้งแรก ให้รออย่างน้อย 2 ครั้ง วินาทีก่อนหน้าเพลงถัดไป จากนั้น 4 วินาที และเป็นเช่นนี้ต่อไปเรื่อยๆ หากคุณ การส่งข้อความหลายข้อความ ให้หน่วงเวลาแต่ละข้อความแยกกันโดย จำนวนแบบสุ่มเพิ่มเติมเพื่อหลีกเลี่ยงการออกคำขอใหม่สำหรับ พร้อมกัน
ผู้ส่งที่ทำให้เกิดปัญหาเสี่ยงต่อการถูกขึ้นบัญชีดำ
messaging/internal-error เซิร์ฟเวอร์ FCM พบข้อผิดพลาดขณะพยายามประมวลผล อีกครั้ง คุณลองส่งคำขอเดิมอีกครั้งได้ตามข้อกำหนด ซึ่งแสดงในแถว messaging/server-unavailable ด้านบน หาก ข้อผิดพลาดยังคงอยู่ โปรดรายงานปัญหาไปยัง ช่องทางการสนับสนุนรายงานข้อบกพร่อง
messaging/unknown-error ระบบส่งคืนข้อผิดพลาดที่ไม่รู้จักเกี่ยวกับเซิร์ฟเวอร์ ดูการตอบกลับเซิร์ฟเวอร์แบบ RAW ใน เพื่อดูรายละเอียดเพิ่มเติม หากคุณได้รับข้อผิดพลาดนี้ โปรดรายงาน ข้อความแสดงข้อผิดพลาดทั้งหมดไปยัง ช่องทางการสนับสนุนรายงานข้อบกพร่อง

ส่งข้อความโดยใช้โปรโตคอลเซิร์ฟเวอร์แอปแบบเดิม

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

  • หัวข้อ 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 เดิมได้

คำขอ POST สำหรับ HTTP ของกลุ่มอุปกรณ์

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 รายการที่เชื่อมโยงอยู่ และข้อความ ส่งไปยังทั้ง 2 บัญชีเรียบร้อยแล้ว

{
  "success": 2,
  "failure": 0
}

นี่คือตัวอย่างของ "ความสำเร็จบางส่วน" — notification_key มีโทเค็นการลงทะเบียน 3 รายการที่เชื่อมโยง ด้วย ส่งข้อความไปยัง 1 รายที่จดทะเบียนสำเร็จแล้ว โทเค็นเท่านั้น ข้อความตอบกลับจะแสดงโทเค็นการลงทะเบียน (registration_ids) ที่รับข้อความไม่สำเร็จ:

{
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

เมื่อไม่สามารถส่งข้อความถึง โทเค็นการลงทะเบียนที่เชื่อมโยงกับ notification_key เซิร์ฟเวอร์แอปควรลองอีกครั้งโดย Backoff ระหว่างการลองใหม่

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

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

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 ยอมรับเพย์โหลดของข้อความเป็นอาร์กิวเมนต์และการสนับสนุนที่ 2 ทั้งคู่ ข้อความการแจ้งเตือนและข้อมูล คุณสามารถระบุข้อความประเภทเดียวหรือทั้ง 2 ประเภทได้โดยการสร้างออบเจ็กต์ด้วย data และ / หรือ notification เช่น วิธีกำหนดประเภทต่างๆ ของเพย์โหลดข้อความ:

ข้อความแจ้งเตือน

const payload = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
};

ข้อความข้อมูล

const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

ข้อความแบบรวม

const payload = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  data: {
    stock: 'GOOG',
    open: '829.62',
    close: '635.67'
  }
};

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

เพย์โหลดข้อความข้อมูลประกอบด้วยคู่คีย์-ค่าที่กำหนดเองที่มี 2-3 คู่ ข้อจำกัดดังกล่าว ซึ่งรวมถึงข้อเท็จจริงที่ว่าค่าทั้งหมดต้องเป็นสตริง โปรดดู เอกสารอ้างอิงสำหรับ 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 เพื่อดูรายการตัวเลือกทั้งหมดที่มี