שלח הודעות למספר מכשירים

כדי למקד הודעה למספר מכשירים, השתמש בהודעות נושא . תכונה זו מאפשרת לך לשלוח הודעה למספר מכשירים שהצטרפו לנושא מסוים.

מדריך זה מתמקד בשליחת הודעות נושא משרת האפליקציות שלך באמצעות ה- 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 כדי להירשם למכשירים המתאימים לנושא:

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

פִּיתוֹן

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

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 של Admin FCM מאפשר לך גם לבטל את הרישום של מכשירים לנושא על ידי העברת אסימוני רישום לשיטה המתאימה:

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

פִּיתוֹן

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

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 Errors .

קבלה וטיפול בהודעות בנושא

ההתנהגות של הודעות משתנה בהתאם אם הדף נמצא בחזית (יש לו מיקוד), או ברקע, מוסתר מאחורי כרטיסיות אחרות או סגור לחלוטין. בכל המקרים הדף חייב לטפל בהתקשרות חוזרת 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);
  // ...
});

טפל בהודעות כאשר אפליקציית האינטרנט שלך ברקע

כל ההודעות המתקבלות בזמן שהאפליקציה ברקע מעוררות התראת תצוגה בדפדפן. אתה יכול לציין אפשרויות עבור הודעה זו, כגון כותרת או פעולת לחיצה, בבקשת השליחה משרת האפליקציה שלך, או באמצעות לוגיקה של 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 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 לקבלת מידע חשוב על רקע והגדרה.

בלוגיקת השליחה שלך בקצה העורפי, ציין את שם הנושא הרצוי כפי שמוצג:

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

פִּיתוֹן

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

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

מנוחה

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

אתה יכול לכלול עד חמישה נושאים בביטוי המותנה שלך.

כדי לשלוח לתנאי:

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

פִּיתוֹן

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

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

מנוחה

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

הוסף מאפייני דחיפה באינטרנט למטען הודעות

עם ה-API של HTTP v1 אתה יכול לציין אפשרויות התראות נוספות כאובייקט 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"
      }
    }
  }
}

עם בקשה זו, לקוחות אינטרנט ממוקדים (כולל דפדפנים נתמכים הפועלים על אנדרואיד) מקבלים הודעת התראה בעדיפות גבוהה שנשארת פעילה עד שהמשתמש יוצר איתה אינטראקציה. הוא מכיל את השדות:

  • כותרת: הודעת FCM
  • גוף: זוהי הודעה מ-FCM לאינטרנט
  • דורש אינטראקציה: נכון
  • תג: /badge-icon.png

אפליקציות מקוריות לאנדרואיד ו-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.