了解 2023 年 Google I/O 大会上介绍的 Firebase 亮点。了解详情

Uygulama sunucusu oluşturma istekleri gönderme

Firebase Admin SDK veya FCM uygulama sunucusu protokollerini kullanarak mesaj istekleri oluşturabilir ve bunları şu tür hedeflere gönderebilirsiniz:

  • Konu adı
  • Durum
  • Cihaz kayıt jetonu
  • Cihaz grubu adı (yalnızca Node.js için eski protokoller ve Firebase Admin SDK)

Önceden tanımlanmış alanlardan oluşan bir bildirim yükü, kendi kullanıcı tanımlı alanlarınızın bir veri yükü veya her iki tür veriyi içeren bir mesaj ile mesajlar gönderebilirsiniz. Daha fazla bilgi için Mesaj türleri konusuna bakın.

Bu sayfadaki örnekler, Firebase Admin SDK ( Node , Java , Python , C# ve Go desteğine sahiptir) ve v1 HTTP protokolünü kullanarak bildirim mesajlarının nasıl gönderileceğini gösterir. Ayrıca , eski HTTP ve XMPP protokolleri aracılığıyla mesaj göndermeye yönelik kılavuz da bulunmaktadır.

Belirli cihazlara mesaj gönder

Belirli bir tek cihaza göndermek için, cihazın kayıt jetonunu gösterildiği gibi iletin. Kayıt belirteçleri hakkında daha fazla bilgi edinmek için platformunuzun istemci kurulum bilgilerine bakın.

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

Piton

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

Gitmek

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

DİNLENMEK

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

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

Başarı durumunda, her gönderme yöntemi bir ileti kimliği döndürür. Firebase Yönetici SDK'sı, kimlik dizesini projects/{project_id}/messages/{message_id} biçiminde döndürür. HTTP protokolü yanıtı, tek bir JSON anahtarıdır:

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

Birden fazla cihaza mesaj gönderin

REST API ve Yönetici FCM API'leri, bir mesajı cihaz kayıt belirteçleri listesine çok noktaya yayın yapmanıza olanak tanır. Çağırma başına en fazla 500 cihaz kayıt belirteci belirleyebilirsiniz.

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

Piton

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

Gitmek

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

DİNLENMEK

Bir HTTP toplu isteği oluşturun:

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

İsteği bir dosyaya kaydedin (bu örnekte batch_request.txt). Ardından cURL komutunu kullanın:

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

Firebase Admin SDK'ları için bu işlem, örneklerde gösterildiği gibi, arka planda sendAll() API'sini kullanır. Dönüş değeri, yanıt listesi giriş belirteçlerinin sırasına karşılık gelen bir BatchResponse . Bu, hangi belirteçlerin hatayla sonuçlandığını kontrol etmek istediğinizde kullanışlıdır.

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

Piton

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

Gitmek

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

DİNLENMEK

Her gönderme alt gönderimi bir yanıt döndürür. Yanıtlar, --batch_ ile başlayan bir yanıt sınır dizisiyle ayrılır.

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

Konulara mesaj gönder

İstemci uygulama örneklerini konuya istemci tarafında abone olarak veya sunucu API'si aracılığıyla bir konu oluşturduktan sonra konuya mesaj gönderebilirsiniz. FCM için ilk kez gönderme istekleri oluşturuyorsanız, önemli arka plan ve kurulum bilgileri için sunucu ortamınıza ve FCM'ye ilişkin kılavuza bakın.

Arka uçtaki gönderme mantığınızda, istediğiniz konu adını gösterildiği gibi belirtin:

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

Piton

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

Gitmek

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

DİNLENMEK

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

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

Bir konu kombinasyonuna mesaj göndermek için, hedef konuları belirten bir mantıksal ifade olan bir koşul belirtin. Örneğin, aşağıdaki koşul, TopicA ve TopicB veya TopicC abone olan cihazlara mesaj gönderir:

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

FCM önce herhangi bir koşulu parantez içinde değerlendirir ve ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya üye olan kullanıcı mesajı almamaktadır. Aynı şekilde TopicA abone olmayan bir kullanıcı mesajı almaz. Bu kombinasyonlar bunu alır:

  • TopicA ve TopicB
  • TopicA ve TopicC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz.

Bir koşula göndermek için:

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

Piton

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

Gitmek

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

DİNLENMEK

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

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

Toplu mesaj gönder

REST API ve Yönetici SDK'ları, mesajların toplu olarak gönderilmesini destekler. 500 adede kadar mesajı tek bir grupta gruplandırabilir ve hepsini tek bir API çağrısında gönderebilirsiniz; her mesaj için ayrı HTTP istekleri göndermeye kıyasla önemli performans artışı elde edersiniz.

Bu özellik, özelleştirilmiş bir mesaj seti oluşturmak ve bunları konular veya belirli cihaz kayıt belirteçleri dahil olmak üzere farklı alıcılara göndermek için kullanılabilir. Örneğin, mesaj gövdesinde biraz farklı ayrıntılarla farklı hedef kitlelere aynı anda mesaj göndermeniz gerektiğinde bu özelliği kullanın.

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

Piton

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

Gitmek

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

DİNLENMEK

Bir alt istekler listesini birleştirerek bir HTTP toplu isteği oluşturun:

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

Kaç iletinin FCM'ye başarıyla teslim edildiğini kontrol etmek için döndürülen BatchResponse sorgulayabilirsiniz. Ayrıca, bireysel mesajların durumunu kontrol etmek için kullanılabilecek yanıtların bir listesini de gösterir. Yanıtların sırası, giriş listesindeki mesajların sırasına karşılık gelir.

Doğrudan önyükleme özellikli mesajlar gönderin (yalnızca Android)

HTTP v1 veya eski HTTP API'lerini kullanarak doğrudan önyükleme modundaki cihazlara mesaj gönderebilirsiniz. Aygıtlara doğrudan önyükleme modunda göndermeden önce, istemci aygıtların doğrudan önyükleme modunda FCM mesajlarını almasını sağlamak için gereken adımları tamamladığınızdan emin olun.

FCM v1 HTTP API kullanarak gönder

Mesaj isteği, istek gövdesinin AndroidConfig seçeneklerinde "direct_boot_ok" : true anahtarını içermelidir. Örneğin:

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

FCM eski HTTP API'sini kullanarak gönderin

Mesaj isteği, istek gövdesinin en üst düzeyinde "direct_boot_ok" : true anahtarını içermelidir. Örneğin:

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
}

İstek gövdesinde bu anahtarla gönderilen mesajlar, şu anda doğrudan önyükleme modunda (ve bu modda değilken) aygıtlardaki uygulamalar tarafından işlenebilir.

Mesajları platformlar arasında özelleştirin

Hem Firebase Admin SDK hem de FCM v1 HTTP protokolü, mesaj isteklerinizin message nesnesinde bulunan tüm alanları ayarlamasına izin verir. Bu içerir:

  • mesajı alan tüm uygulama örnekleri tarafından yorumlanacak ortak bir alan kümesi.
  • AndroidConfig ve WebpushConfig gibi platforma özgü alan kümeleri, yalnızca belirtilen platformda çalışan uygulama örnekleri tarafından yorumlanır.

Platforma özgü bloklar, mesajların alındığında doğru bir şekilde ele alınmasını sağlamak için farklı platformlar için özelleştirme esnekliği sağlar. FCM arka ucu, belirtilen tüm parametreleri hesaba katacak ve mesajı her platform için özelleştirecektir.

Ortak alanlar ne zaman kullanılır?

Aşağıdaki durumlarda ortak alanları kullanın:

  • Apple, Android ve web gibi tüm platformlarda uygulama örneklerini hedefleme
  • Konulara mesaj gönderme

Platformdan bağımsız olarak tüm uygulama örnekleri aşağıdaki ortak alanları yorumlayabilir:

Platforma özgü alanlar ne zaman kullanılır?

Aşağıdakileri yapmak istediğinizde platforma özel alanları kullanın:

  • Alanları yalnızca belirli platformlara gönder
  • Ortak alanlara ek olarak platforma özel alanlar gönderin

Yalnızca belirli platformlara değer göndermek istediğinizde ortak alanlar kullanmayın ; platforma özgü alanları kullanın. Örneğin, yalnızca Apple platformlarına ve web'e bildirim göndermek, ancak Android'e göndermek için, biri Apple ve diğeri web için olmak üzere iki ayrı alan grubu kullanmanız gerekir.

Belirli teslim seçeneklerine sahip iletiler gönderirken, bunları ayarlamak için platforma özel alanları kullanın. İsterseniz platform başına farklı değerler belirleyebilirsiniz. Ancak, temelde aynı değeri platformlar arasında ayarlamak istediğinizde bile, platforma özel alanları kullanmanız gerekir. Bunun nedeni, her platformun değeri biraz farklı yorumlayabilmesidir; örneğin, Android'de yaşam süresi saniye cinsinden bir son kullanma süresi olarak ayarlanırken, Apple'da bir son kullanma tarihi olarak ayarlanır .

Örnek: renk ve simge seçenekleriyle bildirim mesajı

Bu örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı ve içeriği gönderir, ancak aynı zamanda Android cihazlara platforma özgü bazı geçersiz kılmalar gönderir.

Android için istek, Android cihazlarda görüntülenecek özel bir simge ve renk belirler. AndroidNotification referansında belirtildiği gibi, renk #rrggbb biçiminde belirtilir ve görüntü, Android uygulamasında yerel olarak çizilebilir bir simge kaynağı olmalıdır.

Aşağıda, bir kullanıcının cihazındaki görsel efektin bir tahmini verilmiştir:

Biri özel simge ve renk gösteren iki cihazın basit çizimi

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

Piton

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',
)

Gitmek

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

DİNLENMEK

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

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Örnek: özel resimli bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir, ancak aynı zamanda bir görüntü de gönderir. Aşağıda, bir kullanıcının cihazındaki görsel efektin bir tahmini verilmiştir:

Bir görüntü bildiriminde bir görüntünün basit çizimi

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

DİNLENMEK

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

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Örnek: ilişkili bir tıklama eylemiyle bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir, ancak aynı zamanda kullanıcının bildirimle etkileşime girmesine yanıt olarak uygulamanın gerçekleştirmesi için bir eylem gönderir. Aşağıda, bir kullanıcının cihazındaki görsel efektin bir tahmini verilmiştir:

Bir web sayfasını açan bir kullanıcının basit çizimi

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

DİNLENMEK

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

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Örnek: yerelleştirme seçenekleri içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, istemcinin yerelleştirilmiş mesajları görüntülemesi için yerelleştirme seçeneklerini gönderir. Aşağıda, bir kullanıcının cihazındaki görsel efektin bir tahmini verilmiştir:

İngilizce ve İspanyolca metin görüntüleyen iki cihazın basit çizimi

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

DİNLENMEK

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

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Yönetici hata kodları

Aşağıdaki tablo, önerilen çözüm adımları da dahil olmak üzere Firebase Admin FCM API hata kodlarını ve açıklamalarını listeler.

Hata kodu Açıklama ve Çözüm Adımları
messaging/invalid-argument Bir FCM yöntemine geçersiz bir bağımsız değişken sağlandı. Hata mesajı ek bilgi içermelidir.
messaging/invalid-recipient Amaçlanan mesaj alıcısı geçersiz. Hata mesajı ek bilgi içermelidir.
messaging/invalid-payload Geçersiz bir mesaj yükü nesnesi sağlandı. Hata mesajı ek bilgi içermelidir.
messaging/invalid-data-payload-key Veri mesajı yükü, geçersiz bir anahtar içeriyor. Kısıtlanmış anahtarlar için DataMessagePayload başvuru belgelerine bakın.
messaging/payload-size-limit-exceeded Sağlanan mesaj yükü, FCM boyut sınırlarını aşıyor. Çoğu mesaj için sınır 4096 bayttır. Konulara gönderilen mesajlar için sınır 2048 bayttır. Toplam yük boyutu, hem anahtarları hem de değerleri içerir.
messaging/invalid-options Geçersiz bir mesaj seçenekleri nesnesi sağlandı. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-registration-token Geçersiz kayıt belirteci sağlandı. İstemci uygulamasının FCM'ye kaydolurken aldığı kayıt belirteciyle eşleştiğinden emin olun. Kesmeyin veya ek karakterler eklemeyin.
messaging/registration-token-not-registered Sağlanan kayıt belirteci kayıtlı değil. Daha önce geçerli olan bir kayıt jetonunun kaydı, aşağıdakiler de dahil olmak üzere çeşitli nedenlerle iptal edilebilir:
  • İstemci uygulaması, FCM'den kendi kaydını iptal etti.
  • İstemci uygulamasının kaydı otomatik olarak iptal edildi. Bu, kullanıcı uygulamayı kaldırırsa veya Apple platformlarında APNs Geri Bildirim Hizmeti, APNs belirtecini geçersiz olarak bildirirse meydana gelebilir.
  • Kayıt belirtecinin süresi doldu. Örneğin Google, kayıt jetonlarını yenilemeye karar verebilir veya Apple cihazları için APNs jetonunun süresi dolmuş olabilir.
  • İstemci uygulaması güncellendi, ancak yeni sürüm mesaj alacak şekilde yapılandırılmadı.
Tüm bu durumlarda, bu kayıt jetonunu kaldırın ve mesaj göndermek için kullanmayı bırakın.
messaging/invalid-package-name İleti, paket adı sağlanan restrictedPackageName seçeneğiyle eşleşmeyen bir kayıt belirtecine gönderilmiş.
messaging/message-rate-exceeded Belirli bir hedefe gönderilen mesajların oranı çok yüksek. Bu cihaza veya konuya gönderilen mesaj sayısını azaltın ve bu hedefe göndermeyi hemen yeniden denemeyin.
messaging/device-message-rate-exceeded Belirli bir cihaza gönderilen mesajların oranı çok yüksek. Bu cihaza gönderilen mesaj sayısını azaltın ve bu cihaza göndermeyi hemen yeniden denemeyin.
messaging/topics-message-rate-exceeded Belirli bir konuya abone olan mesajların oranı çok yüksektir. Bu konu için gönderilen mesaj sayısını azaltın ve bu konuya hemen tekrar göndermeye çalışmayın.
messaging/too-many-topics Bir kayıt belirteci, maksimum sayıda konuya abone oldu ve artık abone olamaz.
messaging/invalid-apns-credentials Gerekli APNs SSL sertifikası yüklenmediğinden veya süresi dolduğundan, bir Apple cihazını hedefleyen bir mesaj gönderilemedi. Geliştirme ve üretim sertifikalarınızın geçerliliğini kontrol edin.
messaging/mismatched-credential Bu SDK'nın kimliğini doğrulamak için kullanılan kimlik bilgisi, sağlanan kayıt belirtecine karşılık gelen cihaza mesaj gönderme iznine sahip değil. Kimlik bilgisi ve kayıt belirtecinin aynı Firebase projesine ait olduğundan emin olun. Firebase Admin SDK'larının kimliğinin nasıl doğrulanacağına ilişkin belgeler için Uygulamanıza Firebase ekleme bölümüne bakın.
messaging/authentication-error SDK, FCM sunucularında kimlik doğrulaması yapamadı. Firebase Admin SDK'sının kimliğini, FCM mesajlarını göndermek için uygun izinlere sahip bir kimlik bilgisi ile doğruladığınızdan emin olun. Firebase Admin SDK'larının kimliğinin nasıl doğrulanacağına ilişkin belgeler için Uygulamanıza Firebase ekleme bölümüne bakın.
messaging/server-unavailable FCM sunucusu, isteği zamanında işleyemedi. Aynı isteği yeniden denemelisiniz, ancak şunları yapmalısınız:
  • FCM Bağlantı Sunucusundan gelen yanıta dahil edilmişse, Retry-After başlığını dikkate alın.
  • Yeniden deneme mekanizmanızda üstel geri çekilme uygulayın. Örneğin, ilk yeniden denemeden önce bir saniye beklediyseniz, sonraki denemeden önce en az iki saniye, ardından dört saniye vb. Birden fazla mesaj gönderiyorsanız, aynı anda tüm mesajlar için yeni bir istek yayınlamaktan kaçınmak için her birini bağımsız olarak ek bir rasgele miktarda geciktirin.
Sorun yaratan gönderenler kara listeye alınma riskiyle karşı karşıyadır.
messaging/internal-error FCM sunucusu, isteği işlemeye çalışırken bir hatayla karşılaştı. Yukarıdaki messaging/server-unavailable satırında listelenen gereksinimleri izleyerek aynı isteği yeniden deneyebilirsiniz. Hata devam ederse, lütfen sorunu Hata Raporu destek kanalımıza bildirin.
messaging/unknown-error Bilinmeyen bir sunucu hatası döndürüldü. Daha fazla ayrıntı için hata mesajındaki ham sunucu yanıtına bakın. Bu hatayı alırsanız, lütfen hata mesajının tamamını Hata Raporu destek kanalımıza bildirin.

Eski uygulama sunucusu protokollerini kullanarak mesaj gönderin

Eski protokolleri kullanmayı tercih ederseniz, bu bölümde gösterildiği gibi mesaj istekleri oluşturun. HTTP aracılığıyla birden fazla platforma gönderim yapıyorsanız, v1 protokolünün mesaj isteklerinizi basitleştirebileceğini unutmayın.

Belirli cihazlara mesaj gönder

Belirli cihazlara mesaj göndermek için, belirli uygulama örneğinin kayıt belirtecine to tuşunu ayarlayın. Kayıt belirteçleri hakkında daha fazla bilgi edinmek için platformunuzun istemci kurulum bilgilerine bakın.

HTTP POST isteği

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 yanıtı

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

XMPP mesajı

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

XMPP yanıtı

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

XMPP bağlantı sunucusu, yanıtlar için bazı başka seçenekler sunar. Bkz . Sunucu yanıt biçimi .

İstemci uygulamalarına aşağı akış mesajları gönderirken kullanılabilen mesaj seçeneklerinin tam listesi için, seçtiğiniz bağlantı sunucusu protokolünün ( HTTP veya XMPP) referans bilgilerine bakın.

Konulara mesaj gönder

Bir Firebase Bulut Mesajlaşma konusuna mesaj göndermek, tek bir cihaza veya bir kullanıcı grubuna mesaj göndermeye çok benzer. Uygulama sunucusu, to anahtarını /topics/yourTopic gibi bir değerle ayarlar. Geliştiriciler şu normal ifadeyle eşleşen herhangi bir konu adı seçebilir: "/topics/[a-zA-Z0-9-_.~%]+" .

Birden çok konunun kombinasyonlarına göndermek için uygulama sunucusunun condition anahtarını ( to anahtarı yerine) hedef konuları belirten bir boole koşuluna ayarlaması gerekir. Örneğin, TopicA ve TopicB veya TopicC abone olan cihazlara mesaj göndermek için:

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

FCM önce herhangi bir koşulu parantez içinde değerlendirir ve ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya üye olan kullanıcı mesajı almamaktadır. Aynı şekilde TopicA'ya abone olmayan bir kullanıcı mesajı almaz. Bu kombinasyonlar bunu alır:

  • KonuA ve KonuB
  • KonuA ve KonuC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz ve parantezler desteklenir. Desteklenen operatörler: && , || .

Konu HTTP POST isteği

Tek bir konuya gönder:

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


"Köpekler" veya "kediler" konularına abone olan cihazlara gönderin:

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


Konu HTTP yanıtı

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

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

Konu XMPP mesajı

Tek bir konuya gönder:

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


  </gcm>
</message>

"Köpekler" veya "kediler" konularına abone olan cihazlara gönderin:

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


  </gcm>
</message>

Konu XMPP yanıtı

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

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

FCM Sunucusu, konu gönderme isteklerine başarılı veya başarısız bir yanıt vermeden önce 30 saniyeye kadar bir gecikme bekleyin. İstekte uygulama sunucusunun zaman aşımı değerini uygun şekilde ayarladığınızdan emin olun.

Cihaz gruplarına mesaj gönder

Bir cihaz grubuna mesaj göndermek, tek bir cihaza mesaj göndermeye çok benzer. to parametresini cihaz grubu için benzersiz bildirim anahtarına ayarlayın. Yük desteğiyle ilgili ayrıntılar için Mesaj türlerine bakın. Bu sayfadaki örnekler, veri mesajlarının eski HTTP ve XMPP protokollerindeki cihaz gruplarına nasıl gönderileceğini gösterir.

Cihaz Grubu HTTP POST Talebi

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

Cihaz Grubu HTTP Yanıtı

İşte bir "başarı" örneği: notification_key kendisiyle ilişkilendirilmiş 2 kayıt belirteci vardır ve mesaj her ikisine de başarıyla gönderilmiştir:

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

İşte bir "kısmi başarı" örneği - notification_key kendisiyle ilişkilendirilmiş 3 kayıt belirteci vardır. Mesaj başarıyla yalnızca 1 kayıt jetonuna gönderildi. Yanıt mesajı, mesajı alamayan kayıt belirteçlerini ( registration_ids ) listeler:

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

Bir notification_key ile ilişkili bir veya daha fazla kayıt jetonuna bir mesaj teslim edilemediğinde, uygulama sunucusu yeniden denemeler arasında geri çekilme ile yeniden denemelidir.

Sunucu, üyesi olmayan bir cihaz grubuna mesaj göndermeye çalışırsa, yanıt 0 başarı ve 0 başarısızlıkla aşağıdaki gibi görünür:

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

Cihaz Grubu XMPP Mesajı

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

Cihaz Grubu XMPP Yanıtı

Mesaj, gruptaki cihazlardan herhangi birine başarıyla gönderildiğinde, XMPP bağlantı sunucusu bir ACK ile yanıt verir. Gruptaki tüm cihazlara gönderilen tüm mesajlar başarısız olursa, XMPP bağlantı sunucusu bir NACK ile yanıt verir.

İşte bir "başarı" örneği: notification_key kendisiyle ilişkilendirilmiş 3 kayıt belirteci vardır ve mesaj bunların hepsine başarıyla gönderilmiştir:

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

İşte bir "kısmi başarı" örneği - notification_key kendisiyle ilişkilendirilmiş 3 kayıt belirteci vardır. Mesaj başarıyla yalnızca 1 kayıt jetonuna gönderildi. Yanıt mesajı, mesajı alamayan kayıt jetonlarını listeler:

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

FCM bağlantı sunucusu, gruptaki tüm cihazlara teslim edemediğinde. Uygulama sunucusu bir nack yanıtı alacaktır.

Mesaj seçeneklerinin tam listesi için, seçtiğiniz bağlantı sunucusu protokolünün ( HTTP veya XMPP) referans bilgilerine bakın.

Firebase Admin SDK eski gönderme yöntemleri

Firebase Admin Node.js SDK'sı, Eski FCM sunucusu API'sine dayalı mesaj gönderme (FCM) yöntemlerini destekler. Bu yöntemler send() yöntemine kıyasla farklı bağımsız değişkenleri kabul eder. send() yöntemini mümkün olduğunca kullanmalı ve tek tek aygıtlara veya aygıt gruplarına mesaj gönderirken yalnızca bu sayfada açıklanan yöntemleri kullanmalısınız.

Bireysel cihazlara gönder

Bu cihaza bir mesaj göndermek için sendToDevice() yöntemine bir kayıt belirteci iletebilirsiniz:

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() yöntemi, yalnızca tek bir kayıt belirteci yerine bir dizi kayıt belirteci geçirerek çok noktaya yayın mesajı (yani, birden çok cihaza bir mesaj) gönderebilir:

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() yöntemi, FCM'den gelen yanıtı içeren bir MessagingDevicesResponse nesnesiyle çözümlenen bir söz döndürür. Dönüş türü, tek bir kayıt belirtecini veya bir kayıt belirteçleri dizisini geçirirken aynı biçime sahiptir.

Kimlik doğrulama hatası veya hız sınırlaması gibi bazı durumlar, mesajın tamamının işlenememesine neden olur. Bu durumlarda, sendToDevice() tarafından döndürülen söz bir hatayla reddedilir. Açıklamalar ve çözüm adımları da dahil olmak üzere hata kodlarının tam listesi için Yönetici FCM API Hataları bölümüne bakın.

Bir cihaz grubuna gönder

Cihaz grubu mesajlaşması, tek bir gruba birden fazla cihaz eklemenizi sağlar. Bu, konu mesajlaşmasına benzer, ancak grup üyeliğinin yalnızca sunucularınız tarafından yönetilmesini sağlamak için kimlik doğrulama içerir. Örneğin, farklı telefon modellerine farklı mesajlar göndermek istiyorsanız, sunucularınız uygun gruplara kayıt ekleyebilir/kaldırabilir ve her gruba uygun mesajı gönderebilir. Cihaz grubu mesajlaşması, cihaz gruplarını doğrudan uygulamanız yerine sunucularınızdan yönetmeyi içermesi bakımından konu mesajlaşmasından farklıdır.

Uygulama sunucunuzdaki eski XMPP veya HTTP protokolleri aracılığıyla cihaz grubu mesajlaşmasını kullanabilirsiniz. Firebase Admin SDK for Node.js'nin eski sürümleri, eski protokolleri temel alır ve ayrıca cihaz grubu mesajlaşma özellikleri sağlar. Bir bildirim anahtarı için izin verilen maksimum üye sayısı 20'dir.

Bir uygulama sunucusu veya bir Android istemcisi aracılığıyla cihaz grupları oluşturabilir ve bildirim anahtarları oluşturabilirsiniz. Ayrıntılar için Cihaz gruplarını yönetme bölümüne bakın.

sendToDeviceGroup() yöntemi, o aygıt grubu için bildirim anahtarını belirterek bir aygıt grubuna mesaj göndermenizi sağlar:

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() yöntemi, FCM'den gelen yanıtı içeren bir MessagingDevicesResponse nesnesiyle çözümlenen bir söz döndürür.

Kimlik doğrulama hatası veya hız sınırlaması gibi bazı durumlar, mesajın tamamının işlenememesine neden olur. Bu durumlarda, sendToDeviceGroup() tarafından döndürülen söz bir hatayla reddedilir. Açıklamalar ve çözüm adımları da dahil olmak üzere hata kodlarının tam listesi için Yönetici FCM API Hataları bölümüne bakın.

Mesaj yükünü tanımlama

FCM eski protokollerine dayanan yukarıdaki yöntemler, ikinci bağımsız değişkenleri olarak bir mesaj yükünü kabul eder ve hem bildirim hem de veri mesajlarını destekler. data ve/veya notification tuşları ile bir nesne oluşturarak mesaj türlerinden birini veya her ikisini belirtebilirsiniz. Örneğin, farklı türde mesaj yüklerini nasıl tanımlayacağınız aşağıda açıklanmıştır:

Bildirim mesajı

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.'
  }
};

Veri mesajı

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

Birleşik mesaj

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

Bildirim mesajı yükleri, önceden tanımlanmış bir geçerli özellik alt kümesine sahiptir ve hedeflediğiniz mobil işletim sistemine bağlı olarak biraz farklılık gösterir. Tam liste için NotificationMessagePayload referans belgelerine bakın.

Veri mesajı yükleri, tüm değerlerin dize olması gerektiği gerçeği de dahil olmak üzere birkaç kısıtlama ile özel anahtar/değer çiftlerinden oluşur. Kısıtlamaların tam listesi için DataMessagePayload referans belgelerine bakın.

Mesaj seçeneklerini tanımlama

FCM eski protokollerine dayalı yukarıdaki yöntemler, mesaj için bazı seçenekleri belirten isteğe bağlı bir üçüncü bağımsız değişkeni kabul eder. Örneğin, aşağıdaki örnek, bir cihaza 24 saat sonra süresi dolan yüksek öncelikli bir mesaj gönderir:

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

Mevcut seçeneklerin tam listesi için MessagingOptions referans belgelerine bakın.