Catch up on highlights from Firebase at Google I/O 2023. Learn more

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

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

  • اسم الموضوع
  • حالة
  • رمز تسجيل الجهاز
  • اسم مجموعة الأجهزة (البروتوكولات القديمة و Firebase Admin SDK لـ Node.js فقط)

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

توضح الأمثلة في هذه الصفحة كيفية إرسال رسائل التنبيه باستخدام 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:

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

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

تسمح لك REST API و Admin FCM APIs بإرسال رسالة متعددة إلى قائمة الرموز المميزة لتسجيل الجهاز. يمكنك تحديد ما يصل إلى 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.SendMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

استراحة

إنشاء طلب دفعي HTTP:

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

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

...

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message!"
     }
  }
}
--subrequest_boundary--

احفظ الطلب في ملف (في هذا المثال batch_request.txt). ثم استخدم الأمر cURL:

curl --data-binary @batch_request.txt -H 'Content-Type: multipart/mixed; boundary="subrequest_boundary"' -H 'Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA' https://fcm.googleapis.com/batch

بالنسبة إلى حزم SDK لمشرف Firebase ، تستخدم هذه العملية واجهة برمجة تطبيقات sendAll() تحت الغطاء ، كما هو موضح في الأمثلة. القيمة المرجعة هي BatchResponse والتي تتوافق قائمة إجاباتها مع ترتيب الرموز المميزة للإدخال. يكون هذا مفيدًا عندما تريد التحقق من الرموز المميزة التي أدت إلى حدوث أخطاء.

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

استراحة

كل إرسال فرعي يُرجع ردًا. يتم فصل الردود بسلسلة حدود استجابة تبدأ بـ --batch_ .

--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q
Content-Type: application/http
Content-ID: response-

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Vary: Origin
Vary: X-Origin
Vary: Referer

{
  "name": "projects/35006771263/messages/0:1570471792141125%43c11b7043c11b70"
}

...

--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q
Content-Type: application/http
Content-ID: response-

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Vary: Origin
Vary: X-Origin
Vary: Referer

{
  "name": "projects/35006771263/messages/0:1570471792141696%43c11b7043c11b70"
}

--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q--

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

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

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:

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

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

تدعم REST API و Admin SDKs إرسال الرسائل على دفعات. يمكنك تجميع ما يصل إلى 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');
  });

جافا

// 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.SendAllAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

استراحة

أنشئ طلبًا مجمّعًا لـ HTTP من خلال الجمع بين قائمة الطلبات الفرعية:

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

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

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "topic":"readers-club",
     "notification":{
       "title":"Price drop",
       "body":"2% off all books"
     }
  }
}

...

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message to device N!"
     }
  }
}
--subrequest_boundary--

يمكنك الاستعلام عن BatchResponse الذي تم إرجاعه للتحقق من عدد الرسائل التي تم تسليمها إلى FCM بنجاح. كما يعرض قائمة الردود التي يمكن استخدامها للتحقق من حالة الرسائل الفردية. ترتيب الردود يتوافق مع ترتيب الرسائل في قائمة الإدخال.

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

رموز خطأ المسؤول

يسرد الجدول التالي رموز خطأ 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 Feedback Service أن رمز APNs غير صالح.
  • انتهت صلاحية رمز التسجيل. على سبيل المثال ، قد تقرر Google تحديث الرموز المميزة للتسجيل أو ربما انتهت صلاحية رمز APNs لأجهزة 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 APNs المطلوبة أو انتهاء صلاحيتها. تحقق من صلاحية شهادات التطوير والإنتاج الخاصة بك.
messaging/mismatched-credential لا تمتلك بيانات الاعتماد المستخدمة لمصادقة SDK إذنًا لإرسال رسائل إلى الجهاز المطابق لرمز التسجيل المميز المقدم. تأكد من أن بيانات الاعتماد والرمز المميز للتسجيل ينتميان إلى مشروع Firebase نفسه. راجع إضافة Firebase إلى تطبيقك للحصول على وثائق حول كيفية مصادقة حزم SDK لمشرف Firebase.
messaging/authentication-error تعذر على SDK المصادقة على خوادم FCM. تأكد من مصادقة Firebase Admin SDK باستخدام بيانات اعتماد لديها الأذونات المناسبة لإرسال رسائل FCM. راجع إضافة Firebase إلى تطبيقك للحصول على وثائق حول كيفية مصادقة حزم SDK لمشرف Firebase.
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 لا يتلقى الرسالة. هذه المجموعات تحصل عليها:

  • الموضوع أ والموضوع ب
  • الموضوع أ والموضوع ج

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

طلب موضوع 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 رموز مميزة للتسجيل مرتبطة به. تم إرسال الرسالة بنجاح إلى 1 من الرموز المميزة للتسجيل فقط. تسرد رسالة الرد رموز التسجيل ( 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.

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

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

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

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

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

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

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

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

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

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

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

يمكنك استخدام الرسائل الجماعية للأجهزة عبر بروتوكولات XMPP أو HTTP القديمة على خادم التطبيق الخاص بك. تستند الإصدارات الأقدم من Firebase Admin SDK لـ Node.js إلى البروتوكولات القديمة وتوفر أيضًا إمكانيات المراسلة لمجموعة الأجهزة. الحد الأقصى لعدد الأعضاء المسموح به لمفتاح الإعلام هو 20.

يمكنك إنشاء مجموعات أجهزة وإنشاء مفاتيح إعلام عبر خادم تطبيقات أو عميل Android. انظر إدارة مجموعات الأجهزة للحصول على التفاصيل.

تتيح لك طريقة 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 .

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

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