ارسال پیام به چندین دستگاه

برای هدف قرار دادن یک پیام به چندین دستگاه، از پیام‌رسانی موضوع استفاده کنید. این ویژگی به شما امکان می دهد پیامی را به چندین دستگاهی که موضوع خاصی را انتخاب کرده اند ارسال کنید.

این آموزش بر ارسال پیام های موضوعی از سرور برنامه شما با استفاده از Admin SDK یا REST API برای FCM و دریافت و مدیریت آنها در یک برنامه وب متمرکز است. ما مدیریت پیام را برای برنامه‌های پس‌زمینه و پیش‌زمینه پوشش خواهیم داد.

SDK را تنظیم کنید

اگر یک برنامه مشتری جاوا اسکریپت برای 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);
  });

جاوا

// 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 همچنین به شما این امکان را می دهد که اشتراک دستگاه ها را از یک موضوع با ارسال نشانه های ثبت نام به روش مناسب لغو کنید:

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

جاوا

// 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 Errors مراجعه کنید.

دریافت و مدیریت پیام های موضوعی

رفتار پیام‌ها بسته به اینکه صفحه در پیش‌زمینه (دارای فوکوس)، یا در پس‌زمینه، پنهان شدن در پشت برگه‌های دیگر یا کاملاً بسته باشد، متفاوت است. در همه موارد، صفحه باید پاسخ تماس onMessage را انجام دهد، اما در موارد پس‌زمینه ممکن است نیاز باشد که onBackgroundMessage نیز مدیریت کنید یا اعلان نمایش را پیکربندی کنید تا به کاربر اجازه دهد برنامه وب شما را در پیش‌زمینه بیاورد.

وضعیت برنامه اطلاع داده ها هر دو
پیش زمینه onMessage onMessage onMessage
سابقه (کارمند خدمات) onBackgroundMessage (نمایش اعلان به صورت خودکار نشان داده می شود) onBackgroundMessage onBackgroundMessage (نمایش اعلان به صورت خودکار نشان داده می شود)

وقتی برنامه وب شما در پیش زمینه است، پیام ها را مدیریت کنید

برای دریافت رویداد onMessage ، برنامه شما باید کارگر سرویس پیام‌رسانی Firebase را در firebase-messaging-sw.js تعریف کند. همچنین، می‌توانید یک سرویس‌کار موجود را از طریق getToken(): Promise<string> به SDK ارائه دهید.

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

وقتی برنامه وب شما در پس‌زمینه است، پیام‌ها را مدیریت کنید

همه پیام‌های دریافت شده در حالی که برنامه در پس‌زمینه است، یک اعلان نمایشگر را در مرورگر راه‌اندازی می‌کنند. می‌توانید گزینه‌هایی را برای این اعلان، مانند اقدام عنوان یا کلیک، در درخواست ارسال از سرور برنامه خود یا با استفاده از منطق سرویس‌کار روی کلاینت مشخص کنید.

تنظیم گزینه های اعلان در درخواست ارسال

برای پیام‌های اعلان ارسال شده از سرور برنامه، API جاوا اسکریپت FCM از کلید 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 را برای اطلاعات مربوط به پس‌زمینه و تنظیمات مهم ببینید.

در منطق ارسال خود در باطن، نام موضوع مورد نظر را مطابق شکل مشخص کنید:

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

جاوا

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

می توانید حداکثر پنج موضوع را در عبارت شرطی خود بگنجانید.

برای ارسال به یک شرط:

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

جاوا

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

ویژگی های فشار وب را به یک بار اعلان اضافه کنید

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

با این درخواست، کلاینت‌های وب هدف (از جمله مرورگرهای پشتیبانی‌شده در حال اجرا در اندروید) یک پیام اعلان با اولویت بالا دریافت می‌کنند که تا زمانی که کاربر با آن ارتباط برقرار کند فعال باقی می‌ماند. این شامل فیلدها است:

  • عنوان: پیام FCM
  • بدنه: این یک پیام از FCM به وب است
  • RequireInteraction: درست است
  • نشان: /badge-icon.png

برنامه‌های بومی Android و Apple (که لغو وب روی آنها اعمال نمی‌شود) یک پیام اعلان با اولویت معمولی دریافت می‌کنند:

  • عنوان: پیام FCM
  • بدنه: این پیامی از FCM است

توجه داشته باشید که RequireInteraction در حال حاضر تنها از پشتیبانی جزئی در بین مرورگرها برخوردار است. توسعه دهندگان باید مشخصات Web Notification 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 ، به درخواست‌های ارسال سرور برنامه ایجاد کنید .