एक से ज़्यादा डिवाइसों पर मैसेज भेजें

किसी मैसेज को कई डिवाइसों पर टारगेट करने के लिए, विषय के मैसेज का इस्तेमाल करें. इस सुविधा की मदद से, किसी खास विषय के लिए ऑप्ट-इन किए गए अलग-अलग डिवाइसों पर मैसेज भेजा जा सकता है.

इस ट्यूटोरियल में FCM के लिए एडमिन SDK या REST API का इस्तेमाल करके आपके ऐप्लिकेशन सर्वर से विषय से जुड़े मैसेज भेजने पर फ़ोकस किया गया है. साथ ही, उन्हें वेब ऐप्लिकेशन में पाने और मैनेज करने पर फ़ोकस किया गया है. हम बैकग्राउंड और फ़ोरग्राउंड, दोनों तरह के ऐप्लिकेशन के लिए मैसेज मैनेज करने के बारे में बताएंगे.

SDK टूल सेट अप करें

अगर आपने FCM के लिए JavaScript क्लाइंट ऐप्लिकेशन सेट अप किया है या मैसेज पाने के चरणों पर काम किया है, तो इस सेक्शन में वे चरण शामिल हो सकते हैं जिन्हें आप पहले ही पूरा कर चुके हैं.

FCM SDK टूल जोड़ना और शुरू करना

  1. अगर आपने पहले से ऐसा नहीं किया है, तो Firebase JS SDK टूल इंस्टॉल करें और Firebase शुरू करें.

  2. 'Firebase क्लाउड से मैसेज' JS SDK टूल जोड़ें और Firebase क्लाउड से मैसेज शुरू करें:

Web

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

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

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


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

Web

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

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

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


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

रजिस्ट्रेशन टोकन ऐक्सेस करना

जब आपको किसी ऐप्लिकेशन इंस्टेंस के लिए मौजूदा रजिस्ट्रेशन टोकन को फिर से पाने की ज़रूरत हो, तो सबसे पहले Notification.requestPermission() वाले उपयोगकर्ता से सूचना की अनुमतियों का अनुरोध करें. इस तरह से कॉल किए जाने पर, यह एक टोकन दिखाता है. हालांकि, ऐसा तब होता है, जब प्रॉमिस को अनुमति दी जाती है या अस्वीकार किए जाने पर उसे अस्वीकार कर दिया जाता है:

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

FCM के लिए firebase-messaging-sw.js फ़ाइल की ज़रूरत होती है. अगर आपके पास पहले से कोई firebase-messaging-sw.js फ़ाइल नहीं है, तो उस नाम की एक खाली फ़ाइल बनाएं और टोकन फिर से पाने से पहले उसे अपने डोमेन के रूट में रखें. क्लाइंट सेटअप करने की प्रोसेस के दौरान, बाद में फ़ाइल में काम का कॉन्टेंट जोड़ा जा सकता है.

मौजूदा टोकन फिर से पाने के लिए:

Web

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

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

Web

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

टोकन पाने के बाद, उसे अपने ऐप्लिकेशन सर्वर पर भेजें और अपने पसंदीदा तरीके का इस्तेमाल करके उसे सेव करें.

किसी विषय के लिए, क्लाइंट ऐप्लिकेशन की सदस्यता लेना

Firebase एडमिन SDK टूल की सदस्यता लेने के तरीके पर रजिस्ट्रेशन टोकन की सूची पास की जा सकती है. इससे, उस विषय से जुड़े डिवाइसों की सदस्यता ली जा सकती है:

Node.js के लिए

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

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

Java

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

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

Python

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

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

शुरू करें

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

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

C#

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

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

Admin FCM API आपको सही तरीके पर रजिस्ट्रेशन टोकन पास करके, किसी विषय से जुड़े डिवाइसों की सदस्यता छोड़ने की सुविधा भी देता है:

Node.js के लिए

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

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

Java

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

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

Python

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

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

शुरू करें

// 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 से रिस्पॉन्स मिलता है. अनुरोध में बताए गए रजिस्ट्रेशन टोकन की संख्या चाहे कुछ भी हो, रिटर्न टाइप का फ़ॉर्मैट एक ही होता है.

इन तरीकों से गड़बड़ी (पुष्टि नहीं हो पाना, अमान्य टोकन या विषय वगैरह) की स्थिति में गड़बड़ी होती है. गड़बड़ी के कोड की पूरी सूची देखने के लिए, एडमिन FCM एपीआई से जुड़ी गड़बड़ियां देखें. इस सूची में, गड़बड़ी का ब्यौरा और उसे ठीक करने के तरीके भी शामिल हैं.

विषय के मैसेज पाएं और मैनेज करें

मैसेज का व्यवहार इस बात पर निर्भर करता है कि पेज फ़ोरग्राउंड में है (फ़ोकस किया गया है), या बैकग्राउंड में है, दूसरे टैब के पीछे छिपा है या पूरी तरह से बंद है. सभी मामलों में पेज को onMessage कॉलबैक को हैंडल करना होगा. हालांकि, बैकग्राउंड में उपयोगकर्ता को आपके वेब ऐप्लिकेशन को फ़ोरग्राउंड में लाने की अनुमति देने के लिए, आपको onBackgroundMessage को मैनेज करना पड़ सकता है या डिसप्ले सूचना को कॉन्फ़िगर करना पड़ सकता है.

ऐप्लिकेशन की स्थिति सूचना डेटा दोनों
फ़ोरग्राउंड onMessage onMessage onMessage
बैकग्राउंड (सर्विस वर्कर) onBackgroundMessage (डिसप्ले की सूचना अपने-आप दिखने लगेगी) onBackgroundMessage onBackgroundMessage (डिसप्ले की सूचना अपने-आप दिखने लगेगी)

वेब ऐप्लिकेशन के फ़ोरग्राउंड में होने पर मैसेज मैनेज करना

onMessage इवेंट पाने के लिए, आपके ऐप्लिकेशन को firebase-messaging-sw.js में Firebase मैसेज सर्विस वर्कर तय करना होगा. इसके अलावा, getToken(): Promise<string> की मदद से SDK टूल के लिए, कोई मौजूदा सर्विस वर्कर जोड़ा जा सकता है.

Web

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

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

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

Web

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
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

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

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

Web

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

वेब ऐप्लिकेशन के बैकग्राउंड में चलने पर, मैसेज मैनेज करना

ऐप्लिकेशन के बैकग्राउंड में चलने के दौरान मिलने वाले सभी मैसेज, ब्राउज़र में एक डिसप्ले सूचना ट्रिगर करते हैं. इस सूचना के लिए विकल्प चुने जा सकते हैं, जैसे कि टाइटल या क्लिक ऐक्शन. इसके लिए, ऐप्लिकेशन सर्वर से भेजे गए अनुरोध में या क्लाइंट पर सर्विस वर्कर लॉजिक का इस्तेमाल करना होगा.

भेजने के अनुरोध में सूचना के विकल्प सेट करना

ऐप्लिकेशन सर्वर से भेजे जाने वाले सूचना मैसेज के लिए, 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 काम नहीं करता. इसलिए, आपको सभी डेटा मैसेज में सूचना पेलोड जोड़ने का सुझाव दिया जाता है. इसके अलावा, सर्विस वर्कर का इस्तेमाल करके सूचनाएं मैनेज की जा सकती हैं.

सूचना और डेटा मैसेज के बीच का अंतर जानने के लिए, मैसेज के टाइप देखें.

सर्विस वर्कर में सूचना विकल्प सेट करना

डेटा मैसेज के लिए, सर्विस वर्कर में सूचना के विकल्प सेट किए जा सकते हैं. सबसे पहले, सर्विस वर्कर में अपना ऐप्लिकेशन शुरू करें:

Web

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

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

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

Web

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
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();

विकल्प सेट करने के लिए, firebase-messaging-sw.js में onBackgroundMessage पर कॉल करें. इस उदाहरण में, हमने टाइटल, मुख्य हिस्से, और आइकॉन फ़ील्ड के साथ सूचना बनाई है.

Web

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

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

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

Web

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

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

मैसेज भेजने के अनुरोध बनाएं

विषय बनाने के बाद, क्लाइंट-साइड पर विषय के लिए क्लाइंट ऐप्लिकेशन इंस्टेंस की सदस्यता लेकर या सर्वर एपीआई की मदद से, उस विषय पर मैसेज भेजे जा सकते हैं. अगर आप पहली बार FCM के लिए अनुरोध भेज रहे हैं, तो बैकग्राउंड और सेटअप की ज़रूरी जानकारी के लिए अपने सर्वर एनवायरमेंट और FCM की गाइड देखें.

बैकएंड पर, भेजने के तरीके में, विषय का पसंदीदा नाम बताएं, जैसा कि यहां दिखाया गया है:

Node.js के लिए

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

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

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

Java

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

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

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

Python

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

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

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

शुरू करें

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

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

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

C#

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

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

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

REST

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

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

cURL निर्देश:

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

विषयों के कॉम्बिनेशन को मैसेज भेजने के लिए, condition की जानकारी दें. यह एक बूलियन एक्सप्रेशन है, जो टारगेट किए गए विषयों के बारे में बताता है. उदाहरण के लिए, इस शर्त से उन डिवाइसों पर मैसेज भेजे जाएंगे जिन्होंने 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);

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)

शुरू करें

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

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

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

C#

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

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

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

REST

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

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

cURL निर्देश:

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

नोटिफ़िकेशन पेलोड में वेब पुश प्रॉपर्टी जोड़ें

एचटीटीपी v1 एपीआई की मदद से, JSON ऑब्जेक्ट के तौर पर सूचना के अन्य विकल्प तय किए जा सकते हैं. इसमें Web Notification API से कोई भी मान्य प्रॉपर्टी शामिल होती है. अगर इस ऑब्जेक्ट में title और body फ़ील्ड मौजूद हैं, तो वे इसके बराबर के google.firebase.fcm.v1.Notification.title और google.firebase.fcm.v1.Notification.body फ़ील्ड को बदल देंगे.

एचटीटीपी पोस्ट अनुरोध

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 फ़िलहाल, ब्राउज़र पर सिर्फ़ कुछ हद तक काम करता है. प्लैटफ़ॉर्म और ब्राउज़र पर यह काम करता है या नहीं, इसकी पुष्टि करने के लिए डेवलपर को 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"

एचटीटीपी रिस्पॉन्स

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

FCM मैसेज के बारे में ज़्यादा जानने के लिए, ऐप्लिकेशन सर्वर भेजने के अनुरोध बनाएं देखें.