Gửi tin nhắn đến nhiều thiết bị

Để nhắm mục tiêu tin nhắn đến nhiều thiết bị, hãy sử dụng Tin nhắn theo chủ đề . Tính năng này cho phép bạn gửi tin nhắn đến nhiều thiết bị đã chọn tham gia vào một chủ đề cụ thể.

Hướng dẫn này tập trung vào việc gửi thông báo chủ đề từ máy chủ ứng dụng của bạn bằng SDK quản trị hoặc API REST cho FCM, đồng thời nhận và xử lý chúng trong ứng dụng web. Chúng tôi sẽ đề cập đến việc xử lý tin nhắn cho cả ứng dụng nền và ứng dụng nền trước.

Thiết lập SDK

Phần này có thể bao gồm các bước bạn đã hoàn thành nếu bạn đã thiết lập ứng dụng khách JavaScript cho FCM hoặc đã thực hiện các bước để nhận tin nhắn .

Thêm và khởi tạo SDK FCM

  1. Nếu bạn chưa có, hãy cài đặt SDK Firebase JS và khởi chạy Firebase .

  2. Thêm SDK JS nhắn tin qua đám mây Firebase và khởi tạo Nhắn tin qua đám mây Firebase:

API mô-đun 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);

API không gian tên 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();

Truy cập mã thông báo đăng ký

Khi bạn cần truy xuất mã thông báo đăng ký hiện tại cho một phiên bản ứng dụng, trước tiên hãy yêu cầu quyền thông báo từ người dùng bằng Notification.requestPermission() . Khi được gọi như được hiển thị, mã này sẽ trả về mã thông báo nếu được cấp quyền hoặc từ chối lời hứa nếu bị từ chối:

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

FCM yêu cầu tệp firebase-messaging-sw.js . Trừ khi bạn đã có tệp firebase-messaging-sw.js , hãy tạo một tệp trống có tên đó và đặt nó vào thư mục gốc của miền trước khi truy xuất mã thông báo. Bạn có thể thêm nội dung có ý nghĩa vào tệp sau trong quá trình thiết lập máy khách.

Để lấy mã thông báo hiện tại:

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

Sau khi bạn nhận được mã thông báo, hãy gửi mã đó đến máy chủ ứng dụng của bạn và lưu trữ mã đó bằng phương pháp ưa thích của bạn.

Đăng ký ứng dụng khách theo một chủ đề

Bạn có thể chuyển danh sách mã thông báo đăng ký sang phương thức đăng ký SDK quản trị Firebase để đăng ký các thiết bị tương ứng theo một chủ đề:

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

Đi

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

API FCM quản trị cũng cho phép bạn hủy đăng ký thiết bị khỏi một chủ đề bằng cách chuyển mã thông báo đăng ký sang phương thức thích hợp:

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

Đi

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

Các phương thức subscribeToTopic()unsubscribeFromTopic() dẫn đến một đối tượng chứa phản hồi từ FCM. Kiểu trả về có cùng định dạng bất kể số lượng mã thông báo đăng ký được chỉ định trong yêu cầu.

Trong trường hợp có lỗi (xác thực không thành công, mã thông báo hoặc chủ đề không hợp lệ, v.v.), các phương thức này sẽ dẫn đến lỗi. Để biết danh sách đầy đủ các mã lỗi, bao gồm mô tả và các bước giải quyết, hãy xem Lỗi API FCM của quản trị viên .

Nhận và xử lý tin nhắn chủ đề

Hoạt động của thông báo sẽ khác nhau tùy thuộc vào việc trang đó ở nền trước (có tiêu điểm) hay ở nền, ẩn sau các tab khác hay đóng hoàn toàn. Trong mọi trường hợp, trang phải xử lý lệnh gọi lại onMessage , nhưng trong các trường hợp nền, bạn cũng có thể cần xử lý onBackgroundMessage hoặc định cấu hình thông báo hiển thị để cho phép người dùng đưa ứng dụng web của bạn lên nền trước.

Trạng thái ứng dụng Thông báo Dữ liệu Cả hai
Vấn đề xung quanh onMessage onMessage onMessage
Bối cảnh (nhân viên phục vụ) onBackgroundMessage (thông báo hiển thị tự động hiển thị) onBackgroundMessage onBackgroundMessage (thông báo hiển thị tự động hiển thị)

Xử lý tin nhắn khi ứng dụng web của bạn ở nền trước

Để nhận được sự kiện onMessage , ứng dụng của bạn phải xác định nhân viên dịch vụ nhắn tin Firebase trong firebase-messaging-sw.js . Ngoài ra, bạn có thể cung cấp nhân viên dịch vụ hiện có cho SDK thông qua 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();

Khi ứng dụng của bạn chạy ở nền trước (người dùng hiện đang xem trang web của bạn), bạn có thể nhận dữ liệu và tải trọng thông báo trực tiếp trên trang.

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

Xử lý tin nhắn khi ứng dụng web của bạn ở chế độ nền

Tất cả tin nhắn nhận được khi ứng dụng ở chế độ nền sẽ kích hoạt thông báo hiển thị trong trình duyệt. Bạn có thể chỉ định các tùy chọn cho thông báo này, chẳng hạn như tiêu đề hoặc hành động nhấp chuột, trong yêu cầu gửi từ máy chủ ứng dụng của bạn hoặc sử dụng logic của nhân viên dịch vụ trên máy khách.

Đặt tùy chọn thông báo trong yêu cầu gửi

Đối với các tin nhắn thông báo được gửi từ máy chủ ứng dụng, API FCM JavaScript hỗ trợ khóa fcm_options.link . Thông thường, điều này được đặt thành một trang trong ứng dụng web của bạn:

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

Nếu giá trị liên kết trỏ đến một trang đã mở trong tab trình duyệt, thì một cú nhấp chuột vào thông báo sẽ đưa tab đó lên nền trước. Nếu trang chưa được mở, một lần nhấp thông báo sẽ mở trang trong tab mới.

Vì tin nhắn dữ liệu không hỗ trợ fcm_options.link nên bạn nên thêm tải trọng thông báo vào tất cả tin nhắn dữ liệu. Ngoài ra, bạn có thể xử lý thông báo bằng cách sử dụng nhân viên dịch vụ.

Để biết giải thích về sự khác biệt giữa thông báo và tin nhắn dữ liệu, hãy xem Loại tin nhắn .

Đặt tùy chọn thông báo trong nhân viên dịch vụ

Đối với tin nhắn dữ liệu, bạn có thể đặt tùy chọn thông báo trong nhân viên dịch vụ. Đầu tiên, khởi tạo ứng dụng của bạn trong nhân viên dịch vụ:

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

Để đặt tùy chọn, hãy gọi onBackgroundMessage trong firebase-messaging-sw.js . Trong ví dụ này, chúng tôi tạo thông báo với các trường tiêu đề, nội dung và biểu tượng.

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

Xây dựng yêu cầu gửi

Sau khi bạn đã tạo một chủ đề, bằng cách đăng ký các phiên bản ứng dụng khách cho chủ đề ở phía máy khách hoặc thông qua API máy chủ , bạn có thể gửi tin nhắn đến chủ đề. Nếu đây là lần đầu tiên bạn xây dựng yêu cầu gửi FCM, hãy xem hướng dẫn về môi trường máy chủ và FCM của bạn để biết thông tin cơ bản và thiết lập quan trọng.

Trong logic gửi của bạn ở phần phụ trợ, hãy chỉ định tên chủ đề mong muốn như được hiển thị:

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)

Đi

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

NGHỈ NGƠI

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

lệnh 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

Để gửi tin nhắn đến một tổ hợp các chủ đề, hãy chỉ định một điều kiện , đây là biểu thức boolean chỉ định các chủ đề đích. Ví dụ: điều kiện sau sẽ gửi tin nhắn đến các thiết bị đã đăng ký TopicATopicB hoặc TopicC :

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

Trước tiên FCM đánh giá mọi điều kiện trong ngoặc đơn, sau đó đánh giá biểu thức từ trái sang phải. Trong biểu thức trên, người dùng đăng ký bất kỳ chủ đề nào sẽ không nhận được tin nhắn. Tương tự, người dùng không đăng ký TopicA sẽ không nhận được tin nhắn. Những kết hợp này nhận được nó:

  • TopicATopicB
  • TopicATopicC

Bạn có thể bao gồm tối đa năm chủ đề trong biểu thức điều kiện của mình.

Để gửi đến một điều kiện:

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)

Đi

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

NGHỈ NGƠI

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

lệnh 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

Thêm thuộc tính đẩy web vào tải trọng thông báo

Với API HTTP v1, bạn có thể chỉ định các tùy chọn thông báo bổ sung dưới dạng đối tượng JSON chứa bất kỳ thuộc tính hợp lệ nào từ API thông báo web . Các trường titlebody trong đối tượng này, nếu có, sẽ ghi đè các trường google.firebase.fcm.v1.Notification.titlegoogle.firebase.fcm.v1.Notification.body tương đương.

Yêu cầu 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"
      }
    }
  }
}

Với yêu cầu này, các ứng dụng khách web được nhắm mục tiêu (bao gồm cả các trình duyệt được hỗ trợ chạy trên Android) sẽ nhận được thông báo có mức độ ưu tiên cao vẫn hoạt động cho đến khi người dùng tương tác với nó. Nó chứa các trường:

  • Tiêu đề: Tin nhắn FCM
  • Nội dung: Đây là tin nhắn từ FCM tới web
  • Yêu cầu tương tác: đúng
  • Huy hiệu: /badge-icon.png

Các ứng dụng gốc của Android và Apple (không áp dụng tính năng ghi đè trên web) sẽ nhận được thông báo có mức độ ưu tiên thông thường với:

  • Tiêu đề: Tin nhắn FCM
  • Nội dung: Đây là tin nhắn từ FCM

Lưu ý rằng RequireInteraction hiện chỉ hỗ trợ một phần giữa các trình duyệt. Nhà phát triển nên kiểm tra đặc tả API thông báo web để xác minh sự hỗ trợ của nền tảng và trình duyệt.

Xoăn

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"

Phản hồi HTTP

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

Xem Xây dựng yêu cầu gửi máy chủ ứng dụng để tìm hiểu thêm về tin nhắn FCM.