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

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

บทแนะนำนี้มุ่งเน้นที่การส่งข้อความตามหัวข้อจากเซิร์ฟเวอร์แอปโดยใช้ Admin SDK หรือ REST API สำหรับ FCM รวมถึงการรับและจัดการข้อความใน เว็บแอป เราจะครอบคลุมการจัดการข้อความสำหรับแอปที่ทำงานในเบื้องหลังและเบื้องหน้า

ตั้งค่า SDK

ส่วนนี้อาจครอบคลุมขั้นตอนที่คุณทําเสร็จแล้ว หากคุณ ตั้งค่าแอปไคลเอ็นต์ JavaScript สําหรับ FCM หรือทําตามขั้นตอนเพื่อ รับข้อความ

เพิ่มและเริ่มต้น FCM SDK

  1. หากยังไม่ได้ดำเนินการ ให้ ติดตั้ง Firebase JS SDK และเริ่มต้น Firebase

  2. เพิ่ม Firebase Cloud Messaging JS SDK และเริ่มต้น Firebase Cloud Messaging ดังนี้

Web

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Firebase Cloud Messaging and get a reference to the service
const messaging = getMessaging(app);

Web

import firebase from "firebase/compat/app";
import "firebase/compat/messaging";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Firebase Cloud Messaging and get a reference to the service
const messaging = firebase.messaging();

เข้าถึงโทเค็นการลงทะเบียน

เมื่อต้องการดึงโทเค็นการลงทะเบียนปัจจุบันสำหรับอินสแตนซ์แอป คุณต้องขอสิทธิ์การแจ้งเตือนจากผู้ใช้ด้วย Notification.requestPermission() ก่อน เมื่อเรียกใช้ตามที่แสดง ฟังก์ชันนี้จะแสดงโทเค็นหากได้รับสิทธิ์ หรือปฏิเสธ Promise หากถูกปฏิเสธ

function requestPermission() {
  console.log('Requesting permission...');
  Notification.requestPermission().then((permission) => {
    if (permission === 'granted') {
      console.log('Notification permission granted.');

FCM ต้องใช้ไฟล์ firebase-messaging-sw.js หากยังไม่มีไฟล์ firebase-messaging-sw.js ให้สร้างไฟล์ว่าง ที่มีชื่อดังกล่าวและวางไว้ที่รูทของโดเมนก่อนที่จะดึงโทเค็น คุณเพิ่มเนื้อหาที่มีความหมายลงในไฟล์ได้ในภายหลังในกระบวนการตั้งค่าไคลเอ็นต์

วิธีดึงโทเค็นปัจจุบัน

Web

import { getMessaging, getToken } from "firebase/messaging";

// Get registration token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
const messaging = getMessaging();
getToken(messaging, { vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server and update the UI if necessary
    // ...
  } else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
    // ...
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  // ...
});

Web

// Get registration token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken({ vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server and update the UI if necessary
    // ...
  } else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
    // ...
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  // ...
});

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

สมัครใช้บริการแอปไคลเอ็นต์ไปยังหัวข้อ

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

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // ...
  'YOUR_REGISTRATION_TOKEN_n'
];

// Subscribe the devices corresponding to the registration tokens to the
// topic.
getMessaging().subscribeToTopic(registrationTokens, topic)
  .then((response) => {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully subscribed to topic:', response);
  })
  .catch((error) => {
    console.log('Error subscribing to topic:', error);
  });

Java

// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

// Subscribe the devices corresponding to the registration tokens to the
// topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");

Python

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Subscribe the devices corresponding to the registration tokens to the
# topic.
response = messaging.subscribe_to_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were subscribed successfully')

Go

// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}

// Subscribe the devices corresponding to the registration tokens to the
// topic.
response, err := client.SubscribeToTopic(ctx, registrationTokens, topic)
if err != nil {
	log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were subscribed successfully")

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};

// Subscribe the devices corresponding to the registration tokens to the
// topic
var response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");

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

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // ...
  'YOUR_REGISTRATION_TOKEN_n'
];

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
getMessaging().unsubscribeFromTopic(registrationTokens, topic)
  .then((response) => {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully unsubscribed from topic:', response);
  })
  .catch((error) => {
    console.log('Error unsubscribing from topic:', error);
  });

Java

// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");

Python

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Unubscribe the devices corresponding to the registration tokens from the
# topic.
response = messaging.unsubscribe_from_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were unsubscribed successfully')

Go

// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
response, err := client.UnsubscribeFromTopic(ctx, registrationTokens, topic)
if err != nil {
	log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were unsubscribed successfully")

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};

// Unsubscribe the devices corresponding to the registration tokens from the
// topic
var response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were unsubscribed successfully");

เมธอด subscribeToTopic() และ unsubscribeFromTopic() จะส่งผลให้เกิดออบเจ็กต์ที่มีการตอบกลับจาก FCM ประเภทการตอบกลับมีรูปแบบเดียวกัน ไม่ว่าจะมีโทเค็นการลงทะเบียนกี่รายการที่ระบุในคำขอ

ในกรณีที่เกิดข้อผิดพลาด (การตรวจสอบสิทธิ์ล้มเหลว โทเค็นหรือหัวข้อไม่ถูกต้อง ฯลฯ) วิธีการเหล่านี้จะทำให้เกิดข้อผิดพลาด ดูรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบาย และขั้นตอนการแก้ไขได้ที่ ข้อผิดพลาดของ Admin FCM API

รับและจัดการข้อความของหัวข้อ

ลักษณะการทำงานของข้อความจะแตกต่างกันไปตาม ว่าหน้าเว็บอยู่เบื้องหน้า (มีโฟกัส) หรืออยู่เบื้องหลัง ซ่อน อยู่หลังแท็บอื่นๆ หรือปิดไปแล้ว ในทุกกรณี หน้าเว็บต้องจัดการการเรียกกลับ onMessage แต่ในกรณีที่ทำงานในเบื้องหลัง คุณอาจต้องจัดการ onBackgroundMessage หรือกําหนดค่าการแจ้งเตือนที่แสดงเพื่อให้ผู้ใช้นําเว็บแอปของคุณ มาไว้ที่เบื้องหน้า

สถานะของแอป การแจ้งเตือน ข้อมูล ทั้งสอง
พื้นหน้า onMessage onMessage onMessage
เบื้องหลัง (Service Worker) onBackgroundMessage (แสดงการแจ้งเตือนโดยอัตโนมัติ) onBackgroundMessage onBackgroundMessage (แสดงการแจ้งเตือนโดยอัตโนมัติ)

จัดการข้อความเมื่อเว็บแอปอยู่เบื้องหน้า

หากต้องการรับเหตุการณ์ onMessage แอปต้องกำหนด Service Worker ของการรับส่งข้อความ Firebase ใน firebase-messaging-sw.js หรือจะระบุ Service Worker ที่มีอยู่ให้กับ SDK ผ่าน getToken(): Promise<string> ก็ได้

Web

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

Web

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

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

Web

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
import { getMessaging, onMessage } from "firebase/messaging";

const messaging = getMessaging();
onMessage(messaging, (payload) => {
  console.log('Message received. ', payload);
  // ...
});

Web

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
  // ...
});

จัดการข้อความเมื่อเว็บแอปทำงานในเบื้องหลัง

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

การตั้งค่าตัวเลือกการแจ้งเตือนในคำขอส่ง

สำหรับข้อความแจ้งเตือนที่ส่งจากเซิร์ฟเวอร์ของแอป FCM JavaScript API รองรับคีย์ fcm_options.link โดยปกติแล้วจะตั้งค่าเป็นหน้าในเว็บแอป

https://fcm.googleapis.com//v1/projects/<YOUR-PROJECT-ID>/messages:send
Content-Type: application/json
Authorization: bearer <YOUR-ACCESS-TOKEN>

{
  "message": {
    "topic": "matchday",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}

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

เนื่องจากข้อความข้อมูลไม่รองรับ fcm_options.link เราจึงขอแนะนำให้คุณ เพิ่มเพย์โหลดการแจ้งเตือนลงในข้อความข้อมูลทั้งหมด หรือจะจัดการ การแจ้งเตือนโดยใช้ Service Worker ก็ได้

ดูคำอธิบายความแตกต่างระหว่างข้อความแจ้งเตือนกับข้อความข้อมูลได้ที่ประเภทข้อความ

การตั้งค่าตัวเลือกการแจ้งเตือนใน Service Worker

สำหรับข้อความข้อมูล คุณสามารถตั้งค่าตัวเลือกการแจ้งเตือนใน Service Worker ได้ ก่อนอื่น ให้เริ่มต้นแอปใน Service Worker ดังนี้

Web

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);

Web

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

หากต้องการตั้งค่าตัวเลือก ให้โทรไปที่ onBackgroundMessage ใน firebase-messaging-sw.js ในตัวอย่างนี้ เราจะสร้างการแจ้งเตือนที่มีช่องชื่อ เนื้อหา และไอคอน

Web

import { getMessaging } from "firebase/messaging/sw";
import { onBackgroundMessage } from "firebase/messaging/sw";

const messaging = getMessaging();
onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

Web

messaging.onBackgroundMessage((payload) => {
  console.log(
    '[firebase-messaging-sw.js] Received background message ',
    payload
  );
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

สร้างคำขอส่ง

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

เพิ่มพร็อพเพอร์ตี้ของข้อความ Push บนเว็บไปยังเพย์โหลดการแจ้งเตือน

HTTP v1 API ช่วยให้คุณระบุตัวเลือกการแจ้งเตือนเพิ่มเติมเป็นออบเจ็กต์ JSON ที่มีพร็อพเพอร์ตี้ที่ถูกต้องจาก Web Notification API ได้ ฟิลด์ title และ body ในออบเจ็กต์นี้ หากมี จะลบล้างฟิลด์ google.firebase.fcm.v1.Notification.title และ google.firebase.fcm.v1.Notification.body ที่เทียบเท่า

คำขอ HTTP POST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...PbJ_uNasm

{
  "message": {
    "token" : <token of destination app>,
    "notification": {
      "title": "FCM Message",
      "body": "This is a message from FCM"
    },
    "webpush": {
      "headers": {
        "Urgency": "high"
      },
      "notification": {
        "body": "This is a message from FCM to web",
        "requireInteraction": "true",
        "badge": "/badge-icon.png"
      }
    }
  }
}

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

  • ชื่อ: ข้อความ FCM
  • เนื้อหา: นี่คือข้อความจาก FCM ไปยังเว็บ
  • RequireInteraction: true
  • ป้าย: /badge-icon.png

แอปเนทีฟของ Android และ Apple (ซึ่งการลบล้างบนเว็บใช้ไม่ได้) จะได้รับข้อความแจ้งเตือนที่มีลำดับความสำคัญปกติพร้อมข้อมูลต่อไปนี้

  • ชื่อ: ข้อความ FCM
  • เนื้อหา: นี่คือข้อความจาก FCM

โปรดทราบว่าขณะนี้ RequireInteraction รองรับเฉพาะบางส่วนในเบราว์เซอร์ นักพัฒนาแอปควรตรวจสอบ ข้อกำหนดของ Web Notification API เพื่อยืนยันการรองรับแพลตฟอร์มและเบราว์เซอร์

cURL

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...PbJ_uNasm" -H "Content-Type: application/json" -d '{
  "message": {
    "token": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
    "notification": {
      "title": "FCM Message",
      "body": "This is a message from FCM"
    },
    "webpush": {
      "headers": {
        "Urgency": "high"
      },
      "notification": {
        "body": "This is a message from FCM to web",
        "requireInteraction": "true",
        "badge": "/badge-icon.png"
      }
    }
  }
}' "https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send"

การตอบกลับ HTTP

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

ดูข้อมูลเพิ่มเติมเกี่ยวกับข้อความ FCM ได้ที่สร้างคำขอส่งของเซิร์ฟเวอร์แอป