बिल्ड ऐप्लिकेशन सर्वर से मिले अनुरोध

Firebase Admin SDK या FCM ऐप्लिकेशन सर्वर प्रोटोकॉल का इस्तेमाल करके, मैसेज के अनुरोध बनाए जा सकते हैं और उन्हें इस तरह के टारगेट पर भेजा जा सकता है:

  • विषय का नाम
  • शर्त
  • डिवाइस रजिस्ट्रेशन टोकन
  • डिवाइस ग्रुप का नाम (सिर्फ़ प्रोटोकॉल के लिए)

पहले से तय किए गए फ़ील्ड से बने सूचना पैल्यऑड, उपयोगकर्ता के तय किए गए फ़ील्ड का डेटा पैल्यऑड या दोनों तरह के पैल्यऑड वाले मैसेज भेजे जा सकते हैं. ज़्यादा जानकारी के लिए, मैसेज टाइप देखें.

इस पेज पर दिए गए उदाहरणों में, Firebase Admin SDK (इसमें Node, Java, Python, C#, और Go) और v1 HTTP प्रोटोकॉल का इस्तेमाल करके सूचना मैसेज भेजने का तरीका बताया गया है.

चुनिंदा डिवाइसों पर मैसेज भेजना

किसी एक डिवाइस पर मैसेज भेजने के लिए, डिवाइस का रजिस्टरेशन टोकन डालें, जैसा कि दिखाया गया है. रजिस्ट्रेशन टोकन के बारे में ज़्यादा जानने के लिए, अपने प्लैटफ़ॉर्म के क्लाइंट सेटअप की जानकारी देखें.

Node.js

// This registration token comes from the client FCM SDKs.
const registrationToken = 'YOUR_REGISTRATION_TOKEN';

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

// Send a message to the device corresponding to the provided
// registration token.
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

// This registration token comes from the client FCM SDKs.
String registrationToken = "YOUR_REGISTRATION_TOKEN";

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

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

Python

# This registration token comes from the client FCM SDKs.
registration_token = 'YOUR_REGISTRATION_TOKEN'

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

# Send a message to the device corresponding to the provided
# registration token.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

शुरू करें

// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
	log.Fatalf("error getting Messaging client: %v\n", err)
}

// This registration token comes from the client FCM SDKs.
registrationToken := "YOUR_REGISTRATION_TOKEN"

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

// Send a message to the device corresponding to the provided
// registration token.
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#

// This registration token comes from the client FCM SDKs.
var registrationToken = "YOUR_REGISTRATION_TOKEN";

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

// Send a message to the device corresponding to the provided
// registration token.
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":{
      "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
      "notification":{
        "body":"This is an FCM notification message!",
        "title":"FCM Message"
      }
   }
}

cURL कमांड:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
   "notification":{
     "title":"FCM Message",
     "body":"This is an FCM Message"
   },
   "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

मैसेज भेजने के हर तरीके से, मैसेज आईडी मिलता है. Firebase Admin SDK, projects/{project_id}/messages/{message_id} फ़ॉर्मैट में आईडी स्ट्रिंग दिखाता है. एचटीटीपी प्रोटोकॉल का रिस्पॉन्स, एक JSON कुंजी होती है:

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

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

एडमिन FCM SDK की मदद से, डिवाइस रजिस्ट्रेशन टोकन की सूची में किसी मैसेज को मल्टीकास्ट किया जा सकता है. इस सुविधा का इस्तेमाल तब किया जा सकता है, जब आपको एक ही मैसेज कई डिवाइसों पर भेजना हो. हर बार कॉल करने पर, ज़्यादा से ज़्यादा 500 डिवाइस रजिस्टरेशन टोकन डाले जा सकते हैं.

रिटर्न वैल्यू में, इनपुट टोकन के क्रम के हिसाब से टोकन की सूची शामिल होती है. यह तब काम आता है, जब आपको यह देखना हो कि किन टोकन की वजह से गड़बड़ियां हुईं और फिर उन्हें सही तरीके से मैनेज करना हो.

Node.js

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

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

getMessaging().sendEachForMulticast(message)
  .then((response) => {
    if (response.failureCount > 0) {
      const failedTokens = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success) {
          failedTokens.push(registrationTokens[idx]);
        }
      });
      console.log('List of tokens that caused failures: ' + failedTokens);
    }
  });

Java

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

MulticastMessage message = MulticastMessage.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .addAllTokens(registrationTokens)
    .build();
BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
if (response.getFailureCount() > 0) {
  List<SendResponse> responses = response.getResponses();
  List<String> failedTokens = new ArrayList<>();
  for (int i = 0; i < responses.size(); i++) {
    if (!responses.get(i).isSuccessful()) {
      // The order of responses corresponds to the order of the registration tokens.
      failedTokens.add(registrationTokens.get(i));
    }
  }

  System.out.println("List of tokens that caused failures: " + failedTokens);
}

Python

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

message = messaging.MulticastMessage(
    data={'score': '850', 'time': '2:45'},
    tokens=registration_tokens,
)
response = messaging.send_each_for_multicast(message)
if response.failure_count > 0:
    responses = response.responses
    failed_tokens = []
    for idx, resp in enumerate(responses):
        if not resp.success:
            # The order of responses corresponds to the order of the registration tokens.
            failed_tokens.append(registration_tokens[idx])
    print('List of tokens that caused failures: {0}'.format(failed_tokens))

शुरू करें

// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Tokens: registrationTokens,
}

br, err := client.SendEachForMulticast(context.Background(), message)
if err != nil {
	log.Fatalln(err)
}

if br.FailureCount > 0 {
	var failedTokens []string
	for idx, resp := range br.Responses {
		if !resp.Success {
			// The order of responses corresponds to the order of the registration tokens.
			failedTokens = append(failedTokens, registrationTokens[idx])
		}
	}

	fmt.Printf("List of tokens that caused failures: %v\n", failedTokens)
}

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};
var message = new MulticastMessage()
{
    Tokens = registrationTokens,
    Data = new Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
};

var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(message);
if (response.FailureCount > 0)
{
    var failedTokens = new List<string>();
    for (var i = 0; i < response.Responses.Count; i++)
    {
        if (!response.Responses[i].IsSuccess)
        {
            // The order of responses corresponds to the order of the registration tokens.
            failedTokens.Add(registrationTokens[i]);
        }
    }

    Console.WriteLine($"List of tokens that caused failures: {failedTokens}");
}

मैसेज की सूची भेजना

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

Node.js

// Create a list containing up to 500 messages.
const messages = [];
messages.push({
  notification: { title: 'Price drop', body: '5% off all electronics' },
  token: registrationToken,
});
messages.push({
  notification: { title: 'Price drop', body: '2% off all books' },
  topic: 'readers-club',
});

getMessaging().sendEach(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

Java

// Create a list containing up to 500 messages.
List<Message> messages = Arrays.asList(
    Message.builder()
        .setNotification(Notification.builder()
            .setTitle("Price drop")
            .setBody("5% off all electronics")
            .build())
        .setToken(registrationToken)
        .build(),
    // ...
    Message.builder()
        .setNotification(Notification.builder()
            .setTitle("Price drop")
            .setBody("2% off all books")
            .build())
        .setTopic("readers-club")
        .build()
);

BatchResponse response = FirebaseMessaging.getInstance().sendEach(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");

Python

# Create a list containing up to 500 messages.
messages = [
    messaging.Message(
        notification=messaging.Notification('Price drop', '5% off all electronics'),
        token=registration_token,
    ),
    # ...
    messaging.Message(
        notification=messaging.Notification('Price drop', '2% off all books'),
        topic='readers-club',
    ),
]

response = messaging.send_each(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))

शुरू करें

// Create a list containing up to 500 messages.
messages := []*messaging.Message{
	{
		Notification: &messaging.Notification{
			Title: "Price drop",
			Body:  "5% off all electronics",
		},
		Token: registrationToken,
	},
	{
		Notification: &messaging.Notification{
			Title: "Price drop",
			Body:  "2% off all books",
		},
		Topic: "readers-club",
	},
}

br, err := client.SendEach(context.Background(), messages)
if err != nil {
	log.Fatalln(err)
}

// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)

C#

// Create a list containing up to 500 messages.
var messages = new List<Message>()
{
    new Message()
    {
        Notification = new Notification()
        {
            Title = "Price drop",
            Body = "5% off all electronics",
        },
        Token = registrationToken,
    },
    new Message()
    {
        Notification = new Notification()
        {
            Title = "Price drop",
            Body = "2% off all books",
        },
        Topic = "readers-club",
    },
};

var response = await FirebaseMessaging.DefaultInstance.SendEachAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

विषयों पर मैसेज भेजना

विषय बनाने के बाद, क्लाइंट साइड पर विषय के लिए क्लाइंट ऐप्लिकेशन इंस्टेंस की सदस्यता लेकर या सर्वर एपीआई की मदद से, विषय पर मैसेज भेजे जा सकते हैं. अगर आपने पहली बार 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

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

डिवाइस ग्रुप को मैसेज भेजना

किसी डिवाइस ग्रुप को मैसेज भेजना, किसी एक डिवाइस को मैसेज भेजने जैसा ही है. मैसेज भेजने के अनुरोधों को अनुमति देने के लिए, एक ही तरीके का इस्तेमाल किया जाता है. token फ़ील्ड को ग्रुप सूचना कुंजी पर सेट करें:

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":{
      "token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ",
      "data":{
        "hello": "This is a Firebase Cloud Messaging device group message!"
      }
   }
}

cURL कमांड

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
   "data":{
     "hello": "This is a Firebase Cloud Messaging device group message!"
   },
   "token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ"
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

डिवाइस के चालू होने पर डायरेक्ट मैसेज भेजना (सिर्फ़ Android के लिए)

डायरेक्ट बूट मोड में डिवाइसों को मैसेज भेजने के लिए, एचटीटीपी v1 या लेगसी एचटीटीपी एपीआई का इस्तेमाल किया जा सकता है. डिवाइसों को डायरेक्ट बूट मोड में भेजने से पहले, पक्का करें कि आपने क्लाइंट डिवाइसों को डायरेक्ट बूट मोड में FCM मैसेज पाने की सुविधा चालू करने के लिए, सभी चरणों को पूरा कर लिया हो.

FCM v1 एचटीटीपी एपीआई का इस्तेमाल करके भेजना

मैसेज के अनुरोध में, अनुरोध के मुख्य भाग के AndroidConfig विकल्पों में "direct_boot_ok" : true कुंजी शामिल होनी चाहिए. उदाहरण के लिए:

https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
Content-Type:application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
    "data": {
      "score": "5x1",
      "time": "15:10"
    },
    "android": {
      "direct_boot_ok": true,
    },
}

अलग-अलग प्लैटफ़ॉर्म पर मैसेज को पसंद के मुताबिक बनाना

Firebase Admin SDK और FCM v1 एचटीटीपी प्रोटोकॉल, दोनों ही आपके मैसेज के अनुरोधों को message ऑब्जेक्ट में उपलब्ध सभी फ़ील्ड सेट करने की अनुमति देते हैं. इसमें इस तरह का कॉन्टेंट शामिल है:

  • फ़ील्ड का एक सामान्य सेट, जिसे मैसेज पाने वाले सभी ऐप्लिकेशन इंस्टेंस के हिसाब से समझा जाना चाहिए.
  • AndroidConfig और WebpushConfig जैसे प्लैटफ़ॉर्म के हिसाब से फ़ील्ड के सेट, जिन्हें सिर्फ़ तय किए गए प्लैटफ़ॉर्म पर चल रहे ऐप्लिकेशन इंस्टेंस के हिसाब से समझा जाता है.

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

सामान्य फ़ील्ड का इस्तेमाल कब करना चाहिए

सामान्य फ़ील्ड का इस्तेमाल तब करें, जब:

  • Apple, Android, और वेब जैसे सभी प्लैटफ़ॉर्म पर ऐप्लिकेशन इंस्टेंस को टारगेट करना
  • विषयों पर मैसेज भेजना

सभी ऐप्लिकेशन इंस्टेंस, प्लैटफ़ॉर्म के बावजूद, इन सामान्य फ़ील्ड का इस्तेमाल कर सकते हैं:

प्लैटफ़ॉर्म के हिसाब से फ़ील्ड का इस्तेमाल कब करना चाहिए

प्लैटफ़ॉर्म के हिसाब से फ़ील्ड का इस्तेमाल तब करें, जब आपको:

  • सिर्फ़ कुछ प्लैटफ़ॉर्म पर फ़ील्ड भेजना
  • सामान्य फ़ील्ड के अलावा, प्लैटफ़ॉर्म के हिसाब से फ़ील्ड भेजना

जब आपको सिर्फ़ चुनिंदा प्लैटफ़ॉर्म पर वैल्यू भेजनी हों, तो सामान्य फ़ील्ड का इस्तेमाल न करें. इसके बजाय, प्लैटफ़ॉर्म के हिसाब से फ़ील्ड का इस्तेमाल करें. उदाहरण के लिए, अगर आपको सिर्फ़ Apple प्लैटफ़ॉर्म और वेब पर सूचना भेजनी है, लेकिन Android पर नहीं, तो आपको फ़ील्ड के दो अलग-अलग सेट इस्तेमाल करने होंगे. एक सेट Apple के लिए और दूसरा वेब के लिए.

जब किसी खास डिलीवरी के विकल्प के साथ मैसेज भेजे जा रहे हों, तो उन्हें सेट करने के लिए, प्लैटफ़ॉर्म के हिसाब से फ़ील्ड का इस्तेमाल करें. अगर आप चाहें, तो हर प्लैटफ़ॉर्म के लिए अलग-अलग वैल्यू तय की जा सकती हैं. हालांकि, अगर आपको सभी प्लैटफ़ॉर्म पर एक ही वैल्यू सेट करनी है, तो भी आपको प्लैटफ़ॉर्म के हिसाब से फ़ील्ड का इस्तेमाल करना होगा. ऐसा इसलिए है, क्योंकि हर प्लैटफ़ॉर्म पर वैल्यू को थोड़ा अलग तरीके से समझा जा सकता है. उदाहरण के लिए, Android पर 'सेवा के बंद होने का समय', सेकंड में खत्म होने का समय के तौर पर सेट होता है, जबकि Apple पर इसे खत्म होने की तारीख के तौर पर सेट किया जाता है.

उदाहरण: रंग और आइकॉन के विकल्पों के साथ सूचना मैसेज

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

Android के लिए, अनुरोध में Android डिवाइसों पर दिखाने के लिए एक खास आइकॉन और रंग सेट किया जाता है. AndroidNotification के रेफ़रंस में बताया गया है कि रंग #rrggbb फ़ॉर्मैट में दिया जाता है. साथ ही, इमेज, Android ऐप्लिकेशन में मौजूद ड्रॉबल आइकॉन रिसॉर्स होनी चाहिए.

उपयोगकर्ता के डिवाइस पर विज़ुअल इफ़ेक्ट का अनुमानित असर यहां बताया गया है:

दो डिवाइसों की ड्रॉइंग, जिसमें से एक पर कस्टम आइकॉन और कलर दिख रहा है

Node.js

const topicName = 'industry-tech';

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.'
  },
  android: {
    notification: {
      icon: 'stock_ticker_update',
      color: '#7e55c3'
    }
  },
  topic: topicName,
};

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

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())
    .setAndroidConfig(AndroidConfig.builder()
        .setTtl(3600 * 1000)
        .setNotification(AndroidNotification.builder()
            .setIcon("stock_ticker_update")
            .setColor("#f45342")
            .build())
        .build())
    .setApnsConfig(ApnsConfig.builder()
        .setAps(Aps.builder()
            .setBadge(42)
            .build())
        .build())
    .setTopic("industry-tech")
    .build();

Python

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.',
    ),
    android=messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600),
        priority='normal',
        notification=messaging.AndroidNotification(
            icon='stock_ticker_update',
            color='#f45342'
        ),
    ),
    apns=messaging.APNSConfig(
        payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42),
        ),
    ),
    topic='industry-tech',
)

शुरू करें

oneHour := time.Duration(1) * time.Hour
badge := 42
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.",
	},
	Android: &messaging.AndroidConfig{
		TTL: &oneHour,
		Notification: &messaging.AndroidNotification{
			Icon:  "stock_ticker_update",
			Color: "#f45342",
		},
	},
	APNS: &messaging.APNSConfig{
		Payload: &messaging.APNSPayload{
			Aps: &messaging.Aps{
				Badge: &badge,
			},
		},
	},
	Topic: "industry-tech",
}

C#

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.",
    },
    Android = new AndroidConfig()
    {
        TimeToLive = TimeSpan.FromHours(1),
        Notification = new AndroidNotification()
        {
            Icon = "stock_ticker_update",
            Color = "#f45342",
        },
    },
    Apns = new ApnsConfig()
    {
        Aps = new Aps()
        {
            Badge = 42,
        },
    },
    Topic = "industry-tech",
};

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":"industry-tech",
     "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."
     },
     "android":{
       "notification":{
         "icon":"stock_ticker_update",
         "color":"#7e55c3"
       }
     }
   }
 }

मैसेज के मुख्य हिस्से में, प्लैटफ़ॉर्म के हिसाब से ब्लॉक में उपलब्ध कुंजियों के बारे में पूरी जानकारी पाने के लिए, एचटीटीपी v1 का रेफ़रंस दस्तावेज़ देखें.

उदाहरण: पसंद के मुताबिक इमेज वाली सूचना

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

डिसप्ले नोटिफ़िकेशन में इमेज की आसान ड्रॉइंग

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Sparky says hello!'
  },
  android: {
    notification: {
      imageUrl: 'https://foo.bar.pizza-monster.png'
    }
  },
  apns: {
    payload: {
      aps: {
        'mutable-content': 1
      }
    },
    fcm_options: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  webpush: {
    headers: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  topic: topicName,
};

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

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":"industry-tech",
     "notification":{
       "title":"Sparky says hello!",
     },
     "android":{
       "notification":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "mutable-content":1
         }
       },
       "fcm_options": {
           "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "webpush":{
       "headers":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     }
   }
 }

मैसेज के मुख्य हिस्से में, प्लैटफ़ॉर्म के हिसाब से ब्लॉक में उपलब्ध कुंजियों के बारे में पूरी जानकारी पाने के लिए, एचटीटीपी v1 का रेफ़रंस दस्तावेज़ देखें.

उदाहरण: क्लिक ऐक्शन के साथ सूचना मैसेज

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

वेब पेज खोलने के लिए, टैप करने वाले उपयोगकर्ता की आसान ड्रॉइंग

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Breaking News....'
  },
  android: {
    notification: {
      clickAction: 'news_intent'
    }
  },
  apns: {
    payload: {
      aps: {
        'category': 'INVITE_CATEGORY'
      }
    }
  },
  webpush: {
    fcmOptions: {
      link: 'breakingnews.html'
    }
  },
  topic: topicName,
};

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

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":"industry-tech",
     "notification":{
       "title":"Breaking News...",
     },
     "android":{
       "notification":{
         "click_action":"news_intent"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "category" : "INVITE_CATEGORY"
         }
       },
     },
     "webpush":{
       "fcm_options":{
         "link":"breakingnews.html"
       }
     }
   }
 }

मैसेज के मुख्य हिस्से में, प्लैटफ़ॉर्म के हिसाब से ब्लॉक में उपलब्ध कुंजियों के बारे में पूरी जानकारी पाने के लिए, एचटीटीपी v1 का रेफ़रंस दस्तावेज़ देखें.

उदाहरण: स्थानीय भाषा में सूचना देने के विकल्पों वाला मैसेज

नीचे दिए गए उदाहरण में, अनुरोध भेजने की सुविधा का इस्तेमाल करके, क्लाइंट को स्थानीय भाषा में मैसेज दिखाने के लिए, स्थानीय भाषा में अनुवाद करने के विकल्प भेजे जाते हैं. यहां उपयोगकर्ता के डिवाइस पर विज़ुअल इफ़ेक्ट का अनुमानित डेटा दिया गया है:

अंग्रेज़ी और स्पैनिश भाषा में टेक्स्ट दिखाने वाले दो डिवाइसों की आसान ड्रॉइंग

Node.js

var topicName = 'industry-tech';

var message = {
  android: {
    ttl: 3600000,
    notification: {
      bodyLocKey: 'STOCK_NOTIFICATION_BODY',
      bodyLocArgs: ['FooCorp', '11.80', '835.67', '1.43']
    }
  },
  apns: {
    payload: {
      aps: {
        alert: {
          locKey: 'STOCK_NOTIFICATION_BODY',
          locArgs: ['FooCorp', '11.80', '835.67', '1.43']
        }
      }
    }
  },
  topic: topicName,
};

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

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":"Tech",
             "android":{
               "ttl":"3600s",
               "notification":{
                 "body_loc_key": "STOCK_NOTIFICATION_BODY",
                 "body_loc_args":  ["FooCorp", "11.80", "835.67", "1.43"],
               },
             },
             "apns":{
               "payload":{
                 "aps":{
                   "alert" : {
                     "loc-key": "STOCK_NOTIFICATION_BODY",
                     "loc-args":  ["FooCorp", "11.80", "835.67", "1.43"],
                    },
                 },
               },
             },
  },
}'

मैसेज के मुख्य हिस्से में, प्लैटफ़ॉर्म के हिसाब से ब्लॉक में उपलब्ध कुंजियों के बारे में पूरी जानकारी पाने के लिए, एचटीटीपी v1 का रेफ़रंस दस्तावेज़ देखें.