ساخت سرور برنامه درخواست ارسال

با استفاده از Firebase Admin SDK یا پروتکل‌های سرور برنامه FCM ، می‌توانید درخواست‌های پیام بسازید و آنها را به این نوع اهداف ارسال کنید:

  • نام موضوع
  • وضعیت
  • رمز ثبت دستگاه
  • نام گروه دستگاه (فقط پروتکل)

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

مثال‌های موجود در این صفحه نحوه ارسال پیام‌های اعلان را با استفاده از Firebase Admin SDK (که از Node ، Java ، Python ، C# و Go پشتیبانی می‌کند) و پروتکل HTTP v1 نشان می‌دهد.

ارسال پیام به دستگاه های خاص

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

// 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);
  });
// 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);
# 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)
// 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);
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 رشته ID را در قالب projects/{project_id}/messages/{message_id} برمی‌گرداند. پاسخ پروتکل HTTP یک کلید JSON است:

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

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

Admin FCM APIs به شما امکان می دهد پیام را به لیستی از نشانه های ثبت دستگاه چندپخش کنید. شما می توانید تا 500 توکن ثبت دستگاه را در هر فراخوانی مشخص کنید.

// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# Create a list containing up to 500 registration tokens.
# 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_multicast(message)
# 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 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.SendMulticast(context.Background(), message)
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)
// Create a list containing up to 500 registration tokens.
// 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);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

مقدار بازگشتی لیستی از نشانه ها است که با ترتیب توکن های ورودی مطابقت دارد. این زمانی مفید است که می‌خواهید بررسی کنید کدام نشانه‌ها منجر به خطا شده‌اند.

// 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().sendMulticast(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);
    }
  });
// 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().sendMulticast(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);
}
# 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_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.SendMulticast(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)
}
// 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}");
}

ارسال پیام به موضوعات

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

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

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

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

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

// 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 استفاده کنید. اگر در حال حاضر با استفاده از APIهای ارسال قدیمی قدیمی برای HTTP یا XMPP یا هر یک از نسخه‌های قدیمی‌تر Firebase Admin SDK برای Node.js بر اساس پروتکل‌های قدیمی، به گروه‌های دستگاه ارسال می‌کنید، اکیداً توصیه می‌کنیم در اولین فرصت به API HTTP v1 مهاجرت کنید . APIهای ارسال قدیمی در ژوئن 2024 غیرفعال و حذف خواهند شد.

ارسال پیام به یک گروه دستگاه بسیار شبیه به ارسال پیام به یک دستگاه جداگانه است، با استفاده از همان روش برای تأیید درخواست‌های ارسال . فیلد token را روی کلید اعلان گروه تنظیم کنید:

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

یک دسته پیام بفرستید

Admin SDK از ارسال پیام‌ها به صورت دسته‌ای پشتیبانی می‌کند. شما می توانید حداکثر 500 پیام را در یک دسته گروه بندی کنید و همه آنها را در یک تماس API ارسال کنید، با بهبود عملکرد قابل توجهی نسبت به ارسال درخواست های HTTP جداگانه برای هر پیام.

از این ویژگی می توان برای ایجاد مجموعه ای سفارشی از پیام ها و ارسال آنها به گیرندگان مختلف، از جمله موضوعات یا نشانه های ثبت دستگاه خاص استفاده کرد. از این ویژگی زمانی استفاده کنید که، برای مثال، نیاز دارید به طور همزمان پیام هایی را با جزئیات کمی متفاوت در متن پیام به مخاطبان مختلف ارسال کنید.

// 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().sendAll(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// 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().sendAll(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# 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_all(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.SendAll(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)
// 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");

ارسال پیام‌های مستقیم با قابلیت بوت (فقط اندروید)

می‌توانید با استفاده از HTTP v1 یا APIهای قدیمی HTTP، پیام‌ها را در حالت بوت مستقیم به دستگاه‌ها ارسال کنید. قبل از ارسال به دستگاه‌ها در حالت بوت مستقیم، مطمئن شوید که مراحل فعال کردن دستگاه‌های سرویس گیرنده را برای دریافت پیام‌های FCM در حالت راه‌اندازی مستقیم انجام داده‌اید.

ارسال با استفاده از FCM v1 HTTP API

درخواست پیام باید شامل کلید "direct_boot_ok" : true در گزینه های AndroidConfig بدنه درخواست باشد. به عنوان مثال:

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 HTTP هر دو به درخواست های پیام شما اجازه می دهند تمام فیلدهای موجود در شی message را تنظیم کنند. این شامل:

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

بلوک‌های مخصوص پلتفرم به شما انعطاف‌پذیری می‌دهند تا پیام‌ها را برای پلتفرم‌های مختلف سفارشی کنید تا اطمینان حاصل کنید که هنگام دریافت به‌درستی با آنها برخورد می‌شود. پشتیبان FCM تمام پارامترهای مشخص شده را در نظر می گیرد و پیام را برای هر پلتفرم سفارشی می کند.

زمان استفاده از فیلدهای مشترک

وقتی هستید از فیلدهای مشترک استفاده کنید:

  • هدف قرار دادن نمونه های برنامه در همه پلتفرم ها - اپل، اندروید و وب
  • ارسال پیام به موضوعات

همه نمونه های برنامه، صرف نظر از پلتفرم، می توانند فیلدهای مشترک زیر را تفسیر کنند:

زمان استفاده از فیلدهای مخصوص پلتفرم

زمانی که می خواهید از فیلدهای مخصوص پلتفرم استفاده کنید:

  • فیلدها را فقط به پلتفرم های خاص ارسال کنید
  • علاوه بر فیلدهای مشترک، فیلدهای مخصوص پلتفرم را ارسال کنید

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

وقتی پیام هایی با گزینه های تحویل خاص ارسال می کنید، از فیلدهای مخصوص پلتفرم برای تنظیم آنها استفاده کنید. در صورت تمایل می توانید مقادیر مختلفی را برای هر پلتفرم مشخص کنید. با این حال، حتی زمانی که می‌خواهید اساساً مقدار یکسانی را در بین پلتفرم‌ها تنظیم کنید، باید از فیلدهای مخصوص پلتفرم استفاده کنید. این به این دلیل است که هر پلتفرم ممکن است مقدار را کمی متفاوت تفسیر کند - برای مثال، زمان برای زندگی در Android به عنوان زمان انقضا بر حسب ثانیه تنظیم می شود، در حالی که در اپل به عنوان تاریخ انقضا تنظیم می شود.

مثال: پیام اعلان با گزینه های رنگ و نماد

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

برای اندروید، درخواست یک نماد و رنگ خاص را برای نمایش در دستگاه های اندرویدی تنظیم می کند. همانطور که در مرجع AndroidNotification اشاره شد، رنگ با فرمت #rrggbb مشخص شده است و تصویر باید یک منبع نماد قابل ترسیم محلی برای برنامه Android باشد.

در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده از دو دستگاه، با نمایش نماد و رنگ سفارشی

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);
  });
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();
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",
}
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",
};
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"
       }
     }
   }
 }

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

مثال: پیام اعلان با یک تصویر سفارشی

مثال زیر درخواست ارسال یک عنوان اعلان مشترک را به همه پلتفرم ها ارسال می کند، اما یک تصویر نیز ارسال می کند. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده یک تصویر در یک اعلان نمایشگر

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

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

مثال: پیام اعلان با یک اقدام کلیک مرتبط

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

طراحی ساده یک ضربه کاربر برای باز کردن یک صفحه وب

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

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

مثال: پیام اعلان با گزینه های محلی سازی

مثال زیر درخواست ارسال گزینه‌های محلی‌سازی را برای مشتری ارسال می‌کند تا پیام‌های محلی را نمایش دهد. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده از دو دستگاه که متن را به زبان انگلیسی و اسپانیایی نشان می دهد

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);
  });
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"],
                    },
                 },
               },
             },
  },
}'

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

کدهای خطا REST برای HTTP v1 API

پاسخ های خطای HTTP برای HTTP v1 API حاوی کد خطا، پیام خطا و وضعیت خطا است. آنها همچنین ممکن است حاوی یک آرایه details با جزئیات بیشتر در مورد خطا باشند.

در اینجا دو نمونه پاسخ خطا آورده شده است:

مثال 1: پاسخ خطا از درخواست HTTP v1 API با مقدار نامعتبر در پیام داده

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

مثال 2: پاسخ خطا از یک درخواست API HTTP v1 با یک نشانه ثبت نام معتبر

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

توجه داشته باشید که هر دو پیام کد و وضعیت یکسانی دارند، اما آرایه جزئیات حاوی مقادیر در انواع مختلف است. نمونه اول دارای نوع type.googleapis.com/google.rpc.BadRequest است که نشان دهنده خطا در مقادیر درخواست است. مثال دوم با نوع type.googleapis.com/google.firebase.fcm.v1.FcmError دارای یک خطای خاص FCM است. برای بسیاری از خطاها، آرایه جزئیات حاوی اطلاعاتی است که برای اشکال زدایی و یافتن وضوح نیاز دارید.

جدول زیر کدهای خطای FCM v1 REST API و توضیحات آنها را فهرست می کند.

کد خطا مراحل شرح و تفکیک
UNSPECIFIED_ERROR اطلاعات بیشتری در مورد این خطا در دسترس نیست. هیچ کدام.
INVALID_ARGUMENT (کد خطای HTTP = 400) پارامترهای درخواست نامعتبر بودند. پسوندی از نوع google.rpc.BadRequest برگردانده می شود تا مشخص شود کدام فیلد نامعتبر است. دلایل بالقوه شامل ثبت نامعتبر، نام بسته نامعتبر، پیام خیلی بزرگ، کلید داده نامعتبر، TTL نامعتبر، یا سایر پارامترهای نامعتبر است.
ثبت نام نامعتبر : فرمت رمز ثبت نامی که به سرور ارسال می کنید را بررسی کنید. مطمئن شوید که با نشانه ثبتی که برنامه مشتری از ثبت نام در FCM دریافت می کند مطابقت دارد. نشانه را کوتاه نکنید یا کاراکترهای اضافی اضافه نکنید.
نام بسته نامعتبر : مطمئن شوید که پیام به نشانه ثبتی که نام بسته آن با مقدار ارسال شده در درخواست مطابقت دارد، خطاب شده است.
پیام خیلی بزرگ : بررسی کنید که حجم کل داده‌های محموله موجود در یک پیام از محدودیت‌های FCM تجاوز نکند: 4096 بایت برای بیشتر پیام‌ها، یا 2048 بایت در مورد پیام‌ها به موضوعات. این شامل کلیدها و مقادیر می شود.
کلید داده نامعتبر : بررسی کنید که داده‌های محموله حاوی کلید (مانند از، یا gcm، یا هر مقداری که پیشوند Google است) نباشد که به صورت داخلی توسط FCM استفاده می‌شود. توجه داشته باشید که برخی از کلمات (مانند collapse_key) توسط FCM نیز استفاده می شوند اما در payload مجاز هستند، در این صورت مقدار payload با مقدار FCM لغو می شود.
TTL نامعتبر : بررسی کنید که مقدار استفاده شده در ttl یک عدد صحیح باشد که مدت زمان بر حسب ثانیه را بین 0 تا 2,419,200 (4 هفته) نشان می دهد.
پارامترهای نامعتبر : بررسی کنید که پارامترهای ارائه شده نام و نوع مناسبی داشته باشند.
UNREGISTERED (کد خطای HTTP = 404) نمونه برنامه از FCM ثبت نشده است. این معمولاً به این معنی است که توکن مورد استفاده دیگر معتبر نیست و باید از یک توکن جدید استفاده شود. این خطا می تواند ناشی از گم شدن توکن های ثبت نام یا توکن های ثبت نشده باشد.
عدم ثبت نام : اگر هدف پیام یک مقدار token است، بررسی کنید که درخواست حاوی نشانه ثبت باشد.
ثبت نشده : یک رمز ثبت موجود ممکن است در تعدادی از سناریوها از بین برود، از جمله:
- اگر برنامه مشتری با FCM لغو ثبت نام کند.
- اگر برنامه مشتری به طور خودکار ثبت نشده باشد، در صورتی که کاربر برنامه را حذف نصب کند، ممکن است اتفاق بیفتد. به عنوان مثال، در iOS، اگر سرویس بازخورد APNs توکن APN را نامعتبر گزارش کند.
- اگر رمز ثبت نام منقضی شود (برای مثال، ممکن است Google تصمیم بگیرد که نشانه های ثبت نام را به روز کند، یا نشانه APNs برای دستگاه های iOS منقضی شده است).
- اگر برنامه سرویس گیرنده به روز شده است اما نسخه جدید برای دریافت پیام پیکربندی نشده است.
برای همه این موارد، این رمز ثبت نام را از سرور برنامه حذف کنید و استفاده از آن برای ارسال پیام را متوقف کنید.
SENDER_ID_MISMATCH (کد خطای HTTP = 403) شناسه فرستنده احراز هویت شده با شناسه فرستنده رمز ثبت نام متفاوت است. یک نشانه ثبت نام به گروه خاصی از فرستندگان گره خورده است. هنگامی که یک برنامه مشتری برای FCM ثبت نام می کند، باید مشخص کند که کدام فرستنده مجاز به ارسال پیام است. هنگام ارسال پیام به برنامه مشتری باید از یکی از آن شناسه های فرستنده استفاده کنید. اگر به فرستنده دیگری بروید، نشانه‌های ثبت‌نام موجود کار نمی‌کنند.
QUOTA_EXCEEDED (کد خطای HTTP = 429) از محدودیت ارسال برای هدف پیام فراتر رفت. پسوندی از نوع google.rpc.QuotaFailure برگردانده می شود تا مشخص شود از کدام سهمیه فراتر رفته است. این خطا می تواند ناشی از فراتر رفتن از سهمیه نرخ پیام، فراتر از سهمیه نرخ پیام دستگاه، یا فراتر از سهمیه نرخ پیام موضوعی باشد.
نرخ پیام بیش از حد : نرخ ارسال پیام ها بسیار بالا است. شما باید نرخ کلی ارسال پیام را کاهش دهید. از عقب نشینی نمایی با حداقل تاخیر اولیه 1 دقیقه برای امتحان مجدد پیام های رد شده استفاده کنید.
نرخ پیام دستگاه بیش از حد است : نرخ پیام‌ها به یک دستگاه خاص بسیار زیاد است. محدودیت نرخ پیام برای یک دستگاه را ببینید . تعداد پیام‌های ارسال شده به این دستگاه را کاهش دهید و برای ارسال مجدد از عقب‌نشینی نمایی استفاده کنید.
نرخ پیام موضوع بیش از حد است : نرخ پیام به مشترکین یک موضوع خاص بسیار زیاد است. تعداد پیام‌های ارسال‌شده برای این موضوع را کاهش دهید و برای ارسال مجدد از عقب‌نشینی نمایی با حداقل تأخیر اولیه ۱ دقیقه استفاده کنید.
UNAVAILABLE (کد خطای HTTP = 503) سرور بیش از حد بارگیری شده است. سرور نتوانست به موقع درخواست را پردازش کند. همان درخواست را دوباره امتحان کنید، اما باید:
- اگر هدر Retry-After در پاسخ سرور اتصال FCM گنجانده شده است، به آن احترام بگذارید.
- اجرای عقب نشینی نمایی در مکانیسم تلاش مجدد. (مثلاً اگر یک ثانیه قبل از اولین تلاش مجدد صبر کرده اید، حداقل دو ثانیه قبل از امتحان بعدی صبر کنید، سپس 4 ثانیه و غیره). اگر چندین پیام ارسال می‌کنید، از جیترینگ استفاده کنید. برای اطلاعات بیشتر، به مدیریت مجدد مراجعه کنید ، یا داشبورد وضعیت FCM را بررسی کنید تا تشخیص دهید که آیا اختلالات مداوم سرویس بر FCM تأثیر می گذارد یا خیر. فرستنده هایی که مشکل ایجاد می کنند در معرض خطر رد شدن هستند.
INTERNAL (کد خطای HTTP = 500) یک خطای داخلی ناشناخته رخ داد. سرور هنگام تلاش برای پردازش درخواست با خطایی مواجه شد. می‌توانید همان درخواست را به دنبال پیشنهادهایی که در «کنترل تلاش‌های مجدد» یا بررسی داشبورد وضعیت FCM ارائه شده است، دوباره امتحان کنید. برای شناسایی اینکه آیا اختلالات مداوم سرویس بر FCM تأثیر می گذارد یا خیر. اگر خطا ادامه داشت، لطفاً با پشتیبانی Firebase تماس بگیرید.
THIRD_PARTY_AUTH_ERROR (کد خطای HTTP = 401) گواهینامه APN یا کلید تأیید وب فشار نامعتبر یا گم شده بود. پیامی که برای یک دستگاه iOS یا ثبت وب پوش هدف گذاری شده است ارسال نشد. اعتبار اعتبارنامه توسعه و تولید خود را بررسی کنید.

کدهای خطای ادمین

جدول زیر کدهای خطای Firebase Admin FCM API و توضیحات آنها، از جمله مراحل وضوح پیشنهادی را فهرست می‌کند.

کد خطا مراحل شرح و تفکیک
messaging/invalid-argument یک آرگومان نامعتبر به روش FCM ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-recipient گیرنده پیام مورد نظر نامعتبر است. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-payload یک شیء محموله پیام نامعتبر ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-data-payload-key محموله پیام داده حاوی یک کلید نامعتبر است. به مستندات مرجع DataMessagePayload برای کلیدهای محدود مراجعه کنید.
messaging/payload-size-limit-exceeded محموله پیام ارائه شده از محدودیت های اندازه FCM بیشتر است. محدودیت برای اکثر پیام ها 4096 بایت است. برای پیام های ارسال شده به موضوعات، محدودیت 2048 بایت است. اندازه کل محموله شامل کلیدها و مقادیر است.
messaging/invalid-options یک شیء گزینه های پیام نامعتبر ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-registration-token رمز ثبت نام معتبر ارائه شده است. مطمئن شوید که با نشانه ثبتی که برنامه مشتری از ثبت نام در FCM دریافت می کند مطابقت دارد. از کوتاه کردن یا اضافه کردن کاراکترهای اضافی به آن خودداری کنید.
messaging/registration-token-not-registered رمز ثبت نام ارائه شده ثبت نشده است. نشانه ثبت نام معتبر قبلی به دلایل مختلفی می تواند لغو ثبت شود، از جمله:
  • برنامه مشتری خود را از FCM لغو ثبت کرد.
  • برنامه مشتری به طور خودکار لغو ثبت شد. اگر کاربر برنامه را حذف نصب کند یا در پلتفرم‌های اپل، اگر سرویس بازخورد APNs توکن APN را نامعتبر گزارش کرده باشد، ممکن است این اتفاق بیفتد.
  • ژتون ثبت نام منقضی شده است. برای مثال، ممکن است Google تصمیم بگیرد که نشانه‌های ثبت نام را به‌روزرسانی کند یا نشانه‌های APN ممکن است برای دستگاه‌های اپل منقضی شده باشد.
  • برنامه مشتری به روز شد، اما نسخه جدید برای دریافت پیام پیکربندی نشده است.
برای همه این موارد، این رمز ثبت نام را حذف کنید و استفاده از آن برای ارسال پیام را متوقف کنید.
messaging/invalid-package-name این پیام به نشانه ثبت نامی که نام بسته آن با گزینه restrictedPackageName ارائه شده مطابقت ندارد، خطاب شده است.
messaging/message-rate-exceeded نرخ پیام به یک هدف خاص بسیار بالا است. تعداد پیام های ارسال شده به این دستگاه یا موضوع را کاهش دهید و فوراً ارسال مجدد به این هدف را تکرار نکنید.
messaging/device-message-rate-exceeded نرخ پیام به یک دستگاه خاص بسیار بالا است. تعداد پیام های ارسال شده به این دستگاه را کاهش دهید و فوراً ارسال مجدد به این دستگاه را تکرار نکنید.
messaging/topics-message-rate-exceeded نرخ پیام به مشترکین یک موضوع خاص بسیار زیاد است. تعداد پیام های ارسال شده برای این موضوع را کاهش دهید و بلافاصله ارسال مجدد به این موضوع را تکرار نکنید.
messaging/too-many-topics یک نشانه ثبت نام در حداکثر تعداد موضوع مشترک شده است و دیگر نمی توان در آن مشترک شد.
messaging/invalid-apns-credentials پیامی که برای دستگاه Apple مورد هدف قرار گرفته است ارسال نشد زیرا گواهینامه SSL APN های مورد نیاز آپلود نشده یا منقضی شده است. اعتبار گواهی های توسعه و تولید خود را بررسی کنید.
messaging/mismatched-credential اعتبار مورد استفاده برای احراز هویت این SDK مجوز ارسال پیام به دستگاه مربوط به رمز ثبت نام ارائه شده را ندارد. اطمینان حاصل کنید که اعتبار و رمز ثبت نام هر دو متعلق به یک پروژه Firebase هستند. برای مستندات مربوط به نحوه احراز هویت Firebase Admin SDK s ، به افزودن Firebase به برنامه خود مراجعه کنید.
messaging/authentication-error SDK نمی تواند در سرورهای FCM احراز هویت شود. اطمینان حاصل کنید که Firebase Admin SDK با اعتباری که دارای مجوزهای مناسب برای ارسال پیام‌های FCM است، احراز هویت کنید. برای مستندات مربوط به نحوه احراز هویت Firebase Admin SDK s ، به افزودن Firebase به برنامه خود مراجعه کنید.
messaging/server-unavailable سرور FCM نتوانست به موقع درخواست را پردازش کند. شما باید همان درخواست را دوباره امتحان کنید، اما باید:
  • اگر سرصفحه Retry-After در پاسخ سرور اتصال FCM گنجانده شده است، به آن احترام بگذارید.
  • در مکانیسم تلاش مجدد خود، عقب نشینی نمایی را اجرا کنید. به عنوان مثال، اگر قبل از اولین تلاش مجدد یک ثانیه صبر کرده اید، حداقل دو ثانیه قبل از امتحان بعدی، سپس چهار ثانیه و غیره صبر کنید. اگر چندین پیام ارسال می کنید، هر کدام را به طور مستقل با مقدار تصادفی اضافی به تاخیر بیندازید تا از صدور درخواست جدید برای همه پیام ها به طور همزمان جلوگیری کنید.
فرستنده هایی که مشکل ایجاد می کنند در معرض خطر قرار گرفتن در لیست سیاه هستند.
messaging/internal-error سرور FCM هنگام تلاش برای پردازش درخواست با خطا مواجه شد. می‌توانید با پیروی از الزامات فهرست‌شده در ردیف messaging/server-unavailable در بالا، همان درخواست را دوباره امتحان کنید. اگر خطا ادامه داشت، لطفاً مشکل را به کانال پشتیبانی گزارش اشکال ما گزارش دهید.
messaging/unknown-error یک خطای ناشناخته سرور برگردانده شد. برای جزئیات بیشتر پاسخ سرور خام را در پیام خطا مشاهده کنید. اگر این خطا را دریافت کردید، لطفاً پیام خطای کامل را به کانال پشتیبانی گزارش اشکال گزارش دهید.
،

با استفاده از Firebase Admin SDK یا پروتکل‌های سرور برنامه FCM ، می‌توانید درخواست‌های پیام بسازید و آنها را به این نوع اهداف ارسال کنید:

  • نام موضوع
  • وضعیت
  • رمز ثبت دستگاه
  • نام گروه دستگاه (فقط پروتکل)

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

مثال‌های موجود در این صفحه نحوه ارسال پیام‌های اعلان را با استفاده از Firebase Admin SDK (که از Node ، Java ، Python ، C# و Go پشتیبانی می‌کند) و پروتکل HTTP v1 نشان می‌دهد.

ارسال پیام به دستگاه های خاص

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

// 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);
  });
// 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);
# 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)
// 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);
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 رشته ID را در قالب projects/{project_id}/messages/{message_id} برمی‌گرداند. پاسخ پروتکل HTTP یک کلید JSON است:

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

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

Admin FCM APIs به شما امکان می دهد پیام را به لیستی از نشانه های ثبت دستگاه چندپخش کنید. شما می توانید تا 500 توکن ثبت دستگاه را در هر فراخوانی مشخص کنید.

// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# Create a list containing up to 500 registration tokens.
# 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_multicast(message)
# 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 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.SendMulticast(context.Background(), message)
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)
// Create a list containing up to 500 registration tokens.
// 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);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

مقدار بازگشتی لیستی از نشانه ها است که با ترتیب توکن های ورودی مطابقت دارد. این زمانی مفید است که می‌خواهید بررسی کنید کدام نشانه‌ها منجر به خطا شده‌اند.

// 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().sendMulticast(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);
    }
  });
// 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().sendMulticast(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);
}
# 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_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.SendMulticast(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)
}
// 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}");
}

ارسال پیام به موضوعات

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

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

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

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

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

// 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 استفاده کنید. اگر در حال حاضر با استفاده از APIهای ارسال قدیمی قدیمی برای HTTP یا XMPP یا هر یک از نسخه‌های قدیمی‌تر Firebase Admin SDK برای Node.js بر اساس پروتکل‌های قدیمی، به گروه‌های دستگاه ارسال می‌کنید، اکیداً توصیه می‌کنیم در اولین فرصت به API HTTP v1 مهاجرت کنید . APIهای ارسال قدیمی در ژوئن 2024 غیرفعال و حذف خواهند شد.

ارسال پیام به یک گروه دستگاه بسیار شبیه به ارسال پیام به یک دستگاه جداگانه است، با استفاده از همان روش برای تأیید درخواست‌های ارسال . فیلد token را روی کلید اعلان گروه تنظیم کنید:

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

یک دسته پیام بفرستید

Admin SDK از ارسال پیام‌ها به صورت دسته‌ای پشتیبانی می‌کند. شما می توانید حداکثر 500 پیام را در یک دسته گروه بندی کنید و همه آنها را در یک تماس API ارسال کنید، با بهبود عملکرد قابل توجهی نسبت به ارسال درخواست های HTTP جداگانه برای هر پیام.

از این ویژگی می توان برای ایجاد مجموعه ای سفارشی از پیام ها و ارسال آنها به گیرندگان مختلف، از جمله موضوعات یا نشانه های ثبت دستگاه خاص استفاده کرد. از این ویژگی زمانی استفاده کنید که، برای مثال، نیاز دارید به طور همزمان پیام هایی را با جزئیات کمی متفاوت در متن پیام به مخاطبان مختلف ارسال کنید.

// 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().sendAll(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// 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().sendAll(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# 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_all(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.SendAll(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)
// 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");

ارسال پیام‌های مستقیم با قابلیت بوت (فقط اندروید)

می‌توانید با استفاده از HTTP v1 یا APIهای قدیمی HTTP، پیام‌ها را در حالت بوت مستقیم به دستگاه‌ها ارسال کنید. قبل از ارسال به دستگاه‌ها در حالت بوت مستقیم، مطمئن شوید که مراحل فعال کردن دستگاه‌های سرویس گیرنده را برای دریافت پیام‌های FCM در حالت راه‌اندازی مستقیم انجام داده‌اید.

ارسال با استفاده از FCM v1 HTTP API

درخواست پیام باید شامل کلید "direct_boot_ok" : true در گزینه های AndroidConfig بدنه درخواست باشد. به عنوان مثال:

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 HTTP هر دو به درخواست های پیام شما اجازه می دهند تمام فیلدهای موجود در شی message را تنظیم کنند. این شامل:

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

بلوک‌های مخصوص پلتفرم به شما انعطاف‌پذیری می‌دهند تا پیام‌ها را برای پلتفرم‌های مختلف سفارشی کنید تا اطمینان حاصل کنید که هنگام دریافت به‌درستی با آنها برخورد می‌شود. پشتیبان FCM تمام پارامترهای مشخص شده را در نظر می گیرد و پیام را برای هر پلتفرم سفارشی می کند.

زمان استفاده از فیلدهای مشترک

وقتی هستید از فیلدهای مشترک استفاده کنید:

  • هدف قرار دادن نمونه های برنامه در همه پلتفرم ها - اپل، اندروید و وب
  • ارسال پیام به موضوعات

همه نمونه های برنامه، صرف نظر از پلتفرم، می توانند فیلدهای مشترک زیر را تفسیر کنند:

زمان استفاده از فیلدهای مخصوص پلتفرم

زمانی که می خواهید از فیلدهای مخصوص پلتفرم استفاده کنید:

  • فیلدها را فقط به پلتفرم های خاص ارسال کنید
  • علاوه بر فیلدهای مشترک، فیلدهای مخصوص پلتفرم را ارسال کنید

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

وقتی پیام هایی با گزینه های تحویل خاص ارسال می کنید، از فیلدهای مخصوص پلتفرم برای تنظیم آنها استفاده کنید. در صورت تمایل می توانید مقادیر مختلفی را برای هر پلتفرم مشخص کنید. با این حال، حتی زمانی که می‌خواهید اساساً مقدار یکسانی را در بین پلتفرم‌ها تنظیم کنید، باید از فیلدهای مخصوص پلتفرم استفاده کنید. این به این دلیل است که هر پلتفرم ممکن است مقدار را کمی متفاوت تفسیر کند - برای مثال، زمان برای زندگی در Android به عنوان زمان انقضا بر حسب ثانیه تنظیم می شود، در حالی که در اپل به عنوان تاریخ انقضا تنظیم می شود.

مثال: پیام اعلان با گزینه های رنگ و نماد

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

برای اندروید، درخواست یک نماد و رنگ خاص را برای نمایش در دستگاه های اندرویدی تنظیم می کند. همانطور که در مرجع AndroidNotification اشاره شد، رنگ با فرمت #rrggbb مشخص شده است و تصویر باید یک منبع نماد قابل ترسیم محلی برای برنامه Android باشد.

در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده از دو دستگاه، با نمایش نماد و رنگ سفارشی

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);
  });
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();
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",
}
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",
};
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"
       }
     }
   }
 }

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

مثال: پیام اعلان با یک تصویر سفارشی

مثال زیر درخواست ارسال یک عنوان اعلان مشترک را به همه پلتفرم ها ارسال می کند، اما یک تصویر نیز ارسال می کند. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده یک تصویر در یک اعلان نمایشگر

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

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

مثال: پیام اعلان با یک اقدام کلیک مرتبط

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

طراحی ساده یک ضربه کاربر برای باز کردن یک صفحه وب

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

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

مثال: پیام اعلان با گزینه های محلی سازی

مثال زیر درخواست ارسال گزینه‌های محلی‌سازی را برای مشتری ارسال می‌کند تا پیام‌های محلی را نمایش دهد. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده از دو دستگاه که متن را به زبان انگلیسی و اسپانیایی نشان می دهد

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);
  });
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"],
                    },
                 },
               },
             },
  },
}'

برای جزئیات کامل کلیدهای موجود در بلوک‌های مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.

کدهای خطا REST برای HTTP v1 API

پاسخ های خطای HTTP برای HTTP v1 API حاوی کد خطا، پیام خطا و وضعیت خطا است. آنها همچنین ممکن است حاوی یک آرایه details با جزئیات بیشتر در مورد خطا باشند.

در اینجا دو نمونه پاسخ خطا آورده شده است:

مثال 1: پاسخ خطا از درخواست HTTP v1 API با مقدار نامعتبر در پیام داده

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

مثال 2: پاسخ خطا از یک درخواست API HTTP v1 با یک نشانه ثبت نام معتبر

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

توجه داشته باشید که هر دو پیام کد و وضعیت یکسانی دارند، اما آرایه جزئیات حاوی مقادیر در انواع مختلف است. نمونه اول دارای نوع type.googleapis.com/google.rpc.BadRequest است که نشان دهنده خطا در مقادیر درخواست است. مثال دوم با نوع type.googleapis.com/google.firebase.fcm.v1.FcmError دارای یک خطای خاص FCM است. برای بسیاری از خطاها، آرایه جزئیات حاوی اطلاعاتی است که برای اشکال زدایی و یافتن وضوح نیاز دارید.

جدول زیر کدهای خطای FCM v1 REST API و توضیحات آنها را فهرست می کند.

کد خطا مراحل شرح و تفکیک
UNSPECIFIED_ERROR اطلاعات بیشتری در مورد این خطا در دسترس نیست. هیچ کدام.
INVALID_ARGUMENT (کد خطای HTTP = 400) پارامترهای درخواست نامعتبر بودند. پسوندی از نوع google.rpc.BadRequest برگردانده می شود تا مشخص شود کدام فیلد نامعتبر است. دلایل بالقوه شامل ثبت نامعتبر، نام بسته نامعتبر، پیام خیلی بزرگ، کلید داده نامعتبر، TTL نامعتبر، یا سایر پارامترهای نامعتبر است.
ثبت نام نامعتبر : فرمت رمز ثبت نامی که به سرور ارسال می کنید را بررسی کنید. مطمئن شوید که با نشانه ثبتی که برنامه مشتری از ثبت نام در FCM دریافت می کند مطابقت دارد. نشانه را کوتاه نکنید یا کاراکترهای اضافی اضافه نکنید.
نام بسته نامعتبر : مطمئن شوید که پیام به نشانه ثبتی که نام بسته آن با مقدار ارسال شده در درخواست مطابقت دارد، خطاب شده است.
پیام خیلی بزرگ : بررسی کنید که حجم کل داده‌های محموله موجود در یک پیام از محدودیت‌های FCM تجاوز نکند: 4096 بایت برای بیشتر پیام‌ها، یا 2048 بایت در مورد پیام‌ها به موضوعات. این شامل کلیدها و مقادیر می شود.
کلید داده های نامعتبر : بررسی کنید که داده های بارگذاری حاوی یک کلید (مانند ، یا GCM یا هر مقدار پیشوند شده توسط Google) نیست که توسط FCM در داخل استفاده می شود. توجه داشته باشید که برخی از کلمات (مانند Collapse_Key) نیز توسط FCM استفاده می شوند اما در بار بار مجاز هستند ، در این صورت مقدار بار بار توسط مقدار FCM نادیده گرفته می شود.
نامعتبر TTL : بررسی کنید که مقدار مورد استفاده در TTL یک عدد صحیح است که مدت زمان در ثانیه بین 0 تا 419،200 (4 هفته) را نشان می دهد.
پارامترهای نامعتبر : بررسی کنید که پارامترهای ارائه شده دارای نام و نوع مناسب هستند.
نمونه برنامه UNREGISTERED (کد خطای HTTP = 404) از FCM ثبت نشده است. این معمولاً بدان معنی است که نشانه مورد استفاده دیگر معتبر نیست و باید مورد استفاده جدید باشد. این خطا می تواند در اثر نشانه های ثبت نام از دست رفته یا نشانه های ثبت نشده ایجاد شود.
ثبت نام از دست رفته : اگر هدف پیام یک مقدار token است ، بررسی کنید که درخواست حاوی نشانه ثبت است.
ثبت نشده است : یک نشانه ثبت نام موجود ممکن است در تعدادی از سناریوها معتبر باشد ، از جمله:
- اگر برنامه مشتری با FCM ثبت نام کند.
- اگر برنامه مشتری به طور خودکار ثبت نشده باشد ، اگر کاربر برنامه را حذف کند ، می تواند اتفاق بیفتد. به عنوان مثال ، در iOS ، اگر سرویس بازخورد APNS نشانه APNS را نامعتبر کند.
- اگر نشانه ثبت نام منقضی شود (به عنوان مثال ، Google ممکن است تصمیم بگیرد که نشانه های ثبت نام را تازه کند ، یا APNS Token برای دستگاه های iOS منقضی شده است).
- در صورت بروزرسانی برنامه مشتری اما نسخه جدید برای دریافت پیام پیکربندی نشده است.
برای همه این موارد ، این نشانه ثبت نام را از سرور برنامه حذف کرده و استفاده از آن را برای ارسال پیام متوقف کنید.
SENDER_ID_MISMATCH (کد خطای HTTP = 403) شناسه فرستنده معتبر با شناسه فرستنده برای نشانه ثبت نام متفاوت است. نشانه ثبت نام به گروه خاصی از فرستنده ها گره خورده است. هنگامی که یک برنامه مشتری برای FCM ثبت نام می کند ، باید مشخص کند که چه ارسال کنندگان مجاز به ارسال پیام هستند. هنگام ارسال پیام به برنامه مشتری باید از یکی از آن شناسه های فرستنده استفاده کنید. اگر به یک فرستنده متفاوت تغییر دهید ، نشانه های ثبت نام موجود کار نمی کنند.
QUOTA_EXCEEDED (کد خطای HTTP = 429) برای هدف پیام بیش از حد بود. پسوند نوع google.rpc.QuotaFailure برای مشخص کردن اینکه از سهمیه فراتر رفته است ، بازگردانده می شود. این خطا می تواند ناشی از سهمیه نرخ پیام بیش از حد ، بیش از سهمیه نرخ پیام دستگاه یا بیش از سهمیه نرخ پیام موضوع باشد.
نرخ پیام بیش از : نرخ ارسال پیام ها خیلی زیاد است. شما باید نرخ کلی ارسال پیام را کاهش دهید. برای امتحان مجدد پیام های رد شده از پشتیبان نمایی با حداقل تأخیر اولیه 1 دقیقه استفاده کنید.
نرخ پیام دستگاه بیش از : میزان پیام ها به یک دستگاه خاص بسیار زیاد است. محدودیت نرخ پیام را به یک دستگاه واحد مشاهده کنید . تعداد پیام های ارسال شده به این دستگاه را کاهش داده و برای ارسال مجدد از Backoff Exponential استفاده کنید.
نرخ پیام موضوع بیش از : نرخ پیام برای مشترکین به یک موضوع خاص بسیار زیاد است. تعداد پیام های ارسال شده برای این موضوع را کاهش داده و از برگه نمایی با حداقل تأخیر اولیه 1 دقیقه برای تلاش مجدد استفاده کنید.
UNAVAILABLE (کد خطای HTTP = 503) سرور بیش از حد بارگیری می شود. سرور نمی تواند درخواست را به موقع پردازش کند. همان درخواست را دوباره امتحان کنید ، اما باید:
- اگر در پاسخ از سرور اتصال FCM گنجانده شده است ، از عنوان مجدد پس از آن احترام بگذارید.
- اجرای پشتیبان نمایی را در مکانیسم آزمایش مجدد خود اجرا کنید. (به عنوان مثال اگر یک ثانیه قبل از تلاش اول صبر کردید ، حداقل دو ثانیه قبل از مرحله بعدی صبر کنید ، سپس 4 ثانیه و غیره). اگر چندین پیام ارسال می کنید ، استفاده از لرزش را در نظر بگیرید. برای اطلاعات بیشتر ، به تدابیر مجدد مراجعه کنید ، یا داشبورد وضعیت FCM را بررسی کنید تا در صورت بروز هرگونه اختلال در سرویس در حال انجام بر FCM ، مشخص شود. فرستنده هایی که باعث ایجاد مشکل می شوند در معرض خطر قرار می گیرند.
INTERNAL (کد خطای HTTP = 500) یک خطای داخلی ناشناخته رخ داده است. سرور هنگام تلاش برای پردازش درخواست با خطایی روبرو شد. شما می توانید همان درخواست را به دنبال پیشنهادات در انجام تدابیر مجدد یا بررسی داشبورد وضعیت FCM دوباره امتحان کنید. برای شناسایی اینکه آیا هرگونه اختلال در سرویس در حال انجام بر FCM وجود دارد یا خیر. اگر خطا ادامه دارد ، لطفاً با پشتیبانی Firebase تماس بگیرید.
THIRD_PARTY_AUTH_ERROR (کد خطای http = 401) گواهی APNS یا کلید AUTH PUSH AUT نامعتبر یا مفقود بود. پیامی که به یک دستگاه iOS یا ثبت نام فشار وب هدف داده می شود قابل ارسال نیست. اعتبار اعتبارنامه های توسعه و تولید خود را بررسی کنید.

کدهای خطای سرپرست

در جدول زیر کدهای خطای API FCM Admin Firebase Admin و توضیحات آنها ، از جمله مراحل وضوح توصیه شده ذکر شده است.

کد خطا توضیحات و مراحل وضوح
messaging/invalid-argument یک استدلال نامعتبر به یک روش FCM ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-recipient گیرنده پیام در نظر گرفته شده نامعتبر است. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-payload یک شیء بارگذاری پیام نامعتبر ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-data-payload-key بارگیری پیام داده شامل یک کلید نامعتبر است. برای کلیدهای محدود به مستندات مرجع DataMessagePayload مراجعه کنید.
messaging/payload-size-limit-exceeded بار پیام ارائه شده بیش از حد اندازه FCM است. حد برای اکثر پیام ها 4096 بایت است. برای پیام های ارسال شده به موضوعات ، حد 2048 بایت است. اندازه بار بارگذاری شامل کلیدها و مقادیر است.
messaging/invalid-options یک شیء گزینه های پیام نامعتبر ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-registration-token نشانه ثبت نام نامعتبر ارائه شده است. اطمینان حاصل کنید که با نشانه ثبت نام برنامه مشتری از ثبت نام در FCM مطابقت دارد. شخصیت های اضافی را کوتاه نکنید یا به آن اضافه کنید.
messaging/registration-token-not-registered نشانه ثبت ارائه شده ثبت نشده است. یک نشانه ثبت نام قبلاً معتبر می تواند به دلایل مختلفی از جمله:
  • برنامه مشتری خود را از FCM ثبت نکرد.
  • برنامه مشتری به طور خودکار ثبت نشده بود. اگر کاربر برنامه را حذف کند یا در سیستم عامل های اپل ، اگر سرویس بازخورد APNS نشانه APNS را نامعتبر کند ، می تواند این اتفاق بیفتد.
  • نشانه ثبت نام منقضی شد. به عنوان مثال ، Google ممکن است تصمیم بگیرد که نشانه های ثبت نام را تازه کند یا نشانه APNS ممکن است برای دستگاه های اپل منقضی شده باشد.
  • برنامه مشتری به روز شد ، اما نسخه جدید برای دریافت پیام پیکربندی نشده است.
برای همه این موارد ، این نشانه ثبت نام را حذف کرده و استفاده از آن را برای ارسال پیام متوقف کنید.
messaging/invalid-package-name این پیام به یک نشانه ثبت نام خطاب شده است که نام بسته آن با گزینه ارائه شده restrictedPackageName مطابقت ندارد.
messaging/message-rate-exceeded میزان پیام ها به یک هدف خاص بسیار زیاد است. تعداد پیام های ارسال شده به این دستگاه یا موضوع را کاهش دهید و بلافاصله ارسال مجدد به این هدف را دوباره امتحان نکنید.
messaging/device-message-rate-exceeded میزان پیام ها به یک دستگاه خاص بسیار زیاد است. تعداد پیام های ارسال شده به این دستگاه را کاهش داده و بلافاصله ارسال مجدد به این دستگاه را دوباره امتحان نکنید.
messaging/topics-message-rate-exceeded میزان پیام برای مشترکین به یک موضوع خاص بسیار زیاد است. تعداد پیام های ارسال شده برای این موضوع را کاهش دهید و بلافاصله ارسال مجدد به این موضوع را دوباره امتحان نکنید.
messaging/too-many-topics یک نشانه ثبت نام در حداکثر تعداد موضوعات مشترک شده است و دیگر نمی تواند مشترک شود.
messaging/invalid-apns-credentials پیامی که برای یک دستگاه اپل هدف قرار گرفته است نمی تواند ارسال شود زیرا گواهی APNS SSL مورد نیاز بارگذاری نشده یا منقضی نشده است. اعتبار گواهینامه های توسعه و تولید خود را بررسی کنید.
messaging/mismatched-credential اعتبار مورد استفاده برای تأیید اعتبار این SDK مجوز ارسال پیام به دستگاه مربوط به نشانه ثبت نام ارائه شده ندارد. اطمینان حاصل کنید که اعتبار و ثبت نام هر دو متعلق به یک پروژه Firebase یکسان است. برای اسناد و مدارک در مورد چگونگی تأیید اعتبار SDK S Firebase Admin SDK S را به برنامه خود اضافه کنید .
messaging/authentication-error SDK نتوانست به سرورهای FCM تأیید شود. اطمینان حاصل کنید که Firebase Admin SDK با اعتبارنامه که دارای مجوزهای مناسب برای ارسال پیام های FCM است ، تأیید کرده اید. برای اسناد و مدارک در مورد چگونگی تأیید اعتبار SDK S Firebase Admin SDK S را به برنامه خود اضافه کنید .
messaging/server-unavailable سرور FCM نمی تواند درخواست را به موقع پردازش کند. شما باید همان درخواست را امتحان کنید ، اما باید:
  • اگر در پاسخ از سرور اتصال FCM گنجانده شده است ، از عنوان Retry-After استفاده کنید.
  • در مکانیسم آزمایش مجدد خود ، برگشتی نمایی را اجرا کنید. به عنوان مثال ، اگر یک ثانیه قبل از تلاش اول صبر کردید ، حداقل دو ثانیه قبل از مرحله بعدی صبر کنید ، سپس چهار ثانیه و غیره. اگر در حال ارسال پیام های متعدد هستید ، هرکدام را به طور مستقل با یک مقدار تصادفی اضافی به تأخیر بیندازید تا از صدور درخواست جدید برای همه پیام ها به طور همزمان خودداری کنید.
فرستنده هایی که باعث ایجاد مشکلاتی در لیست سیاه می شوند.
messaging/internal-error سرور FCM هنگام تلاش برای پردازش درخواست با خطایی روبرو شد. شما می توانید همان درخواست را به دنبال الزامات ذکر شده در ردیف messaging/server-unavailable در بالا ، دوباره امتحان کنید. اگر این خطا ادامه دارد ، لطفاً مشکل را به کانال پشتیبانی گزارش اشکال ما گزارش دهید.
messaging/unknown-error خطای سرور ناشناخته برگردانده شد. برای اطلاعات بیشتر به پاسخ سرور خام در پیام خطا مراجعه کنید. اگر این خطا را دریافت کردید ، لطفاً پیام خطای کامل را به کانال پشتیبانی گزارش اشکال ما گزارش دهید.
،

با استفاده از پروتکل های سرور Firebase Admin SDK یا FCM ، می توانید درخواست های پیام بسازید و آنها را به این نوع اهداف ارسال کنید:

  • نام موضوع
  • وضعیت
  • نشانه ثبت نام دستگاه
  • نام گروه دستگاه (فقط پروتکل)

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

نمونه های این صفحه نحوه ارسال پیام های اعلان را با استفاده از Firebase Admin SDK (که دارای پشتیبانی از Node ، Java ، Python ، C# و GO است) و پروتکل V1 HTTP نشان می دهد.

ارسال پیام به دستگاه های خاص

برای ارسال به یک دستگاه واحد و خاص ، همانطور که نشان داده شده است ، نشانه ثبت نام دستگاه را منتقل کنید. برای کسب اطلاعات بیشتر در مورد نشانه های ثبت نام ، به اطلاعات تنظیم مشتری برای سیستم عامل خود مراجعه کنید.

// 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);
  });
// 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);
# 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)
// 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);
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 رشته شناسه را در Format projects/{project_id}/messages/{message_id} reship می کند. پاسخ پروتکل HTTP یک کلید JSON واحد است:

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

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

API های Admin FCM به شما امکان می دهد تا پیامی را به لیستی از نشانه های ثبت نام دستگاه تبدیل کنید. در هر دعوت می توانید حداکثر 500 نشانه ثبت نام دستگاه را مشخص کنید.

// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# Create a list containing up to 500 registration tokens.
# 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_multicast(message)
# 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 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.SendMulticast(context.Background(), message)
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)
// Create a list containing up to 500 registration tokens.
// 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);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

مقدار بازگشت لیستی از نشانه هایی است که مطابق با ترتیب نشانه های ورودی است. این زمانی مفید است که می خواهید بررسی کنید که کدام توکن منجر به خطا شده است.

// 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().sendMulticast(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);
    }
  });
// 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().sendMulticast(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);
}
# 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_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.SendMulticast(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)
}
// 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}");
}

ارسال پیام به موضوعات

پس از ایجاد یک موضوع ، یا با عضویت در مورد برنامه های مشتری در موضوع در سمت مشتری یا از طریق API سرور ، می توانید پیام هایی را به موضوع ارسال کنید. اگر این اولین بار است که درخواست ارسال درخواست FCM را ارسال می کنید ، برای پیش زمینه و اطلاعات مهم تنظیم ، به راهنمای محیط سرور و FCM خود مراجعه کنید.

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

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

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

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

// 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 استفاده کنید. اگر در حال حاضر با استفاده از API های میراث مستهجن برای HTTP یا XMPP یا هر یک از نسخه های قدیمی تر Firebase Admin SDK برای Node.js بر اساس پروتکل های میراث ، به گروه های دستگاهی ارسال می کنید ، ما اکیداً توصیه می کنیم که در اولین فرصت به HTTP V1 API مهاجرت کنید . API های ارسال میراث در ژوئن سال 2024 غیرفعال و حذف می شوند.

ارسال پیام به یک گروه دستگاه بسیار شبیه به ارسال پیام به یک دستگاه جداگانه است ، با استفاده از همان روش برای اجازه ارسال درخواست ارسال . قسمت token را روی کلید اعلان گروه تنظیم کنید:

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

یک دسته از پیام ها ارسال کنید

مدیر SDK ها از ارسال پیام در دسته ها پشتیبانی می کنند. شما می توانید حداکثر 500 پیام را به یک دسته واحد گروه بندی کنید و همه آنها را در یک تماس API واحد ارسال کنید ، با بهبود عملکرد قابل توجهی نسبت به ارسال درخواست های HTTP جداگانه برای هر پیام.

این ویژگی می تواند برای ایجاد مجموعه ای از پیام های سفارشی و ارسال آنها به گیرندگان مختلف از جمله موضوعات یا نشانه های ثبت نام دستگاه استفاده شود. از این ویژگی استفاده کنید که به عنوان مثال ، شما باید همزمان پیام ها را برای مخاطبان مختلف با جزئیات کمی متفاوت در بدن پیام ارسال کنید.

// 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().sendAll(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// 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().sendAll(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# 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_all(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.SendAll(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)
// 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");

ارسال پیام های با قابلیت بوت مستقیم (فقط Android)

می توانید با استفاده از API های HTTP V1 یا Legacy HTTP ، به دستگاه ها در حالت بوت مستقیم ارسال کنید. قبل از ارسال به دستگاه ها در حالت بوت مستقیم ، حتماً مراحل لازم را برای فعال کردن دستگاه های مشتری برای دریافت پیام های FCM در حالت بوت مستقیم انجام داده اید.

با استفاده از API FCM V1 HTTP ارسال کنید

درخواست پیام باید شامل کلید "direct_boot_ok" : true در گزینه های AndroidConfig بدنه درخواست صحیح است. به عنوان مثال:

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 HTTP هر دو به درخواست پیام شما اجازه می دهند تا تمام قسمت های موجود در شیء message را تنظیم کنند. این شامل:

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

بلوک های خاص پلتفرم به شما انعطاف پذیری می دهد تا پیام ها را برای سیستم عامل های مختلف شخصی سازی کنید تا اطمینان حاصل شود که در هنگام دریافت به درستی از آنها برخورد می شوند. BACEND FCM تمام پارامترهای مشخص شده را در نظر می گیرد و پیام را برای هر سیستم عامل سفارشی می کند.

چه زمانی از زمینه های مشترک استفاده کنید

در صورتی که از زمینه های مشترک استفاده کنید:

  • هدف قرار دادن نمونه های برنامه در همه سیستم عامل ها - اپل ، اندروید و وب
  • ارسال پیام به موضوعات

همه نمونه های برنامه ، صرف نظر از پلتفرم ، می توانند زمینه های مشترک زیر را تفسیر کنند:

چه زمانی از زمینه های خاص پلت فرم استفاده کنید

وقتی می خواهید از فیلدهای خاص پلتفرم استفاده کنید:

  • ارسال قسمت ها فقط به سیستم عامل های خاص
  • علاوه بر زمینه های مشترک ، زمینه های خاص سیستم عامل را ارسال کنید

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

هنگامی که در حال ارسال پیام با گزینه های تحویل خاص هستید ، برای تنظیم آنها از قسمت های خاص پلتفرم استفاده کنید. در صورت تمایل می توانید مقادیر مختلفی را برای هر پلتفرم مشخص کنید. با این حال ، حتی وقتی می خواهید اساساً همان مقدار را در سیستم عامل ها تنظیم کنید ، باید از فیلدهای خاص پلتفرم استفاده کنید. این امر به این دلیل است که هر پلتفرم ممکن است مقدار کمی متفاوت را تفسیر کند-برای مثال ، زمان به زندگی در اندروید به عنوان زمان انقضا در ثانیه تنظیم می شود ، در حالی که در اپل به عنوان تاریخ انقضا تعیین شده است.

مثال: پیام اعلان با گزینه های رنگ و نماد

این مثال درخواست ارسال یک عنوان و محتوای مشترک را به همه سیستم عامل ها ارسال می کند ، اما همچنین برخی از موارد اضافی پلتفرم را به دستگاه های Android ارسال می کند.

برای Android ، این درخواست یک نماد و رنگ ویژه را برای نمایش در دستگاه های Android تنظیم می کند. همانطور که در مرجع AndroidNotification ذکر شد ، رنگ در قالب #RRGGBB مشخص شده است ، و تصویر باید یک منبع قابل ترسیم باشد که به برنامه Android محلی باشد.

در اینجا تقریب اثر بصری بر روی دستگاه کاربر وجود دارد:

طراحی ساده دو دستگاه ، با یک نماد و رنگ سفارشی

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);
  });
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();
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",
}
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",
};
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"
       }
     }
   }
 }

برای جزئیات کامل در کلیدهای موجود در بلوک های خاص پلت فرم در بدنه پیام ، به اسناد مرجع HTTP V1 مراجعه کنید.

مثال: پیام اعلان با یک تصویر سفارشی

مثال زیر درخواست ارسال یک عنوان اعلان مشترک را به همه سیستم عامل ها ارسال می کند ، اما همچنین تصویری را ارسال می کند. در اینجا تقریب اثر بصری بر روی دستگاه کاربر وجود دارد:

طراحی ساده یک تصویر در یک اعلان نمایشگر

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

برای جزئیات کامل در کلیدهای موجود در بلوک های خاص پلت فرم در بدنه پیام ، به اسناد مرجع HTTP V1 مراجعه کنید.

مثال: پیام اعلان با یک عمل کلیک همراه

مثال زیر درخواست ارسال یک عنوان اعلان مشترک را به همه سیستم عامل ها ارسال می کند ، اما همچنین اقدامی را برای برنامه در پاسخ به تعامل کاربر با اعلان انجام می دهد. در اینجا تقریب اثر بصری بر روی دستگاه کاربر وجود دارد:

نقاشی ساده از یک کاربر روی باز کردن یک صفحه وب ضربه بزنید

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

برای جزئیات کامل در کلیدهای موجود در بلوک های خاص پلت فرم در بدنه پیام ، به اسناد مرجع HTTP V1 مراجعه کنید.

مثال: پیام اعلان با گزینه های محلی سازی

مثال زیر درخواست ارسال گزینه های محلی سازی را برای مشتری برای نمایش پیام های بومی شده ارسال می کند. در اینجا تقریب اثر بصری بر روی دستگاه کاربر وجود دارد:

طراحی ساده دو دستگاه که متن را به زبان انگلیسی و اسپانیایی نشان می دهند

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);
  });
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"],
                    },
                 },
               },
             },
  },
}'

برای جزئیات کامل در کلیدهای موجود در بلوک های خاص پلت فرم در بدنه پیام ، به اسناد مرجع HTTP V1 مراجعه کنید.

کدهای خطای استراحت برای API HTTP V1

پاسخ خطای HTTP برای HTTP V1 API حاوی کد خطا ، پیام خطا و وضعیت خطا است. آنها همچنین ممکن است دارای یک آرایه details با جزئیات بیشتر در مورد خطا باشند.

در اینجا دو پاسخ خطای نمونه آورده شده است:

مثال 1: پاسخ خطا از درخواست API HTTP V1 با یک مقدار نامعتبر در یک پیام داده

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

مثال 2: پاسخ خطا از درخواست API HTTP V1 با یک نشانه ثبت نام نامعتبر

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

توجه داشته باشید که هر دو پیام دارای یک کد و وضعیت یکسان هستند ، اما آرایه جزئیات حاوی مقادیر در انواع مختلف است. مثال اول دارای type.googleapis.com/google.rpc.BadRequest است که خطایی را در مقادیر درخواست نشان می دهد. مثال دوم با type.googleapis.com/google.firebase.fcm.v1.FcmError یک خطای خاص FCM دارد. برای بسیاری از خطاها ، آرایه جزئیات حاوی اطلاعاتی است که برای اشکال زدایی و یافتن قطعنامه لازم دارید.

در جدول زیر کدهای خطای API FCM V1 REST و توضیحات آنها ذکر شده است.

کد خطا توضیحات و مراحل وضوح
UNSPECIFIED_ERROR هیچ اطلاعات بیشتری در مورد این خطا در دسترس نیست. هیچ کدام.
INVALID_ARGUMENT (کد خطای HTTP = 400) پارامترهای درخواست نامعتبر بودند. پسوند نوع google.rpc.BadRequest برای مشخص کردن اینکه کدام قسمت نامعتبر است ، بازگردانده می شود. علل بالقوه شامل ثبت نام نامعتبر ، نام بسته نامعتبر ، پیام خیلی بزرگ ، کلید داده نامعتبر ، TTL نامعتبر یا سایر پارامترهای نامعتبر است.
ثبت نام نامعتبر : قالب نشانه ثبت نام را که به سرور منتقل می کنید ، بررسی کنید. اطمینان حاصل کنید که با نشانه ثبت نام برنامه مشتری از ثبت نام در FCM مطابقت دارد. نشانه را کوتاه نکنید و شخصیت های اضافی اضافه کنید.
نام بسته نامعتبر : اطمینان حاصل کنید که پیام به یک نشانه ثبت نام که نام بسته آن با مقدار منتقل شده در درخواست مطابقت دارد ، ارسال شده است.
پیام خیلی بزرگ : بررسی کنید که اندازه کل داده های بار موجود در یک پیام از محدودیت های FCM تجاوز نمی کند: 4096 بایت برای بیشتر پیام ها ، یا 2048 بایت در مورد پیام به موضوعات. این شامل کلیدها و مقادیر است.
کلید داده های نامعتبر : بررسی کنید که داده های بارگذاری حاوی یک کلید (مانند ، یا GCM یا هر مقدار پیشوند شده توسط Google) نیست که توسط FCM در داخل استفاده می شود. توجه داشته باشید که برخی از کلمات (مانند Collapse_Key) نیز توسط FCM استفاده می شوند اما در بار بار مجاز هستند ، در این صورت مقدار بار بار توسط مقدار FCM نادیده گرفته می شود.
نامعتبر TTL : بررسی کنید که مقدار مورد استفاده در TTL یک عدد صحیح است که مدت زمان در ثانیه بین 0 تا 419،200 (4 هفته) را نشان می دهد.
پارامترهای نامعتبر : بررسی کنید که پارامترهای ارائه شده دارای نام و نوع مناسب هستند.
نمونه برنامه UNREGISTERED (کد خطای HTTP = 404) از FCM ثبت نشده است. این معمولاً بدان معنی است که نشانه مورد استفاده دیگر معتبر نیست و باید مورد استفاده جدید باشد. این خطا می تواند در اثر نشانه های ثبت نام از دست رفته یا نشانه های ثبت نشده ایجاد شود.
ثبت نام از دست رفته : اگر هدف پیام یک مقدار token است ، بررسی کنید که درخواست حاوی نشانه ثبت است.
ثبت نشده است : یک نشانه ثبت نام موجود ممکن است در تعدادی از سناریوها معتبر باشد ، از جمله:
- اگر برنامه مشتری با FCM ثبت نام کند.
- اگر برنامه مشتری به طور خودکار ثبت نشده باشد ، اگر کاربر برنامه را حذف کند ، می تواند اتفاق بیفتد. به عنوان مثال ، در iOS ، اگر سرویس بازخورد APNS نشانه APNS را نامعتبر کند.
- اگر نشانه ثبت نام منقضی شود (به عنوان مثال ، Google ممکن است تصمیم بگیرد که نشانه های ثبت نام را تازه کند ، یا APNS Token برای دستگاه های iOS منقضی شده است).
- در صورت بروزرسانی برنامه مشتری اما نسخه جدید برای دریافت پیام پیکربندی نشده است.
برای همه این موارد ، این نشانه ثبت نام را از سرور برنامه حذف کرده و استفاده از آن را برای ارسال پیام متوقف کنید.
SENDER_ID_MISMATCH (کد خطای HTTP = 403) شناسه فرستنده معتبر با شناسه فرستنده برای نشانه ثبت نام متفاوت است. نشانه ثبت نام به گروه خاصی از فرستنده ها گره خورده است. هنگامی که یک برنامه مشتری برای FCM ثبت نام می کند ، باید مشخص کند که چه ارسال کنندگان مجاز به ارسال پیام هستند. هنگام ارسال پیام به برنامه مشتری باید از یکی از آن شناسه های فرستنده استفاده کنید. اگر به یک فرستنده متفاوت تغییر دهید ، نشانه های ثبت نام موجود کار نمی کنند.
QUOTA_EXCEEDED (کد خطای HTTP = 429) برای هدف پیام بیش از حد بود. پسوند نوع google.rpc.QuotaFailure برای مشخص کردن اینکه از سهمیه فراتر رفته است ، بازگردانده می شود. این خطا می تواند ناشی از سهمیه نرخ پیام بیش از حد ، بیش از سهمیه نرخ پیام دستگاه یا بیش از سهمیه نرخ پیام موضوع باشد.
نرخ پیام بیش از : نرخ ارسال پیام ها خیلی زیاد است. شما باید نرخ کلی ارسال پیام را کاهش دهید. برای امتحان مجدد پیام های رد شده از پشتیبان نمایی با حداقل تأخیر اولیه 1 دقیقه استفاده کنید.
نرخ پیام دستگاه بیش از : میزان پیام ها به یک دستگاه خاص بسیار زیاد است. محدودیت نرخ پیام را به یک دستگاه واحد مشاهده کنید . تعداد پیام های ارسال شده به این دستگاه را کاهش داده و برای ارسال مجدد از Backoff Exponential استفاده کنید.
نرخ پیام موضوع بیش از : نرخ پیام برای مشترکین به یک موضوع خاص بسیار زیاد است. تعداد پیام های ارسال شده برای این موضوع را کاهش داده و از برگه نمایی با حداقل تأخیر اولیه 1 دقیقه برای تلاش مجدد استفاده کنید.
UNAVAILABLE (کد خطای HTTP = 503) سرور بیش از حد بارگیری می شود. سرور نمی تواند درخواست را به موقع پردازش کند. همان درخواست را دوباره امتحان کنید ، اما باید:
- اگر در پاسخ از سرور اتصال FCM گنجانده شده است ، از عنوان مجدد پس از آن احترام بگذارید.
- اجرای پشتیبان نمایی را در مکانیسم آزمایش مجدد خود اجرا کنید. (به عنوان مثال اگر یک ثانیه قبل از تلاش اول صبر کردید ، حداقل دو ثانیه قبل از مرحله بعدی صبر کنید ، سپس 4 ثانیه و غیره). اگر چندین پیام ارسال می کنید ، استفاده از لرزش را در نظر بگیرید. برای اطلاعات بیشتر ، به تدابیر مجدد مراجعه کنید ، یا داشبورد وضعیت FCM را بررسی کنید تا در صورت بروز هرگونه اختلال در سرویس در حال انجام بر FCM ، مشخص شود. فرستنده هایی که باعث ایجاد مشکل می شوند در معرض خطر قرار می گیرند.
INTERNAL (کد خطای HTTP = 500) یک خطای داخلی ناشناخته رخ داده است. سرور هنگام تلاش برای پردازش درخواست با خطایی روبرو شد. شما می توانید همان درخواست را به دنبال پیشنهادات در انجام تدابیر مجدد یا بررسی داشبورد وضعیت FCM دوباره امتحان کنید. برای شناسایی اینکه آیا هرگونه اختلال در سرویس در حال انجام بر FCM وجود دارد یا خیر. اگر خطا ادامه دارد ، لطفاً با پشتیبانی Firebase تماس بگیرید.
THIRD_PARTY_AUTH_ERROR (کد خطای http = 401) گواهی APNS یا کلید AUTH PUSH AUT نامعتبر یا مفقود بود. پیامی که به یک دستگاه iOS یا ثبت نام فشار وب هدف داده می شود قابل ارسال نیست. اعتبار اعتبارنامه های توسعه و تولید خود را بررسی کنید.

کدهای خطای سرپرست

در جدول زیر کدهای خطای API FCM Admin Firebase Admin و توضیحات آنها ، از جمله مراحل وضوح توصیه شده ذکر شده است.

کد خطا توضیحات و مراحل وضوح
messaging/invalid-argument یک استدلال نامعتبر به یک روش FCM ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-recipient گیرنده پیام در نظر گرفته شده نامعتبر است. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-payload یک شیء بارگذاری پیام نامعتبر ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-data-payload-key بارگیری پیام داده شامل یک کلید نامعتبر است. برای کلیدهای محدود به مستندات مرجع DataMessagePayload مراجعه کنید.
messaging/payload-size-limit-exceeded بار پیام ارائه شده بیش از حد اندازه FCM است. حد برای اکثر پیام ها 4096 بایت است. برای پیام های ارسال شده به موضوعات ، حد 2048 بایت است. اندازه بار بارگذاری شامل کلیدها و مقادیر است.
messaging/invalid-options یک شیء گزینه های پیام نامعتبر ارائه شد. پیام خطا باید حاوی اطلاعات اضافی باشد.
messaging/invalid-registration-token نشانه ثبت نام نامعتبر ارائه شده است. اطمینان حاصل کنید که با نشانه ثبت نام برنامه مشتری از ثبت نام در FCM مطابقت دارد. شخصیت های اضافی را کوتاه نکنید یا به آن اضافه کنید.
messaging/registration-token-not-registered نشانه ثبت ارائه شده ثبت نشده است. یک نشانه ثبت نام قبلاً معتبر می تواند به دلایل مختلفی از جمله:
  • برنامه مشتری خود را از FCM ثبت نکرد.
  • برنامه مشتری به طور خودکار ثبت نشده بود. اگر کاربر برنامه را حذف کند یا در سیستم عامل های اپل ، اگر سرویس بازخورد APNS نشانه APNS را نامعتبر کند ، می تواند این اتفاق بیفتد.
  • نشانه ثبت نام منقضی شد. به عنوان مثال ، Google ممکن است تصمیم بگیرد که نشانه های ثبت نام را تازه کند یا نشانه APNS ممکن است برای دستگاه های اپل منقضی شده باشد.
  • برنامه مشتری به روز شد ، اما نسخه جدید برای دریافت پیام پیکربندی نشده است.
برای همه این موارد ، این نشانه ثبت نام را حذف کرده و استفاده از آن را برای ارسال پیام متوقف کنید.
messaging/invalid-package-name این پیام به یک نشانه ثبت نام خطاب شده است که نام بسته آن با گزینه ارائه شده restrictedPackageName مطابقت ندارد.
messaging/message-rate-exceeded میزان پیام ها به یک هدف خاص بسیار زیاد است. تعداد پیام های ارسال شده به این دستگاه یا موضوع را کاهش دهید و بلافاصله ارسال مجدد به این هدف را دوباره امتحان نکنید.
messaging/device-message-rate-exceeded میزان پیام ها به یک دستگاه خاص بسیار زیاد است. تعداد پیام های ارسال شده به این دستگاه را کاهش داده و بلافاصله ارسال مجدد به این دستگاه را دوباره امتحان نکنید.
messaging/topics-message-rate-exceeded میزان پیام برای مشترکین به یک موضوع خاص بسیار زیاد است. تعداد پیام های ارسال شده برای این موضوع را کاهش دهید و بلافاصله ارسال مجدد به این موضوع را دوباره امتحان نکنید.
messaging/too-many-topics یک نشانه ثبت نام در حداکثر تعداد موضوعات مشترک شده است و دیگر نمی تواند مشترک شود.
messaging/invalid-apns-credentials پیامی که برای یک دستگاه اپل هدف قرار گرفته است نمی تواند ارسال شود زیرا گواهی APNS SSL مورد نیاز بارگذاری نشده یا منقضی نشده است. اعتبار گواهینامه های توسعه و تولید خود را بررسی کنید.
messaging/mismatched-credential اعتبار مورد استفاده برای تأیید اعتبار این SDK مجوز ارسال پیام به دستگاه مربوط به نشانه ثبت نام ارائه شده ندارد. اطمینان حاصل کنید که اعتبار و ثبت نام هر دو متعلق به یک پروژه Firebase یکسان است. برای اسناد و مدارک در مورد چگونگی تأیید اعتبار SDK S Firebase Admin SDK S را به برنامه خود اضافه کنید .
messaging/authentication-error SDK نتوانست به سرورهای FCM تأیید شود. اطمینان حاصل کنید که Firebase Admin SDK با اعتبارنامه که دارای مجوزهای مناسب برای ارسال پیام های FCM است ، تأیید کرده اید. برای اسناد و مدارک در مورد چگونگی تأیید اعتبار SDK S Firebase Admin SDK S را به برنامه خود اضافه کنید .
messaging/server-unavailable سرور FCM نمی تواند درخواست را به موقع پردازش کند. شما باید همان درخواست را امتحان کنید ، اما باید:
  • اگر در پاسخ از سرور اتصال FCM گنجانده شده است ، از عنوان Retry-After استفاده کنید.
  • در مکانیسم آزمایش مجدد خود ، برگشتی نمایی را اجرا کنید. به عنوان مثال ، اگر یک ثانیه قبل از تلاش اول صبر کردید ، حداقل دو ثانیه قبل از مرحله بعدی صبر کنید ، سپس چهار ثانیه و غیره. اگر در حال ارسال پیام های متعدد هستید ، هرکدام را به طور مستقل با یک مقدار تصادفی اضافی به تأخیر بیندازید تا از صدور درخواست جدید برای همه پیام ها به طور همزمان خودداری کنید.
فرستنده هایی که باعث ایجاد مشکلاتی در لیست سیاه می شوند.
messaging/internal-error سرور FCM هنگام تلاش برای پردازش درخواست با خطایی روبرو شد. شما می توانید همان درخواست را به دنبال الزامات ذکر شده در ردیف messaging/server-unavailable در بالا ، دوباره امتحان کنید. اگر این خطا ادامه دارد ، لطفاً مشکل را به کانال پشتیبانی گزارش اشکال ما گزارش دهید.
messaging/unknown-error خطای سرور ناشناخته برگردانده شد. برای اطلاعات بیشتر به پاسخ سرور خام در پیام خطا مراجعه کنید. اگر این خطا را دریافت کردید ، لطفاً پیام خطای کامل را به کانال پشتیبانی گزارش اشکال ما گزارش دهید.
،

با استفاده از پروتکل های سرور Firebase Admin SDK یا FCM ، می توانید درخواست های پیام بسازید و آنها را به این نوع اهداف ارسال کنید:

  • نام موضوع
  • وضعیت
  • نشانه ثبت نام دستگاه
  • نام گروه دستگاه (فقط پروتکل)

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

نمونه های این صفحه نحوه ارسال پیام های اعلان را با استفاده از Firebase Admin SDK (که دارای پشتیبانی از Node ، Java ، Python ، C# و GO است) و پروتکل V1 HTTP نشان می دهد.

ارسال پیام به دستگاه های خاص

برای ارسال به یک دستگاه واحد و خاص ، همانطور که نشان داده شده است ، نشانه ثبت نام دستگاه را منتقل کنید. برای کسب اطلاعات بیشتر در مورد نشانه های ثبت نام ، به اطلاعات تنظیم مشتری برای سیستم عامل خود مراجعه کنید.

// 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);
  });
// 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);
# 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)
// 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);
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 رشته شناسه را در Format projects/{project_id}/messages/{message_id} reship می کند. پاسخ پروتکل HTTP یک کلید JSON واحد است:

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

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

API های Admin FCM به شما امکان می دهد تا پیامی را به لیستی از نشانه های ثبت نام دستگاه تبدیل کنید. در هر دعوت می توانید حداکثر 500 نشانه ثبت نام دستگاه را مشخص کنید.

// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# Create a list containing up to 500 registration tokens.
# 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_multicast(message)
# 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 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.SendMulticast(context.Background(), message)
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)
// Create a list containing up to 500 registration tokens.
// 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);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

مقدار بازگشت لیستی از نشانه هایی است که مطابق با ترتیب نشانه های ورودی است. این زمانی مفید است که می خواهید بررسی کنید که کدام توکن منجر به خطا شده است.

// 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().sendMulticast(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);
    }
  });
// 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().sendMulticast(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);
}
# 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_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.SendMulticast(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)
}
// 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}");
}

ارسال پیام به موضوعات

پس از ایجاد یک موضوع ، یا با عضویت در مورد برنامه های مشتری در موضوع در سمت مشتری یا از طریق API سرور ، می توانید پیام هایی را به موضوع ارسال کنید. If this is your first time building send requests for FCM , see the guide to your server environment and FCM for important background and setup information.

In your sending logic on the backend, specify the desired topic name as shown:

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

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

To send a message to a combination of topics, specify a condition , which is a boolean expression that specifies the target topics. برای مثال، شرایط زیر پیام‌هایی را به دستگاه‌هایی ارسال می‌کند که مشترک TopicA و TopicB یا TopicC هستند:

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

FCM ابتدا هر شرایط داخل پرانتز را ارزیابی می کند و سپس عبارت را از چپ به راست ارزیابی می کند. در عبارت بالا، کاربری که در یک موضوع مشترک است، پیامی را دریافت نمی کند. به همین ترتیب، کاربری که در TopicA مشترک نمی شود، پیام را دریافت نمی کند. این ترکیب ها آن را دریافت می کنند:

  • TopicA و TopicB
  • TopicA و TopicC

You can include up to five topics in your conditional expression.

To send to a condition:

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

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

Send messages to device groups

To send messages to device groups, use the HTTP v1 API. If you are currently sending to device groups using the deprecated legacy send APIs for HTTP or XMPP, or any of the older versions of the Firebase Admin SDK for Node.js based on the legacy protocols, we strongly recommend that you migrate to the HTTP v1 API at the earliest opportunity. The legacy send APIs will be disabled and removed in June 2024.

Sending messages to a device group is very similar to sending messages to an individual device, using the same method to authorize send requests . Set the token field to the group notification key:

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

Send a batch of messages

The Admin SDKs support sending messages in batches. You can group up to 500 messages into a single batch and send them all in a single API call, with significant performance improvement over sending separate HTTP requests for each message.

This feature can be used to build a customized set of messages and send them to different recipients, including topics or specific device registration tokens. Use this feature when, for example, you need to simultaneously send messages to different audiences with slightly different details in the message body.

// 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().sendAll(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });
// 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().sendAll(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
# 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_all(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.SendAll(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)
// 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");

Send direct boot-enabled messages (Android only)

You can send messages to devices in direct boot mode using the HTTP v1 or legacy HTTP APIs. Before sending to devices in direct boot mode, make sure you have completed the steps to enable client devices to receive FCM messages in direct boot mode .

Send using the FCM v1 HTTP API

The message request must include the key "direct_boot_ok" : true in the AndroidConfig options of the request body. به عنوان مثال:

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

Customize messages across platforms

The Firebase Admin SDK and the FCM v1 HTTP protocol both allow your message requests to set all fields available in the message object. این شامل:

  • a common set of fields to be interpreted by all app instances that receive the message.
  • platform-specific sets of fields, such as AndroidConfig and WebpushConfig , interpreted only by app instances running on the specified platform.

Platform-specific blocks give you flexibility to customize messages for different platforms to ensure that they are handled correctly when received. The FCM backend will take all specified parameters into account and customize the message for each platform.

When to use common fields

Use common fields when you're:

  • Targeting app instances on all platforms — Apple, Android, and web
  • Sending messages to topics

All app instances, regardless of platform, can interpret the following common fields:

When to use platform-specific fields

Use platform-specific fields when you want to:

  • Send fields only to particular platforms
  • Send platform-specific fields in addition to the common fields

Whenever you want to send values only to particular platforms, don't use common fields; use platform-specific fields. For example, to send a notification only to Apple platforms and web but not to Android, you must use two separate sets of fields, one for Apple and one for web.

When you are sending messages with specific delivery options , use platform-specific fields to set them. You can specify different values per platform if you want. However, even when you want to set essentially the same value across platforms, you must use platform-specific fields. This is because each platform may interpret the value slightly differently—for example, time-to-live is set on Android as an expiration time in seconds, while on Apple it is set as an expiration date .

Example: notification message with color and icon options

This example send request sends a common notification title and content to all platforms, but it also sends some platform-specific overrides to Android devices.

For Android, the request sets a special icon and color to display on Android devices. As noted in the reference for AndroidNotification , the color is specified in #rrggbb format, and the image must be a drawable icon resource local to the Android app.

Here's an approximation of the visual effect on a user's device:

Simple drawing of two devices, with one displaying a custom icon and color

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);
  });
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();
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",
}
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",
};
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"
       }
     }
   }
 }

See the HTTP v1 reference documentation for complete detail on the keys available in platform-specific blocks in the message body.

Example: notification message with a custom image

The following example send request sends a common notification title to all platforms, but it also sends an image. Here's an approximation of the visual effect on a user's device:

Simple drawing of an image in a display notification

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

See the HTTP v1 reference documentation for complete detail on the keys available in platform-specific blocks in the message body.

Example: notification message with an associated click action

The following example send request sends a common notification title to all platforms, but it also sends an action for the app to perform in response to user interacting with the notification. Here's an approximation of the visual effect on a user's device:

Simple drawing of a user tap opening a web page

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

See the HTTP v1 reference documentation for complete detail on the keys available in platform-specific blocks in the message body.

Example: notification message with localization options

The following example send request sends localization options for the client to display localized messages. Here's an approximation of the visual effect on a user's device:

Simple drawing of two devices displaying text in English and Spanish

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);
  });
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"],
                    },
                 },
               },
             },
  },
}'

See the HTTP v1 reference documentation for complete detail on the keys available in platform-specific blocks in the message body.

REST error codes for the HTTP v1 API

HTTP error responses for the HTTP v1 API contain an error code, an error message, and error status. They may also contain a details array with more details on the error.

Here are two sample error responses:

Example 1: Error response from an HTTP v1 API request with an invalid value in a data message

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

Example 2: Error response from an HTTP v1 API request with an invalid registration token

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

Note that both messages have the same code and status, but the details array contains values in different types. The first example has type type.googleapis.com/google.rpc.BadRequest indicating an error in request values. The second example with type type.googleapis.com/google.firebase.fcm.v1.FcmError has an FCM specific error. For many errors, the details array contains the information you'll need to debug and find a resolution.

The following table lists the FCM v1 REST API error codes and their descriptions.

کد خطا Description and Resolution Steps
UNSPECIFIED_ERROR No more information is available about this error. هیچ کدام.
INVALID_ARGUMENT (HTTP error code = 400) Request parameters were invalid. An extension of type google.rpc.BadRequest is returned to specify which field was invalid. Potential causes include invalid registration, invalid package name, message too big, invalid data key, invalid TTL, or other invalid parameters.
Invalid registration : Check the format of the registration token you pass to the server. Make sure it matches the registration token the client app receives from registering with FCM. Do not truncate the token or add additional characters.
Invalid package name : Make sure the message was addressed to a registration token whose package name matches the value passed in the request.
Message too big : Check that the total size of the payload data included in a message does not exceed FCM limits: 4096 bytes for most messages, or 2048 bytes in the case of messages to topics. This includes both the keys and the values.
Invalid data key : Check that the payload data does not contain a key (such as from, or gcm, or any value prefixed by google) that is used internally by FCM. Note that some words (such as collapse_key) are also used by FCM but are allowed in the payload, in which case the payload value will be overridden by the FCM value.
Invalid TTL : Check that the value used in ttl is an integer representing a duration in seconds between 0 and 2,419,200 (4 weeks).
Invalid parameters : Check that the provided parameters have the right name and type.
UNREGISTERED (HTTP error code = 404) App instance was unregistered from FCM. This usually means that the token used is no longer valid and a new one must be used. This error can be caused by missing registration tokens, or unregistered tokens.
Missing Registration : If the message's target is a token value, check that the request contains a registration token.
Not registered : An existing registration token may cease to be valid in a number of scenarios, including:
- If the client app unregisters with FCM.
- If the client app is automatically unregistered, which can happen if the user uninstalls the application. For example, on iOS, if the APNs Feedback Service reported the APNs token as invalid.
- If the registration token expires (for example, Google might decide to refresh registration tokens, or the APNs token has expired for iOS devices).
- If the client app is updated but the new version is not configured to receive messages.
For all these cases, remove this registration token from the app server and stop using it to send messages.
SENDER_ID_MISMATCH (HTTP error code = 403) The authenticated sender ID is different from the sender ID for the registration token. A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work.
QUOTA_EXCEEDED (HTTP error code = 429) Sending limit exceeded for the message target. An extension of type google.rpc.QuotaFailure is returned to specify which quota was exceeded. This error can be caused by exceeded message rate quota, exceeded device message rate quota, or exceeded topic message rate quota.
Message rate exceeded : The sending rate of messages is too high. You must reduce the overall rate at which you send messages. Use exponential backoff with a minimum initial delay of 1 minute to retry rejected messages.
Device message rate exceeded : The rate of messages to a particular device is too high. See message rate limit to a single device . Reduce the number of messages sent to this device and use exponential backoff to retry sending.
Topic message rate exceeded : The rate of messages to subscribers to a particular topic is too high. Reduce the number of messages sent for this topic and use exponential backoff with a minimum initial delay of 1 minute to retry sending.
UNAVAILABLE (HTTP error code = 503) The server is overloaded. The server couldn't process the request in time. Retry the same request, but you must:
- Honor the Retry-After header if it is included in the response from the FCM Connection Server.
- Implement exponential backoff in your retry mechanism. (eg if you waited one second before the first retry, wait at least two seconds before the next one, then 4 seconds and so on). If you're sending multiple messages, consider applying jittering. For more information, see Handling retries , or check the FCM status dashboard to identify if there are any ongoing service disruptions affecting FCM. Senders that cause problems risk being denylisted.
INTERNAL (HTTP error code = 500) An unknown internal error occurred. The server encountered an error while trying to process the request. You could retry the same request following suggestions in Handling retries or checking the FCM status dashboard . to identify if there are any ongoing service disruptions affecting FCM. If the error persists, please contact Firebase support.
THIRD_PARTY_AUTH_ERROR (HTTP error code = 401) APNs certificate or web push auth key was invalid or missing. A message targeted to an iOS device or a web push registration could not be sent. Check the validity of your development and production credentials.

Admin error codes

The following table lists the Firebase Admin FCM API error codes and their descriptions, including recommended resolution steps.

کد خطا Description and Resolution Steps
messaging/invalid-argument An invalid argument was provided to an FCM method. The error message should contain additional information.
messaging/invalid-recipient The intended message recipient is invalid. The error message should contain additional information.
messaging/invalid-payload An invalid message payload object was provided. The error message should contain additional information.
messaging/invalid-data-payload-key The data message payload contains an invalid key. See the reference documentation for DataMessagePayload for restricted keys.
messaging/payload-size-limit-exceeded The provided message payload exceeds the FCM size limits. The limit is 4096 bytes for most messages. For messages sent to topics, the limit is 2048 bytes. The total payload size includes both keys and values.
messaging/invalid-options An invalid message options object was provided. The error message should contain additional information.
messaging/invalid-registration-token Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM . Do not truncate or add additional characters to it.
messaging/registration-token-not-registered The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons, including:
  • The client app unregistered itself from FCM .
  • The client app was automatically unregistered. This can happen if the user uninstalls the application or, on Apple platforms, if the APNs Feedback Service reported the APNs token as invalid.
  • The registration token expired. For example, Google might decide to refresh registration tokens or the APNs token may have expired for Apple devices.
  • The client app was updated, but the new version is not configured to receive messages.
For all these cases, remove this registration token and stop using it to send messages.
messaging/invalid-package-name The message was addressed to a registration token whose package name does not match the provided restrictedPackageName option.
messaging/message-rate-exceeded The rate of messages to a particular target is too high. Reduce the number of messages sent to this device or topic and do not immediately retry sending to this target.
messaging/device-message-rate-exceeded The rate of messages to a particular device is too high. Reduce the number of messages sent to this device and do not immediately retry sending to this device.
messaging/topics-message-rate-exceeded The rate of messages to subscribers to a particular topic is too high. Reduce the number of messages sent for this topic, and do not immediately retry sending to this topic.
messaging/too-many-topics A registration token has been subscribed to the maximum number of topics and cannot be subscribed to any more.
messaging/invalid-apns-credentials A message targeted to an Apple device could not be sent because the required APNs SSL certificate was not uploaded or has expired. Check the validity of your development and production certificates.
messaging/mismatched-credential The credential used to authenticate this SDK does not have permission to send messages to the device corresponding to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project. See Add Firebase to your app for documentation on how to authenticate the Firebase Admin SDK s.
messaging/authentication-error The SDK could not authenticate to the FCM servers. Make sure you authenticate the Firebase Admin SDK with a credential which has the proper permissions to send FCM messages. See Add Firebase to your app for documentation on how to authenticate the Firebase Admin SDK s.
messaging/server-unavailable The FCM server could not process the request in time. You should retry the same request, but you must:
  • Honor the Retry-After header if it is included in the response from the FCM Connection Server.
  • Implement exponential back-off in your retry mechanism. For example, if you waited one second before the first retry, wait at least two seconds before the next one, then four seconds, and so on. If you're sending multiple messages, delay each one independently by an additional random amount to avoid issuing a new request for all messages at the same time.
Senders that cause problems risk being blacklisted.
messaging/internal-error The FCM server encountered an error while trying to process the request. You could retry the same request following the requirements listed in the messaging/server-unavailable row above. If the error persists, please report the problem to our Bug Report support channel.
messaging/unknown-error An unknown server error was returned. See the raw server response in the error message for more details. If you receive this error, please report the full error message to our Bug Report support channel.