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

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

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

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

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

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

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

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

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

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

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

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().sendEachForMulticast(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().sendEachForMulticast(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_each_for_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(f'List of tokens that caused failures: {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.SendEachForMulticast(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}");
}

ส่งรายการข้อความ

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

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().sendEach(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().sendEach(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_each(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print(f'{response.success_count} messages were sent successfully')

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.SendEach(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");

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

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

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

Node.js

// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';

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

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

Java

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Topic: topic,
}

// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";

// See documentation on defining a message payload.
var message = new Message()
{
    Data = new Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
    Topic = topic,
};

// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

คำสั่ง cURL

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "message": {
    "topic" : "foo-bar",
    "notification": {
      "body": "This is a Firebase Cloud Messaging Topic Message!",
      "title": "FCM Message"
    }
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

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

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

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

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

คุณใส่หัวข้อในนิพจน์แบบมีเงื่อนไขได้สูงสุด 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

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

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

ส่งข้อความที่เปิดใช้การบูตโดยตรง (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,
    },
}

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

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

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

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

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

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

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

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

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

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

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

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

เมื่อส่งข้อความที่มีตัวเลือกการนำส่งที่เฉพาะเจาะจง ให้ใช้ช่องเฉพาะแพลตฟอร์มเพื่อตั้งค่า คุณสามารถระบุค่าที่แตกต่างกันต่อแพลตฟอร์มได้หาก ต้องการ อย่างไรก็ตาม แม้ว่าคุณต้องการตั้งค่าที่เหมือนกันในทุกแพลตฟอร์ม คุณก็ต้องใช้ช่องที่เฉพาะเจาะจงสำหรับแพลตฟอร์มนั้นๆ เนื่องจากแต่ละแพลตฟอร์มอาจตีความค่าแตกต่างกันเล็กน้อย เช่น ใน Android ระบบจะตั้งค่า Time-To-Live เป็นเวลาหมดอายุในหน่วยวินาที ส่วนใน 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