إنشاء طلبات إرسال خادم التطبيق

باستخدام Firebase Admin SDK أو بروتوكولات خادم تطبيق FCM، يمكنك إنشاء طلبات الرسائل وإرسالها إلى هذه الأنواع من الأهداف:

  • اسم الموضوع
  • حالة
  • رمز تسجيل الجهاز
  • اسم مجموعة الأجهزة (البروتوكول فقط)

يمكنك إرسال رسائل تحتوي على حمولة إشعارات مكونة من حقول محددة مسبقًا، أو حمولة بيانات للحقول المحددة بواسطة المستخدم، أو رسالة تحتوي على كلا النوعين من الحمولة. راجع أنواع الرسائل لمزيد من المعلومات.

توضح الأمثلة في هذه الصفحة كيفية إرسال رسائل إشعارات باستخدام Firebase Admin SDK (الذي يدعم Node و Java و Python و C# و Go ) وبروتوكول v1 HTTP . هناك أيضًا إرشادات لإرسال الرسائل عبر بروتوكولات HTTP وXMPP القديمة المهملة.

إرسال رسائل إلى أجهزة محددة

للإرسال إلى جهاز واحد محدد، قم بتمرير رمز تسجيل الجهاز كما هو موضح. راجع معلومات إعداد العميل لمنصتك لمعرفة المزيد حول رموز التسجيل المميزة.

Node.js

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

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

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

جافا

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

عند النجاح، تقوم كل طريقة إرسال بإرجاع معرف الرسالة. تقوم Firebase Admin SDK بإرجاع سلسلة المعرفات بتنسيق projects/{project_id}/messages/{message_id} . استجابة بروتوكول HTTP هي مفتاح JSON واحد:

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

إرسال رسائل إلى أجهزة متعددة

تسمح لك واجهات برمجة تطبيقات FCM الخاصة بالمسؤول بإرسال رسالة متعددة إلى قائمة من الرموز المميزة لتسجيل الجهاز. يمكنك تحديد ما يصل إلى 500 رمزًا مميزًا لتسجيل الجهاز لكل استدعاء.

Node.js

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

القيمة المرجعة هي قائمة من الرموز المميزة التي تتوافق مع ترتيب الرموز المميزة للإدخال. يعد هذا مفيدًا عندما تريد التحقق من الرموز المميزة التي أدت إلى حدوث أخطاء.

Node.js

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

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

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

إرسال رسائل إلى المواضيع

بعد إنشاء موضوع، إما عن طريق اشتراك مثيلات تطبيق العميل في الموضوع من جانب العميل أو عبر واجهة برمجة تطبيقات الخادم ، يمكنك إرسال رسائل إلى الموضوع. إذا كانت هذه هي المرة الأولى التي تقوم فيها بإنشاء طلبات إرسال لـ FCM، فاطلع على الدليل الخاص ببيئة الخادم الخاص بك وFCM للحصول على معلومات أساسية ومعلومات الإعداد المهمة.

في منطق الإرسال الخاص بك على الواجهة الخلفية، حدد اسم الموضوع المطلوب كما هو موضح:

Node.js

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

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

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

جافا

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

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

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

بايثون

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

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

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

يذهب

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

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

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

ج#

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

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

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

استراحة

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

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

أمر الضفيرة:

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

لإرسال رسالة إلى مجموعة من المواضيع، حدد شرطًا ، وهو عبارة عن تعبير منطقي يحدد الموضوعات المستهدفة. على سبيل المثال، سيؤدي الشرط التالي إلى إرسال رسائل إلى الأجهزة المشتركة في TopicA وإما TopicB أو TopicC :

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

تقوم FCM أولاً بتقييم أي شروط بين قوسين، ثم تقوم بتقييم التعبير من اليسار إلى اليمين. في التعبير أعلاه، المستخدم المشترك في أي موضوع واحد لا يتلقى الرسالة. وبالمثل، فإن المستخدم الذي لم يشترك في TopicA لا يتلقى الرسالة. هذه المجموعات تستقبلها:

  • TopicA والموضوع TopicB
  • TopicA و TopicC

يمكنك تضمين ما يصل إلى خمسة مواضيع في تعبيرك الشرطي.

للإرسال إلى الشرط:

Node.js

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

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

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

جافا

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

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setCondition(condition)
    .build();

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

بايثون

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

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

يذهب

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

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

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

ج#

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

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

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

استراحة

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

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

أمر الضفيرة:

curl -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. إذا كنت تقوم حاليًا بالإرسال إلى مجموعات الأجهزة باستخدام واجهات برمجة تطبيقات الإرسال القديمة المهملة لـ HTTP أو XMPP، أو أي من الإصدارات الأقدم من Firebase Admin SDK لـ Node.js استنادًا إلى البروتوكولات القديمة، فإننا نوصي بشدة بالانتقال إلى 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

إرسال مجموعة من الرسائل

تدعم حزم SDK الخاصة بالمسؤول إرسال الرسائل على دفعات. يمكنك تجميع ما يصل إلى 500 رسالة في دفعة واحدة وإرسالها جميعًا في مكالمة واحدة لواجهة برمجة التطبيقات (API)، مع تحسين كبير في الأداء مقارنة بإرسال طلبات HTTP منفصلة لكل رسالة.

يمكن استخدام هذه الميزة لإنشاء مجموعة مخصصة من الرسائل وإرسالها إلى مستلمين مختلفين، بما في ذلك المواضيع أو الرموز المميزة لتسجيل جهاز معين. استخدم هذه الميزة، على سبيل المثال، عندما تحتاج إلى إرسال رسائل في وقت واحد إلى جماهير مختلفة بتفاصيل مختلفة قليلاً في نص الرسالة.

Node.js

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

getMessaging().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 فقط)

يمكنك إرسال رسائل إلى الأجهزة في وضع التمهيد المباشر باستخدام HTTP v1 أو واجهات برمجة تطبيقات 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,
    },
}

أرسل باستخدام واجهة برمجة تطبيقات HTTP القديمة الخاصة بـ FCM

يجب أن يتضمن طلب الرسالة المفتاح "direct_boot_ok" : true في المستوى العلوي من نص الطلب. على سبيل المثال:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

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

يمكن التعامل مع الرسائل المرسلة باستخدام هذا المفتاح في نص الطلب من خلال التطبيقات الموجودة على الأجهزة الموجودة حاليًا في وضع التمهيد المباشر (وأيضًا عندما لا تكون في هذا الوضع).

تخصيص الرسائل عبر الأنظمة الأساسية

يسمح كل من Firebase Admin SDK وبروتوكول FCM v1 HTTP لطلبات الرسائل الخاصة بك بتعيين جميع الحقول المتوفرة في كائن message . هذا يتضمن:

  • مجموعة مشتركة من الحقول التي سيتم تفسيرها بواسطة جميع مثيلات التطبيق التي تتلقى الرسالة.
  • مجموعات الحقول الخاصة بالنظام الأساسي، مثل AndroidConfig و WebpushConfig ، والتي يتم تفسيرها فقط من خلال مثيلات التطبيق التي تعمل على النظام الأساسي المحدد.

تمنحك الكتل الخاصة بالنظام الأساسي المرونة لتخصيص الرسائل لمنصات مختلفة لضمان التعامل معها بشكل صحيح عند استلامها. ستأخذ الواجهة الخلفية لـ FCM جميع المعلمات المحددة في الاعتبار وستقوم بتخصيص الرسالة لكل نظام أساسي.

متى تستخدم الحقول المشتركة

استخدم الحقول المشتركة عندما تكون:

  • استهداف مثيلات التطبيق على جميع الأنظمة الأساسية — Apple وAndroid والويب
  • إرسال الرسائل إلى المواضيع

يمكن لجميع مثيلات التطبيق، بغض النظر عن النظام الأساسي، تفسير الحقول المشتركة التالية:

متى يجب استخدام الحقول الخاصة بالمنصة

استخدم الحقول الخاصة بالنظام الأساسي عندما تريد:

  • إرسال الحقول فقط إلى منصات معينة
  • إرسال الحقول الخاصة بالمنصة بالإضافة إلى الحقول المشتركة

عندما تريد إرسال القيم إلى منصات معينة فقط، لا تستخدم الحقول المشتركة؛ استخدام الحقول الخاصة بالمنصة. على سبيل المثال، لإرسال إشعار إلى أنظمة Apple الأساسية والويب فقط وليس إلى Android، يجب عليك استخدام مجموعتين منفصلتين من الحقول، واحدة لـ Apple والأخرى للويب.

عندما تقوم بإرسال رسائل ذات خيارات تسليم محددة، استخدم الحقول الخاصة بالنظام الأساسي لتعيينها. يمكنك تحديد قيم مختلفة لكل منصة إذا كنت تريد ذلك. ومع ذلك، حتى عندما تريد تعيين نفس القيمة بشكل أساسي عبر الأنظمة الأساسية، يجب عليك استخدام الحقول الخاصة بالنظام الأساسي. وذلك لأن كل نظام أساسي قد يفسر القيمة بشكل مختلف قليلاً - على سبيل المثال، يتم تعيين مدة البقاء على Android كوقت انتهاء الصلاحية بالثواني، بينما يتم تعيينها على Apple كتاريخ انتهاء الصلاحية.

مثال: رسالة إعلام مع خيارات اللون والرمز

يرسل طلب الإرسال هذا عنوانًا ومحتوى إشعارًا مشتركًا إلى جميع الأنظمة الأساسية، ولكنه يرسل أيضًا بعض التجاوزات الخاصة بالنظام الأساسي إلى أجهزة Android.

بالنسبة لنظام Android، يقوم الطلب بتعيين رمز ولون خاصين لعرضهما على أجهزة Android. كما هو مذكور في مرجع AndroidNotification ، يتم تحديد اللون بتنسيق #rrggbb، ويجب أن تكون الصورة مصدر رمز قابل للرسم محليًا لتطبيق Android.

فيما يلي تقدير تقريبي للتأثير المرئي على جهاز المستخدم:

رسم بسيط لجهازين، يعرض أحدهما رمزًا ولونًا مخصصين

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: '`$FooCorp` up 1.43% on the day',
    body: 'FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  android: {
    notification: {
      icon: 'stock_ticker_update',
      color: '#7e55c3'
    }
  },
  topic: topicName,
};

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

جافا

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 للحصول على تفاصيل كاملة حول المفاتيح المتوفرة في الكتل الخاصة بالنظام الأساسي في نص الرسالة.

مثال: رسالة إعلام بصورة مخصصة

يرسل طلب الإرسال في المثال التالي عنوان إشعار مشتركًا إلى جميع الأنظمة الأساسية، ولكنه يرسل أيضًا صورة. فيما يلي تقدير تقريبي للتأثير المرئي على جهاز المستخدم:

رسم بسيط لصورة في إشعار العرض

Node.js

const topicName = 'industry-tech';

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

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

استراحة

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 للحصول على تفاصيل كاملة حول المفاتيح المتوفرة في الكتل الخاصة بالنظام الأساسي في نص الرسالة.

مثال: رسالة إعلام مع إجراء النقر المرتبط

يرسل طلب الإرسال في المثال التالي عنوان إشعار مشتركًا إلى جميع الأنظمة الأساسية، ولكنه يرسل أيضًا إجراءً ليقوم به التطبيق استجابة لتفاعل المستخدم مع الإشعار. فيما يلي تقدير تقريبي للتأثير المرئي على جهاز المستخدم:

رسم بسيط للمستخدم وهو ينقر لفتح صفحة ويب

Node.js

const topicName = 'industry-tech';

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

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

استراحة

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 للحصول على تفاصيل كاملة حول المفاتيح المتوفرة في الكتل الخاصة بالنظام الأساسي في نص الرسالة.

مثال: رسالة إعلام مع خيارات الترجمة

يرسل طلب إرسال المثال التالي خيارات الترجمة للعميل لعرض الرسائل المترجمة. فيما يلي تقدير تقريبي للتأثير المرئي على جهاز المستخدم:

رسم بسيط لجهازين يعرضان النص باللغتين الإنجليزية والإسبانية

Node.js

var topicName = 'industry-tech';

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

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

استراحة

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

تحتوي استجابات خطأ HTTP لواجهة برمجة تطبيقات HTTP v1 على رمز خطأ ورسالة خطأ وحالة خطأ. وقد تحتوي أيضًا على مصفوفة 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: استجابة خطأ من طلب HTTP v1 API برمز تسجيل غير صالح

{
  "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. لاحظ أن بعض الكلمات (مثلlapse_key) تُستخدم أيضًا بواسطة FCM ولكنها مسموح بها في الحمولة النافعة، وفي هذه الحالة سيتم تجاوز قيمة الحمولة النافعة بقيمة FCM.
TTL غير صالح : تأكد من أن القيمة المستخدمة في ttl هي عدد صحيح يمثل مدة بالثواني بين 0 و2,419,200 (4 أسابيع).
المعلمات غير صالحة : تأكد من أن المعلمات المقدمة لها الاسم والنوع الصحيحان.
UNREGISTERED (رمز خطأ HTTP = 404) تم إلغاء تسجيل مثيل التطبيق من FCM. وهذا يعني عادةً أن الرمز المميز المستخدم لم يعد صالحًا ويجب استخدام رمز جديد. يمكن أن يحدث هذا الخطأ بسبب فقدان رموز التسجيل المميزة أو الرموز المميزة غير المسجلة.
التسجيل مفقود : إذا كان هدف الرسالة عبارة عن قيمة token ، فتأكد من أن الطلب يحتوي على رمز مميز للتسجيل.
غير مسجل : قد يتوقف صلاحية رمز التسجيل الحالي في عدد من السيناريوهات، بما في ذلك:
- إذا تم إلغاء تسجيل تطبيق العميل لدى FCM.
- إذا تم إلغاء تسجيل تطبيق العميل تلقائيًا، وهو ما يمكن أن يحدث إذا قام المستخدم بإلغاء تثبيت التطبيق. على سبيل المثال، في نظام التشغيل iOS، إذا أبلغت خدمة تعليقات APNs عن أن رمز APNs غير صالح.
- إذا انتهت صلاحية رمز التسجيل المميز (على سبيل المثال، قد تقرر Google تحديث رموز التسجيل المميزة، أو انتهت صلاحية رمز APNs المميز لأجهزة iOS).
- إذا تم تحديث تطبيق العميل ولكن الإصدار الجديد لم يتم تكوينه لتلقي الرسائل.
في كل هذه الحالات، قم بإزالة رمز التسجيل هذا من خادم التطبيق وتوقف عن استخدامه لإرسال الرسائل.
SENDER_ID_MISMATCH (رمز خطأ HTTP = 403) يختلف معرف المرسل المصادق عليه عن معرف المرسل الخاص برمز التسجيل. يرتبط رمز التسجيل بمجموعة معينة من المرسلين. عندما يقوم تطبيق عميل بالتسجيل في FCM، يجب عليه تحديد المرسلين المسموح لهم بإرسال الرسائل. يجب عليك استخدام أحد معرفات المرسل عند إرسال الرسائل إلى تطبيق العميل. إذا قمت بالتبديل إلى مرسل مختلف، فلن تعمل رموز التسجيل الحالية.
QUOTA_EXCEEDED (رمز خطأ HTTP = 429) تم تجاوز حد الإرسال لهدف الرسالة. يتم إرجاع ملحق من النوع google.rpc.QuotaFailure لتحديد الحصة النسبية التي تم تجاوزها. يمكن أن يحدث هذا الخطأ بسبب تجاوز الحصة النسبية لمعدل الرسائل، أو تجاوز الحصة النسبية لمعدل رسائل الجهاز، أو تجاوز الحصة النسبية لمعدل رسائل الموضوع.
تم تجاوز معدل الرسائل : معدل إرسال الرسائل مرتفع جدًا. يجب عليك تقليل المعدل الإجمالي الذي ترسل به الرسائل. استخدم التراجع الأسي مع تأخير مبدئي لا يقل عن دقيقة واحدة لإعادة محاولة الرسائل المرفوضة.
تم تجاوز معدل رسائل الجهاز : معدل الرسائل إلى جهاز معين مرتفع جدًا. راجع حد معدل الرسائل لجهاز واحد . قم بتقليل عدد الرسائل المرسلة إلى هذا الجهاز واستخدم التراجع الأسي لإعادة محاولة الإرسال.
تم تجاوز معدل رسائل الموضوع : معدل الرسائل المرسلة إلى المشتركين في موضوع معين مرتفع جدًا. قم بتقليل عدد الرسائل المرسلة لهذا الموضوع واستخدم التراجع الأسي مع تأخير أولي أدنى قدره دقيقة واحدة لإعادة محاولة الإرسال.
UNAVAILABLE (رمز خطأ HTTP = 503) تم تحميل الخادم بشكل زائد. تعذر على الخادم معالجة الطلب في الوقت المناسب. أعد محاولة نفس الطلب، لكن يجب عليك:
- قم بتكريم رأس "إعادة المحاولة بعد" إذا تم تضمينه في الاستجابة من خادم اتصال FCM.
- تنفيذ التراجع الأسي في آلية إعادة المحاولة الخاصة بك. (على سبيل المثال، إذا انتظرت ثانية واحدة قبل إعادة المحاولة الأولى، فانتظر ثانيتين على الأقل قبل المحاولة التالية، ثم 4 ثوانٍ وهكذا). إذا كنت ترسل رسائل متعددة، ففكر في تطبيق الارتعاش. لمزيد من المعلومات، راجع التعامل مع إعادة المحاولة . المرسلون الذين يتسببون في حدوث مشكلات يتعرضون لخطر إدراجهم في القائمة المرفوضة.
INTERNAL (رمز خطأ HTTP = 500) حدث خطأ داخلي غير معروف. واجه الخادم خطأ أثناء محاولة معالجة الطلب. يمكنك إعادة محاولة نفس الطلب باتباع الاقتراحات الموجودة في معالجة إعادة المحاولة . إذا استمر الخطأ، فيرجى الاتصال بدعم Firebase.
THIRD_PARTY_AUTH_ERROR (رمز خطأ HTTP = 401) كانت شهادة APNs أو مفتاح مصادقة دفع الويب غير صالح أو مفقود. لا يمكن إرسال رسالة موجهة إلى جهاز 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.
  • تم إلغاء تسجيل تطبيق العميل تلقائيًا. يمكن أن يحدث هذا إذا قام المستخدم بإلغاء تثبيت التطبيق، أو، على أنظمة Apple الأساسية، إذا أبلغت خدمة تعليقات APNs عن رمز APNs المميز على أنه غير صالح.
  • انتهت صلاحية رمز التسجيل. على سبيل المثال، قد تقرر Google تحديث الرموز المميزة للتسجيل أو ربما انتهت صلاحية رمز APN المميز لأجهزة Apple.
  • تم تحديث تطبيق العميل، ولكن لم يتم تكوين الإصدار الجديد لتلقي الرسائل.
في كل هذه الحالات، قم بإزالة رمز التسجيل هذا وتوقف عن استخدامه لإرسال الرسائل.
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 نظرًا لعدم تحميل شهادة APNs SSL المطلوبة أو انتهاء صلاحيتها. التحقق من صحة شهادات التطوير والإنتاج الخاصة بك.
messaging/mismatched-credential لا تحتوي بيانات الاعتماد المستخدمة لمصادقة SDK على إذن لإرسال رسائل إلى الجهاز المتوافق مع رمز التسجيل المميز. تأكد من أن رمز الاعتماد والتسجيل ينتميان إلى نفس مشروع Firebase. راجع إضافة Firebase إلى تطبيقك للحصول على وثائق حول كيفية مصادقة Firebase Admin SDKs.
messaging/authentication-error تعذر على SDK المصادقة على خوادم FCM. تأكد من مصادقة Firebase Admin SDK باستخدام بيانات اعتماد تتمتع بالأذونات المناسبة لإرسال رسائل FCM. راجع إضافة Firebase إلى تطبيقك للحصول على وثائق حول كيفية مصادقة Firebase Admin SDKs.
messaging/server-unavailable تعذر على خادم FCM معالجة الطلب في الوقت المناسب. يجب عليك إعادة محاولة نفس الطلب، ولكن يجب عليك:
  • قم بتكريم رأس Retry-After " إذا تم تضمينه في الاستجابة من خادم اتصال FCM.
  • قم بتنفيذ التراجع الأسي في آلية إعادة المحاولة الخاصة بك. على سبيل المثال، إذا انتظرت ثانية واحدة قبل إعادة المحاولة الأولى، فانتظر ثانيتين على الأقل قبل المحاولة التالية، ثم أربع ثوانٍ، وهكذا. إذا كنت ترسل رسائل متعددة، قم بتأخير كل واحدة بشكل مستقل بمقدار عشوائي إضافي لتجنب إصدار طلب جديد لجميع الرسائل في نفس الوقت.
المرسلون الذين يتسببون في حدوث مشكلات يتعرضون لخطر إدراجهم في القائمة السوداء.
messaging/internal-error واجه خادم FCM خطأً أثناء محاولة معالجة الطلب. يمكنك إعادة محاولة نفس الطلب باتباع المتطلبات المذكورة في صف messaging/server-unavailable أعلاه. إذا استمر الخطأ، فيرجى الإبلاغ عن المشكلة إلى قناة دعم الإبلاغ عن الأخطاء لدينا.
messaging/unknown-error تم إرجاع خطأ غير معروف في الخادم. راجع استجابة الخادم الأولية في رسالة الخطأ لمزيد من التفاصيل. إذا تلقيت هذا الخطأ، فيرجى الإبلاغ عن رسالة الخطأ الكاملة إلى قناة دعم تقرير الأخطاء لدينا.

أرسل الرسائل باستخدام بروتوكولات خادم التطبيقات القديمة

إذا كنت تستخدم البروتوكولات القديمة حاليًا، فقم بإنشاء طلبات الرسائل كما هو موضح في هذا القسم. ضع في اعتبارك أنه إذا كنت ترسل إلى منصات متعددة عبر HTTP، فيمكن لبروتوكول v1 أن يبسط طلبات رسائلك بشكل كبير.

إرسال رسائل إلى أجهزة محددة

لإرسال رسائل إلى أجهزة معينة، قم بتعيين مفتاح to لرمز التسجيل المميز لمثيل التطبيق المحدد. راجع معلومات إعداد العميل لمنصتك لمعرفة المزيد حول رموز التسجيل المميزة.

طلب HTTP POST

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

استجابة HTTP

{ "multicast_id": 108,
  "success": 1,
  "failure": 0,
  "results": [
    { "message_id": "1:08" }
  ]
}

رسالة XMPP

<message id="">
  <gcm xmlns="google:mobile:data">
    { "data": {
      "score": "5x1",
      "time": "15:10"
    },
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  }
  </gcm>
</message>

استجابة XMPP

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "from":"REGID",
      "message_id":"m-1366082849205"
      "message_type":"ack"
  }
  </gcm>
</message>

يوفر خادم اتصال XMPP بعض الخيارات الأخرى للاستجابات. راجع تنسيق استجابة الخادم .

للحصول على القائمة الكاملة لخيارات الرسائل المتاحة عند إرسال الرسائل النهائية إلى تطبيقات العميل، راجع المعلومات المرجعية لبروتوكول خادم الاتصال الذي اخترته، HTTP أو XMPP .

إرسال رسائل إلى المواضيع

إن إرسال الرسائل إلى موضوع Firebase Cloud Messaging يشبه إلى حد كبير إرسال الرسائل إلى جهاز فردي أو إلى مجموعة مستخدمين. يقوم خادم التطبيق بتعيين المفتاح to بقيمة مثل /topics/yourTopic . يمكن للمطورين اختيار أي اسم موضوع يطابق التعبير العادي: "/topics/[a-zA-Z0-9-_.~%]+" .

للإرسال إلى مجموعات من موضوعات متعددة، يجب أن يقوم خادم التطبيق بتعيين مفتاح condition (بدلاً من المفتاح to ) إلى شرط منطقي يحدد المواضيع المستهدفة. على سبيل المثال، لإرسال رسائل إلى الأجهزة المشتركة في TopicA وإما TopicB أو TopicC :

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

تقوم FCM أولاً بتقييم أي شروط بين قوسين، ثم تقوم بتقييم التعبير من اليسار إلى اليمين. في التعبير أعلاه، المستخدم المشترك في أي موضوع واحد لا يتلقى الرسالة. وبالمثل، فإن المستخدم الذي لم يشترك في TopicA لا يتلقى الرسالة. هذه المجموعات تستقبلها:

  • الموضوع أ والموضوع ب
  • TopicA وTopicC

يمكنك تضمين ما يصل إلى خمسة مواضيع في تعبيرك الشرطي، ويتم دعم الأقواس. عوامل التشغيل المدعومة: && ، || .

طلب موضوع HTTP POST

إرسال إلى موضوع واحد:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA


إرسال إلى الأجهزة المشتركة في موضوعات "الكلاب" أو "القطط":

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA


استجابة موضوع HTTP

// Success example:
{
  "message_id": "1023456"
}

// failure example:
{
  "error": "TopicsMessageRateExceeded"
}

موضوع رسالة XMPP

إرسال إلى موضوع واحد:

<message id="">
  <gcm xmlns="google:mobile:data">


  </gcm>
</message>

إرسال إلى الأجهزة المشتركة في موضوعات "الكلاب" أو "القطط":

<message id="">
  <gcm xmlns="google:mobile:data">


  </gcm>
</message>

استجابة الموضوع XMPP

// Success example:
{
  "message_id": "1023456"
}

// failure example:
{
  "error": "TopicsMessageRateExceeded"
}

توقع ما يصل إلى 30 ثانية من التأخير قبل أن يُرجع خادم FCM استجابة النجاح أو الفشل لطلبات إرسال الموضوع. تأكد من تعيين قيمة مهلة خادم التطبيق في الطلب وفقًا لذلك.

إرسال رسائل إلى مجموعات الأجهزة

إن إرسال الرسائل إلى مجموعة أجهزة باستخدام واجهات برمجة التطبيقات القديمة المهملة يشبه إلى حد كبير إرسال الرسائل إلى جهاز فردي. قم بتعيين to إلى مفتاح الإعلام الفريد لمجموعة الأجهزة. توضح الأمثلة في هذا القسم كيفية إرسال رسائل البيانات إلى مجموعات الأجهزة في بروتوكولات HTTP وXMPP القديمة.

طلب HTTP POST لمجموعة الأجهزة

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "aUniqueKey",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!",
   }
}

استجابة HTTP لمجموعة الأجهزة

فيما يلي مثال على "النجاح" - يحتوي notification_key على رمزين مميزين للتسجيل مرتبطين به، وقد تم إرسال الرسالة بنجاح إلى كليهما:

{
  "success": 2,
  "failure": 0
}

فيما يلي مثال على "النجاح الجزئي" - يحتوي notification_key على 3 رموز تسجيل مميزة مرتبطة به. تم إرسال الرسالة بنجاح إلى أحد رموز التسجيل المميزة فقط. تسرد رسالة الرد رموز التسجيل ( registration_ids ) التي فشلت في تلقي الرسالة:

{
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

عندما يفشل تسليم رسالة إلى واحد أو أكثر من رموز التسجيل المرتبطة بـ notification_key ، يجب على خادم التطبيق إعادة المحاولة مع التراجع بين مرات المحاولات.

إذا حاول الخادم إرسال رسالة إلى مجموعة أجهزة لا تحتوي على أعضاء، فستبدو الاستجابة كما يلي، مع 0 نجاح و0 فشل:

{
  "success": 0,
  "failure": 0
}

رسالة XMPP لمجموعة الأجهزة

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to": "aUniqueKey",
      "message_id": "m-1366082849205" ,
      "data": {
          "hello":"This is a Firebase Cloud Messaging Device Group Message!"
      }
  }
  </gcm>
</message>

استجابة مجموعة الأجهزة XMPP

عندما يتم إرسال الرسالة إلى أي من الأجهزة في المجموعة بنجاح، يستجيب خادم اتصال XMPP بـ ACK. إذا فشلت كافة الرسائل المرسلة إلى كافة الأجهزة في المجموعة، يستجيب خادم اتصال XMPP بـ NACK.

فيما يلي مثال على "النجاح" - يحتوي notification_key على 3 رموز تسجيل مرتبطة به، وقد تم إرسال الرسالة بنجاح إليهم جميعًا:

{
  "from": "aUniqueKey",
  "message_type": "ack",
  "success": 3,
  "failure": 0,
  "message_id": "m-1366082849205"
}

فيما يلي مثال على "النجاح الجزئي" - يحتوي notification_key على 3 رموز تسجيل مميزة مرتبطة به. تم إرسال الرسالة بنجاح إلى أحد رموز التسجيل المميزة فقط. تسرد رسالة الرد رموز التسجيل التي فشلت في تلقي الرسالة:

{
  "from": "aUniqueKey",
  "message_type": "ack",
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

عندما يفشل خادم اتصال FCM في التوصيل إلى جميع الأجهزة في المجموعة. سوف يتلقى خادم التطبيق استجابة nack.

للحصول على القائمة الكاملة لخيارات الرسائل، راجع المعلومات المرجعية لبروتوكول خادم الاتصال الذي اخترته، HTTP أو XMPP .

طرق الإرسال القديمة لـ Firebase Admin SDK

تدعم Firebase Admin Node.js SDK طرق إرسال رسائل (FCM) بناءً على واجهة برمجة تطبيقات خادم Legacy FCM . تقبل هذه الطرق وسيطات مختلفة مقارنة بطريقة send() . يجب عليك استخدام طريقة send() كلما أمكن ذلك، واستخدام الطرق الموضحة في هذه الصفحة فقط عند إرسال رسائل إلى أجهزة فردية أو مجموعات أجهزة.

إرسال إلى الأجهزة الفردية

يمكنك تمرير رمز التسجيل إلى طريقة sendToDevice() لإرسال رسالة إلى هذا الجهاز:

Node.js

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

// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the device corresponding to the provided
// registration token.
getMessaging().sendToDevice(registrationToken, payload)
  .then((response) => {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

يمكن للطريقة sendToDevice() أيضًا إرسال رسالة بث متعدد (أي رسالة إلى أجهزة متعددة) عن طريق تمرير مصفوفة من رموز التسجيل المميزة بدلاً من مجرد رمز تسجيل واحد:

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
  // ...
  'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...'
];

// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the devices corresponding to the provided
// registration tokens.
getMessaging().sendToDevice(registrationTokens, payload)
  .then((response) => {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

يُرجع الأسلوب sendToDevice() وعدًا تم حله باستخدام كائن MessagingDevicesResponse الذي يحتوي على الاستجابة من FCM. نوع الإرجاع له نفس التنسيق عند تمرير رمز تسجيل واحد أو مجموعة من رموز التسجيل المميزة.

تتسبب بعض الحالات، مثل خطأ المصادقة أو تحديد المعدل، في فشل معالجة الرسالة بالكامل. في هذه الحالات، يتم رفض الوعد الذي تم إرجاعه بواسطة sendToDevice() مع وجود خطأ. للحصول على قائمة كاملة برموز الأخطاء، بما في ذلك الأوصاف وخطوات الحل، راجع أخطاء Admin FCM API .

إرسال إلى مجموعة الأجهزة

يتيح لك الأسلوب sendToDeviceGroup() إرسال رسالة إلى مجموعة أجهزة عن طريق تحديد مفتاح الإشعارات لمجموعة الأجهزة تلك:

Node.js

// See the "Managing device groups" link above on how to generate a
// notification key.
const notificationKey = 'some-notification-key';

// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the device group corresponding to the provided
// notification key.
getMessaging().sendToDeviceGroup(notificationKey, payload)
  .then((response) => {
    // See the MessagingDeviceGroupResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

يُرجع الأسلوب sendToDeviceGroup() وعدًا تم حله باستخدام كائن MessagingDevicesResponse الذي يحتوي على الاستجابة من FCM.

تتسبب بعض الحالات، مثل خطأ المصادقة أو تحديد المعدل، في فشل معالجة الرسالة بأكملها. في هذه الحالات، يتم رفض الوعد الذي تم إرجاعه بواسطة sendToDeviceGroup() مع وجود خطأ. للحصول على قائمة كاملة برموز الأخطاء، بما في ذلك الأوصاف وخطوات الحل، راجع أخطاء Admin FCM API .

تحديد حمولة الرسالة

تقبل الطرق المذكورة أعلاه المستندة إلى بروتوكولات FCM القديمة حمولة الرسالة باعتبارها الوسيطة الثانية وتدعم كلاً من رسائل الإعلام والبيانات . يمكنك تحديد نوع واحد أو كلا النوعين من الرسائل عن طريق إنشاء كائن يحتوي على data و/أو مفاتيح notification . على سبيل المثال، فيما يلي كيفية تحديد أنواع مختلفة من حمولات الرسائل:

رسالة الإخطار

const payload = {
  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.'
  }
};

رسالة البيانات

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

رسالة مجمعة

const payload = {
  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.'
  },
  data: {
    stock: 'GOOG',
    open: '829.62',
    close: '635.67'
  }
};

تحتوي حمولات رسائل الإعلام على مجموعة فرعية محددة مسبقًا من الخصائص الصالحة وتختلف قليلاً اعتمادًا على نظام تشغيل الهاتف المحمول الذي تستهدفه. راجع المستندات المرجعية لـ NotificationMessagePayload للحصول على القائمة الكاملة.

تتكون حمولات رسائل البيانات من أزواج قيمة مفتاحية مخصصة مع بعض القيود، بما في ذلك حقيقة أن جميع القيم يجب أن تكون سلاسل. راجع المستندات المرجعية الخاصة بـ DataMessagePayload للحصول على قائمة كاملة بالقيود.

تحديد خيارات الرسالة

تقبل الطرق المذكورة أعلاه المستندة إلى بروتوكولات FCM القديمة وسيطة ثالثة اختيارية تحدد بعض الخيارات للرسالة. على سبيل المثال، يرسل المثال التالي رسالة ذات أولوية عالية إلى جهاز تنتهي صلاحيته بعد 24 ساعة:

Node.js

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

// See the "Defining the message payload" section above for details
// on how to define a message payload.
const payload = {
  notification: {
    title: 'Urgent action needed!',
    body: 'Urgent action is needed to prevent your account from being disabled!'
  }
};

// Set the message as high priority and have it expire after 24 hours.
const options = {
  priority: 'high',
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
getMessaging().sendToDevice(registrationToken, payload, options)
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

راجع المستندات المرجعية لـ MessagingOptions للحصول على قائمة كاملة بالخيارات المتاحة.