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

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

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

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

توضّح الأمثلة في هذه الصفحة كيفية إرسال رسائل إشعارات باستخدام حزمة SDK لمشرف Firebase (التي تتوافق مع Node وJava وPython وC# وGo) وv1 HTTP Protocol. تتوفّر أيضًا إرشادات حول إرسال الرسائل عبر بروتوكولات 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);
  });

Java

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

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

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

Python

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

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

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

Go

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

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

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

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

C#‎

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

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

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

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
   "message":{
      "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
      "notification":{
        "body":"This is an FCM notification message!",
        "title":"FCM Message"
      }
   }
}

الأمر cURL:

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

عند نجاح كل طريقة إرسال، يتم عرض معرِّف الرسالة. تعرض حزمة SDK لمشرف Firebase سلسلة رقم التعريف بالتنسيق 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');
  });

Java

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

Python

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

Go

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

C#‎

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

Java

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

MulticastMessage message = MulticastMessage.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .addAllTokens(registrationTokens)
    .build();
BatchResponse response = FirebaseMessaging.getInstance().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);
}

Python

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

message = messaging.MulticastMessage(
    data={'score': '850', 'time': '2:45'},
    tokens=registration_tokens,
)
response = messaging.send_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))

Go

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

C#‎

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

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

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

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

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

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

Node.js

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

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

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

Java

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

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

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

Python

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

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

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

Go

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

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

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

C#‎

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

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

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

REST

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

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

الأمر cURL:

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

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

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

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

  • TopicA وTopicB
  • TopicA وTopicC

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

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

Node.js

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

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

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

Java

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

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

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

Python

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

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

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

Go

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

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

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

C#‎

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

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

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

REST

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

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

الأمر cURL:

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

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

لإرسال الرسائل إلى مجموعات الأجهزة، استخدِم واجهة برمجة التطبيقات HTTP v1. إذا كنت ترسل حاليًا إلى مجموعات الأجهزة باستخدام واجهات برمجة التطبيقات القديمة للإرسال والمتوقّفة نهائيًا لـ HTTP أو XMPP أو أي من الإصدارات القديمة من حزمة SDK لمشرف Firebase لنظام Node.js استنادًا إلى البروتوكولات القديمة، ننصحك بشدة بإجراء عملية نقل البيانات إلى واجهة برمجة تطبيقات HTTP الإصدار 1 في أقرب فرصة ممكنة. سيتم إيقاف واجهات برمجة التطبيقات القديمة للإرسال وإزالتها في حزيران (يونيو) 2024.

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

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
   "message":{
      "token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ",
      "data":{
        "hello": "This is a Firebase Cloud Messaging device group message!"
      }
   }
}

الأمر cURL

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

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

تتيح حِزم SDK للمشرف إرسال الرسائل على دفعات. يمكنك تجميع ما يصل إلى 500 رسالة في دفعة واحدة وإرسالها جميعًا في طلب بيانات واحد من واجهة برمجة التطبيقات، مع إجراء تحسُّن ملحوظ في الأداء مقارنةً بإرسال طلبات 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');
  });

Java

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

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

Python

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

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

Go

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

C#‎

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

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

إرسال رسائل مباشرة مع تفعيل التشغيل (Android فقط)

يمكنك إرسال رسائل إلى الأجهزة في وضع التشغيل المباشر باستخدام HTTP v1 أو واجهات برمجة تطبيقات HTTP القديمة. وقبل الإرسال إلى الأجهزة في وضع التشغيل المباشر، تأكّد من إكمال الخطوات لتمكين أجهزة العملاء من تلقّي رسائل "المراسلة عبر السحابة الإلكترونية من Firebase" في وضع التشغيل المباشر.

الإرسال باستخدام واجهة برمجة تطبيقات 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,
    },
}

الإرسال باستخدام واجهة برمجة تطبيقات HTTP القديمة للمراسلة عبر السحابة الإلكترونية من Firebase

يجب أن يشتمل طلب الرسالة على المفتاح "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
}

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

تخصيص الرسائل على جميع المنصّات

إنّ حزمة تطوير البرامج (SDK) لمشرف Firebase وبروتوكول HTTP الإصدار 1 من "المراسلة عبر السحابة الإلكترونية من Firebase" تتيحان لطلبات رسائلك ضبط جميع الحقول المتاحة في العنصر message. يشمل هذا النوع من المحتوى ما يلي:

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

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

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

استخدِم الحقول الشائعة عندما:

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

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

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

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

  • إرسال الحقول إلى منصات محدَّدة فقط
  • إرسال الحقول الخاصة بالنظام الأساسي بالإضافة إلى الحقول المشتركة

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

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

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

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

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

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

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

Node.js

const topicName = 'industry-tech';

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

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

Java

Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setAndroidConfig(AndroidConfig.builder()
        .setTtl(3600 * 1000)
        .setNotification(AndroidNotification.builder()
            .setIcon("stock_ticker_update")
            .setColor("#f45342")
            .build())
        .build())
    .setApnsConfig(ApnsConfig.builder()
        .setAps(Aps.builder()
            .setBadge(42)
            .build())
        .build())
    .setTopic("industry-tech")
    .build();

Python

message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    android=messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600),
        priority='normal',
        notification=messaging.AndroidNotification(
            icon='stock_ticker_update',
            color='#f45342'
        ),
    ),
    apns=messaging.APNSConfig(
        payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42),
        ),
    ),
    topic='industry-tech',
)

Go

oneHour := time.Duration(1) * time.Hour
badge := 42
message := &messaging.Message{
	Notification: &messaging.Notification{
		Title: "$GOOG up 1.43% on the day",
		Body:  "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
	},
	Android: &messaging.AndroidConfig{
		TTL: &oneHour,
		Notification: &messaging.AndroidNotification{
			Icon:  "stock_ticker_update",
			Color: "#f45342",
		},
	},
	APNS: &messaging.APNSConfig{
		Payload: &messaging.APNSPayload{
			Aps: &messaging.Aps{
				Badge: &badge,
			},
		},
	},
	Topic: "industry-tech",
}

C#‎

var message = new Message
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Android = new AndroidConfig()
    {
        TimeToLive = TimeSpan.FromHours(1),
        Notification = new AndroidNotification()
        {
            Icon = "stock_ticker_update",
            Color = "#f45342",
        },
    },
    Apns = new ApnsConfig()
    {
        Aps = new Aps()
        {
            Badge = 42,
        },
    },
    Topic = "industry-tech",
};

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"`$FooCorp` up 1.43% on the day",
       "body":"FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day."
     },
     "android":{
       "notification":{
         "icon":"stock_ticker_update",
         "color":"#7e55c3"
       }
     }
   }
 }

راجِع المستندات المرجعية لـ HTTP الإصدار 1 لمعرفة التفاصيل الكاملة حول المفاتيح المتاحة في المجموعات الخاصة بالنظام الأساسي في نص الرسالة.

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

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

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

Node.js

const topicName = 'industry-tech';

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

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

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Sparky says hello!",
     },
     "android":{
       "notification":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "mutable-content":1
         }
       },
       "fcm_options": {
           "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "webpush":{
       "headers":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     }
   }
 }

راجِع المستندات المرجعية لـ HTTP الإصدار 1 لمعرفة التفاصيل الكاملة حول المفاتيح المتاحة في المجموعات الخاصة بالنظام الأساسي في نص الرسالة.

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

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

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

Node.js

const topicName = 'industry-tech';

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

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

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Breaking News...",
     },
     "android":{
       "notification":{
         "click_action":"news_intent"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "category" : "INVITE_CATEGORY"
         }
       },
     },
     "webpush":{
       "fcm_options":{
         "link":"breakingnews.html"
       }
     }
   }
 }

راجِع المستندات المرجعية لـ HTTP الإصدار 1 لمعرفة التفاصيل الكاملة حول المفاتيح المتاحة في المجموعات الخاصة بالنظام الأساسي في نص الرسالة.

مثال: رسالة إشعار تتضمّن خيارات الترجمة

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

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

Node.js

var topicName = 'industry-tech';

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

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

REST

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

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
             "topic":"Tech",
             "android":{
               "ttl":"3600s",
               "notification":{
                 "body_loc_key": "STOCK_NOTIFICATION_BODY",
                 "body_loc_args":  ["FooCorp", "11.80", "835.67", "1.43"],
               },
             },
             "apns":{
               "payload":{
                 "aps":{
                   "alert" : {
                     "loc-key": "STOCK_NOTIFICATION_BODY",
                     "loc-args":  ["FooCorp", "11.80", "835.67", "1.43"],
                    },
                 },
               },
             },
  },
}'

راجِع المستندات المرجعية لـ HTTP الإصدار 1 لمعرفة التفاصيل الكاملة حول المفاتيح المتاحة في المجموعات الخاصة بالنظام الأساسي في نص الرسالة.

رموز خطأ REST لواجهة برمجة التطبيقات HTTP v1

استجابات خطأ HTTP لواجهة برمجة التطبيقات HTTP v1 API تحتوي على رمز خطأ ورسالة خطأ وحالة خطأ. قد تحتوي أيضًا على مصفوفة details تحتوي على مزيد من التفاصيل حول الخطأ.

في ما يلي نموذجان للردود عن الخطأ:

المثال 1: استجابة خطأ من طلب واجهة برمجة تطبيقات 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: استجابة عن طريق الخطأ من طلب 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 به خطأ خاص بالمراسلة عبر السحابة الإلكترونية من Firebase. بالنسبة إلى الكثير من الأخطاء، تحتوي مصفوفة التفاصيل على المعلومات التي ستحتاج إلى تصحيح الأخطاء والعثور على حلّ لها.

يسرد الجدول التالي رموز أخطاء FCM v1 REST API وأوصافها.

رمز الخطأ خطوات الوصف والحلّ
UNSPECIFIED_ERROR لا تتوفّر مزيد من المعلومات عن هذا الخطأ. بلا.
INVALID_ARGUMENT (رمز خطأ HTTP = 400) مَعلمات الطلب غير صالحة. يتم عرض إضافة من النوع google.rpc.BadRequest لتحديد الحقل غير الصالح. تشمل الأسباب المحتملة تسجيلاً غير صالح أو اسم حزمة غير صالح أو الرسالة كبيرة جدًا أو مفتاح بيانات غير صالح أو مدة البقاء غير صالحة أو معلمات أخرى غير صالحة.
تسجيل غير صالح: تحقَّق من تنسيق الرمز المميّز للتسجيل الذي ترسله إلى الخادم. وتأكَّد من أنّه يتطابق مع الرمز المميّز للتسجيل الذي يتلقّاه تطبيق العميل من التسجيل في خدمة "المراسلة عبر السحابة الإلكترونية من Firebase". يجب عدم اقتطاع الرمز المميّز أو إضافة أحرف أخرى.
اسم الحزمة غير صالح: تأكَّد من أنّ الرسالة موجهة إلى رمز مميَّز للتسجيل يتطابق اسم الحزمة الخاص به مع القيمة التي تم تمريرها في الطلب.
الرسالة كبيرة جدًا: تأكَّد من أنّ الحجم الإجمالي لبيانات الحمولة المضمّنة في الرسالة لا يتجاوز حدود "المراسلة عبر السحابة الإلكترونية من Firebase": 4096 بايت لمعظم الرسائل أو 2048 بايت في حالة الرسائل إلى المواضيع. يتضمن هذا كلاً من المفاتيح والقيم.
مفتاح بيانات غير صالح: تأكَّد من أنّ بيانات الحمولة لا تحتوي على مفتاح (مثل from أو gcm، أو أي قيمة مسبوقة بـ google) تستخدمه ميزة "المراسلة عبر السحابة الإلكترونية من Firebase" داخليًا. تجدر الإشارة إلى أنّ خدمة FCM تستخدم أيضًا بعض الكلمات (مثل expand_key) ولكن يُسمح بها في الحمولة، وفي هذه الحالة ستلغي قيمة FCM قيمة الحمولة.
مدة البقاء غير صالحة: تأكَّد من أنّ القيمة المستخدَمة في ttl هي عدد صحيح يمثّل مدة بالثواني بين 0 و2,419,200 (4 أسابيع).
المَعلمات غير الصالحة: تأكَّد من أنّ المَعلمات المقدّمة تحمل الاسم والنوع الصحيحَين.
UNREGISTERED (رمز خطأ HTTP = 404) تم إلغاء تسجيل مثيل التطبيق من خدمة "المراسلة عبر السحابة الإلكترونية من Firebase". ويعني ذلك عادةً أنّ الرمز المميّز المستخدَم لم يعُد صالحًا ويجب استخدام رمز جديد. قد يرجع السبب في هذا الخطأ إلى فقدان رموز التسجيل المميَّزة أو الرموز غير المسجَّلة.
التسجيل غير متوفّر: إذا كان هدف الرسالة هو قيمة token، تأكَّد من أنّ الطلب يحتوي على رمز مميّز للتسجيل.
غير مسجَّل: قد لا يكون الرمز المميّز للتسجيل الحالي صالحًا في عدد من السيناريوهات، بما في ذلك:
- في حال إلغاء تسجيل تطبيق العميل لدى "المراسلة عبر السحابة الإلكترونية من Firebase".
- إذا تم إلغاء تسجيل تطبيق العميل تلقائيًا، قد يحدث ذلك إذا ألغى المستخدم تثبيت التطبيق. على سبيل المثال، في نظام iOS، إذا أبلغت "خدمة تعليقات APNs" عن أنّ الرمز المميّز لرموز APN غير صالح.
- في حال انتهاء صلاحية الرمز المميّز للتسجيل (على سبيل المثال، من الممكن أن تقرر Google إعادة تحميل الرموز المميّزة للتسجيل أو انتهت صلاحية الرمز المميّز لنقاط الوصول (APN) لأجهزة iOS).
- إذا تم تحديث تطبيق العميل بدون ضبط الإصدار الجديد لتلقّي الرسائل.
في جميع هذه الحالات، يمكنك إزالة الرمز المميّز للتسجيل هذا من خادم التطبيق والتوقّف عن استخدامه لإرسال الرسائل.
SENDER_ID_MISMATCH (رمز خطأ HTTP = 403) يختلف معرّف المُرسِل الذي تمت مصادقته عن معرِّف المُرسِل للرمز المميّز للتسجيل. يرتبط الرمز المميز للتسجيل بمجموعة معيّنة من المُرسِلين. عندما يُسجِّل تطبيق عميل في ميزة "المراسلة عبر السحابة الإلكترونية من Firebase"، يجب تحديد المُرسِلين المسموح لهم بإرسال الرسائل. عليك استخدام أحد معرّفات المُرسِلين هذه عند إرسال رسائل إلى تطبيق العميل. في حال التبديل إلى مُرسِل مختلف، لن تعمل رموز التسجيل المميّزة الحالية.
QUOTA_EXCEEDED (رمز خطأ HTTP = 429) تم تجاوز حد الإرسال لهدف الرسائل. يتم عرض إضافة من النوع google.rpc.QuotaFailure لتحديد الحصة التي تم تجاوزها. يمكن أن يرجع السبب في هذا الخطأ إلى تجاوز حصة معدّل الرسائل أو تجاوز حصة معدّل الرسائل على الجهاز أو تجاوز حصة معدّل الرسائل حسب الموضوع.
تم تجاوز معدل الرسائل: معدل إرسال الرسائل مرتفع جدًا. يجب خفض المعدل الإجمالي لإرسال الرسائل. استخدِم ميزة "الرقود الأسي" مع مهلة مبدئية تبلغ دقيقة واحدة على الأقل لإعادة محاولة إرسال الرسائل المرفوضة.
تم تجاوز معدّل الرسائل على الجهاز: معدّل الرسائل المرسَلة إلى جهاز معيّن مرتفع جدًا. راجِع الحد الأقصى لمعدّل الرسائل على جهاز واحد. يمكنك تقليل عدد الرسائل المُرسَلة إلى هذا الجهاز واستخدام ميزة "الرقود الأسي" لإعادة محاولة الإرسال.
تم تجاوز معدّل الرسائل حسب الموضوع: معدّل الرسائل المرسَلة إلى المشتركين في موضوع معيّن مرتفع جدًا. يمكنك تقليل عدد الرسائل المُرسَلة لهذا الموضوع واستخدام ميزة "الرقود الأسي الثنائي" مع مهلة أوّلية لا تقل عن دقيقة واحدة لإعادة محاولة الإرسال.
UNAVAILABLE (رمز خطأ HTTP = 503) هناك تحميل زائد على الخادم. لم يتمكّن الخادم من معالجة الطلب في الوقت المناسب. يُرجى إعادة محاولة الطلب نفسه، ولكن عليك إجراء ما يلي:
- تنفيذ العنوان Try- After (إعادة المحاولة بعد) إذا كان مُضمَّنًا في الاستجابة من خادم اتصال FCM.
- تنفيذ الرقود الأسي في آلية إعادة المحاولة (على سبيل المثال، إذا انتظرت ثانية واحدة قبل إعادة المحاولة الأولى، انتظر لمدة ثانيتين على الأقل قبل المحاولة التالية، ثم 4 ثوانٍ وهكذا). إذا كنت ترسل رسائل متعددة، ضع في اعتبارك تطبيق عدم الاستقرار. لمزيد من المعلومات، يُرجى الاطّلاع على التعامل مع عمليات إعادة المحاولة. ويتعرض المرسِلون الذين يسببون مشاكل إلى القائمة المرفوضة.
INTERNAL (رمز خطأ HTTP = 500) حدث خطأ داخلي غير معروف. واجه الخادم خطأً أثناء محاولة معالجة الطلب. يمكنك إعادة محاولة الطلب نفسه بعد اتّباع الاقتراحات في التعامل مع عمليات إعادة المحاولة. في حال استمرار ظهور الخطأ، يُرجى التواصل مع فريق دعم Firebase.
THIRD_PARTY_AUTH_ERROR (رمز خطأ HTTP = 401) كانت شهادة APNs أو مفتاح المصادقة الفورية على الويب غير صالح أو غير متوفّر. تعذَّر إرسال رسالة موجَّهة إلى جهاز iOS أو تسجيل فوري على الويب. تحقَّق من صلاحية بيانات اعتماد التطوير والإنتاج.

رموز الخطأ الخاصة بالمشرف

يسرد الجدول التالي رموز خطأ واجهة برمجة التطبيقات FCM Admin في Firebase وأوصافها، بما في ذلك خطوات الحل المقترحة.

رمز الخطأ خطوات الوصف والحلّ
messaging/invalid-argument تم تقديم وسيطة غير صالحة إلى طريقة FCM. ويجب أن تحتوي رسالة الخطأ على معلومات إضافية.
messaging/invalid-recipient مستلِم الرسالة المقصودة غير صالح. ويجب أن تحتوي رسالة الخطأ على معلومات إضافية.
messaging/invalid-payload تم تقديم كائن حمولة رسالة غير صالح. ويجب أن تحتوي رسالة الخطأ على معلومات إضافية.
messaging/invalid-data-payload-key تحتوي حمولة رسالة البيانات على مفتاح غير صالح. اطّلِع على المستندات المرجعية بشأن DataMessagePayload للتعرّف على المفاتيح المحظورة.
messaging/payload-size-limit-exceeded تتجاوز حمولة الرسالة المقدّمة حدود حجم "المراسلة عبر السحابة الإلكترونية من Firebase". ويبلغ الحدّ الأقصى 4096 بايت لمعظم الرسائل. وبالنسبة إلى الرسائل المرسلة إلى المواضيع، يبلغ الحد الأقصى 2048 بايت. ويشمل الحجم الإجمالي للحمولة كلاً من المفاتيح والقيم.
messaging/invalid-options تم تقديم كائن خيارات رسالة غير صالح. ويجب أن تحتوي رسالة الخطأ على معلومات إضافية.
messaging/invalid-registration-token تم تقديم رمز مميز للتسجيل غير صالح. وتأكَّد من أنّه يتطابق مع الرمز المميّز للتسجيل الذي يتلقّاه تطبيق العميل من التسجيل في خدمة "المراسلة عبر السحابة الإلكترونية من Firebase". ويجب عدم اقتطاعه أو إضافة أحرف أخرى إليه.
messaging/registration-token-not-registered الرمز المميّز للتسجيل الذي قدّمته غير مسجَّل. يمكن إلغاء تسجيل رمز مميَّز للتسجيل كان صالحًا في السابق لأسباب مختلفة، منها:
  • ألغى تطبيق العميل تسجيل نفسه من خدمة "المراسلة عبر السحابة الإلكترونية من Firebase".
  • تم إلغاء تسجيل تطبيق العميل تلقائيًا. ويمكن أن يحدث ذلك إذا ألغى المستخدم تثبيت التطبيق، أو إذا أبلغت "خدمة تعليقات APNs" عن أنّ الرمز المميّز لنقاط الوصول (APN) غير صالح.
  • انتهت صلاحية الرمز المميّز للتسجيل. على سبيل المثال، قد تقرر 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 لأنّ شهادة طبقة المقابس الآمنة (SSL) المطلوبة لحسابات APN لم يتم تحميلها أو انتهت صلاحيتها. تحقَّق من صلاحية شهادات التطوير والإنتاج الخاصة بك.
messaging/mismatched-credential لا تتضمّن بيانات الاعتماد المستخدَمة لمصادقة حزمة تطوير البرامج (SDK) هذه إذنًا لإرسال رسائل إلى الجهاز المتوافق مع الرمز المميّز للتسجيل الذي تم تقديمه. تأكَّد من أنّ بيانات الاعتماد والرمز المميّز للتسجيل ينتميان إلى مشروع Firebase نفسه. راجِع إضافة Firebase إلى تطبيقك للحصول على مستندات عن كيفية مصادقة حِزم SDK لمشرف Firebase.
messaging/authentication-error تعذّر على حزمة تطوير البرامج (SDK) المصادقة على خوادم خدمة "المراسلة عبر السحابة الإلكترونية من Firebase". تأكَّد من مصادقة حزمة تطوير البرامج (SDK) لمشرف Firebase باستخدام بيانات اعتماد لديها الأذونات المناسبة لإرسال رسائل "المراسلة عبر السحابة الإلكترونية من Firebase". راجِع إضافة Firebase إلى تطبيقك للحصول على مستندات عن كيفية مصادقة حِزم SDK لمشرف Firebase.
messaging/server-unavailable لم يتمكن خادم خدمة "المراسلة عبر السحابة الإلكترونية من Firebase" من معالجة الطلب في الوقت المناسب. عليك إعادة محاولة إرسال الطلب نفسه، ولكن عليك تنفيذ ما يلي:
  • عليك مراعاة عنوان Retry-After إذا كان مضمّنًا في الاستجابة من خادم اتصال FCM.
  • نفِّذ الرقود الأسي الثنائي في آلية إعادة المحاولة. على سبيل المثال، إذا انتظرت ثانية واحدة قبل إعادة المحاولة الأولى، انتظِر لمدة ثانيتين على الأقل قبل الثانية، ثم أربع ثوانٍ، وهكذا. في حال إرسال عدة رسائل، يمكنك تأخير كل رسالة على حدة بمقدار مبلغ عشوائي إضافي لتجنُّب إصدار طلب جديد لجميع الرسائل في الوقت نفسه.
يتعرض المرسلون الذين يسببون مشاكل إلى القائمة السوداء.
messaging/internal-error واجه خادم "المراسلة عبر السحابة الإلكترونية من Firebase" خطأً أثناء محاولة معالجة الطلب. يمكنك إعادة محاولة الطلب نفسه وفقًا للمتطلبات المذكورة في صف 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" يشبه إلى حد كبير إرسال رسائل إلى جهاز فردي أو إلى مجموعة مستخدمين. يضبط خادم التطبيق مفتاح to بقيمة، مثل /topics/yourTopic. يمكن للمطوّرين اختيار أي اسم موضوع يتطابق مع التعبير العادي: "/topics/[a-zA-Z0-9-_.~%]+".

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

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

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

  • الموضوع والموضوع (ب)
  • الموضوع والموضوع (ج)

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

طلب 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 ثانية قبل أن يعرض خادم "المراسلة عبر السحابة الإلكترونية من Firebase" استجابة ناجحة أو تعذُّر لطلبات إرسال الموضوع. تأكّد من ضبط قيمة مهلة خادم التطبيق في الطلب وفقًا لذلك.

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

إنّ إرسال الرسائل إلى مجموعة أجهزة باستخدام واجهات برمجة التطبيقات القديمة المتوقّفة يشبه إلى حد كبير إرسال الرسائل إلى جهاز فردي. يمكنك ضبط المعلَمة 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، من المفترض أن يعيد خادم التطبيق المحاولة مرة أخرى مع إجراء تراجع بين عمليات إعادة المحاولة.

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

{
  "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"
  ]
}

تحدث هذه المشكلة عند تعذُّر تسليم خادم اتصال "المراسلة عبر السحابة الإلكترونية من Firebase" إلى جميع الأجهزة في المجموعة. سيتلقى خادم التطبيق استجابة nack.

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

طرق الإرسال القديمة لحزمة تطوير البرامج (SDK) لمشرف Firebase

تتوافق حزمة Node.js SDK للمشرف في Firebase مع طرق إرسال الرسائل (FCM) استنادًا إلى واجهة برمجة تطبيقات خادم 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 يحتوي على الاستجابة من "المراسلة عبر السحابة الإلكترونية من Firebase". نوع الإرجاع له نفس التنسيق عند تمرير رمز مميز واحد للتسجيل أو مصفوفة من الرموز المميزة للتسجيل.

تتسبب بعض الحالات، مثل خطأ في المصادقة أو الحد من المعدل، في تعذُّر معالجة الرسالة بأكملها. وفي هذه الحالات، يتم رفض الوعد الذي يعرضه sendToDevice() مع عرض خطأ. للحصول على قائمة كاملة برموز الأخطاء، بما في ذلك الأوصاف وخطوات الحلّ، يُرجى الاطّلاع على أخطاء المشرف في واجهة برمجة التطبيقات 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 يحتوي على الاستجابة من "المراسلة عبر السحابة الإلكترونية من Firebase".

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

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

تقبل الطرق أعلاه المستندة إلى بروتوكولات "المراسلة عبر السحابة الإلكترونية من Firebase" القديمة حمولة الرسالة كوسيطة ثانية وتتوافق مع رسائل الإشعارات والبيانات. يمكنك تحديد نوع واحد من الرسائل أو كليهما من خلال إنشاء كائن باستخدام مفتاحَي 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 للحصول على قائمة كاملة بالقيود.

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

تقبل الطرق أعلاه المستندة إلى بروتوكولات "المراسلة عبر السحابة الإلكترونية من Firebase" القديمة وسيطة ثالثة اختيارية تحدد بعض الخيارات للرسالة. على سبيل المثال، يرسل المثال التالي رسالة ذات أولوية عالية إلى أحد الأجهزة التي تنتهي صلاحيتها بعد 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 للحصول على قائمة كاملة بالخيارات المتاحة.