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

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

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

ตั้งค่า SDK

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

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

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

  2. เพิ่ม Firebase Cloud Messaging JS SDK และเริ่มต้น Firebase Cloud Messaging:

API แบบโมดูลาร์ของเว็บ

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

API เนมสเปซของเว็บ

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() เมื่อเรียกตามที่แสดง สิ่งนี้จะส่งคืนโทเค็นหากได้รับอนุญาตหรือปฏิเสธสัญญาหากถูกปฏิเสธ:

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

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

// 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 เพื่อสมัครสมาชิกอุปกรณ์ที่เกี่ยวข้องในหัวข้อ:

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

ชวา

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

หลาม

# 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')

ไป

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

ค#

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

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

ชวา

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

หลาม

# 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')

ไป

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

ค#

// 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
ความเป็นมา (พนักงานบริการ) onBackgroundMessage (แสดงการแจ้งเตือนโดยอัตโนมัติ) onBackgroundMessage onBackgroundMessage (แสดงการแจ้งเตือนโดยอัตโนมัติ)

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

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

Web modular API

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

// 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.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.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 modular API

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

// 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);
  // ...
});

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

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

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

สำหรับข้อความแจ้งเตือนที่ส่งจากเซิร์ฟเวอร์แอป 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:

Web modular API

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

// 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.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.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 modular API

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

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

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

โหนด js

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

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

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

ชวา

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

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

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

หลาม

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

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

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

ไป

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

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

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

ค#

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

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

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

พักผ่อน

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

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

คำสั่ง cURL:

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

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

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

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

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

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

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

โหนด js

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

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

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

ชวา

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

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setCondition(condition)
    .build();

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

หลาม

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

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

ไป

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

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

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

ค#

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

// See documentation on defining a message payload.
var message = new Message()
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Condition = condition,
};

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

พักผ่อน

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
   "message":{
    "condition": "'dogs' in topics || 'cats' in topics",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message",
    }
  }
}

คำสั่ง cURL:

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

เพิ่มคุณสมบัติ Web 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 ถึงเว็บ
  • ต้องการการโต้ตอบ: จริง
  • ป้ายสถานะ: /badge-icon.png

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

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

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

ม้วนผม

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