Uygulama sunucusu gönderme istekleri oluşturma

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

  • Konu adı
  • Koşul
  • Cihaz kaydı jetonu
  • Cihaz grubu adı (yalnızca protokol)

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

Bu sayfadaki örneklerde Node, Java, Python, C# ve Go desteği sunan Firebase Admin SDK ve v1 HTTP protokolü kullanılarak bildirim mesajlarının nasıl gönderileceği gösterilmektedir. Ayrıca, kullanımdan kaldırılan eski HTTP ve XMPP protokolleri aracılığıyla mesaj gönderme hakkında bilgi verilmektedir.

Belirli cihazlara mesaj gönderme

Belirli bir cihaza göndermek için cihazın kayıt jetonunu gösterildiği gibi iletin. Kayıt jetonları hakkında daha fazla bilgi edinmek için platformunuzla ilgili istemci kurulum bilgilerini inceleyin.

Node.js

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

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

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

Java

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

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

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

Python

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

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

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

Go

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

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

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

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

C#

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

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

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

REST

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

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

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

cURL 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ılı olduğunda, her gönderme yöntemi bir ileti kimliği döndürür. Firebase Admin SDK, 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önderme

Yönetici FCM API'leri, bir mesajı cihaz kayıt jetonları listesine çoklu yayın yapmanıza olanak tanır. Çağrı başına en fazla 500 cihaz kaydı jetonu belirtebilirsiniz.

Node.js

// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // …
  'YOUR_REGISTRATION_TOKEN_N',
];

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

getMessaging().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

Java

// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

MulticastMessage message = MulticastMessage.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .addAllTokens(registrationTokens)
    .build();
BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");

Python

# Create a list containing up to 500 registration tokens.
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_N',
]

message = messaging.MulticastMessage(
    data={'score': '850', 'time': '2:45'},
    tokens=registration_tokens,
)
response = messaging.send_multicast(message)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))

Go

// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Tokens: registrationTokens,
}

br, err := client.SendMulticast(context.Background(), message)
if err != nil {
	log.Fatalln(err)
}

// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)

C#

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

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

Döndürülen değer, giriş jetonlarının sırasına karşılık gelen jeton listesidir. Bu, hangi jetonların hataya yol açtığını kontrol etmek istediğinizde yararlı olur.

Node.js

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

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

getMessaging().sendMulticast(message)
  .then((response) => {
    if (response.failureCount > 0) {
      const failedTokens = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success) {
          failedTokens.push(registrationTokens[idx]);
        }
      });
      console.log('List of tokens that caused failures: ' + failedTokens);
    }
  });

Java

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

MulticastMessage message = MulticastMessage.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .addAllTokens(registrationTokens)
    .build();
BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
if (response.getFailureCount() > 0) {
  List<SendResponse> responses = response.getResponses();
  List<String> failedTokens = new ArrayList<>();
  for (int i = 0; i < responses.size(); i++) {
    if (!responses.get(i).isSuccessful()) {
      // The order of responses corresponds to the order of the registration tokens.
      failedTokens.add(registrationTokens.get(i));
    }
  }

  System.out.println("List of tokens that caused failures: " + failedTokens);
}

Python

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

message = messaging.MulticastMessage(
    data={'score': '850', 'time': '2:45'},
    tokens=registration_tokens,
)
response = messaging.send_multicast(message)
if response.failure_count > 0:
    responses = response.responses
    failed_tokens = []
    for idx, resp in enumerate(responses):
        if not resp.success:
            # The order of responses corresponds to the order of the registration tokens.
            failed_tokens.append(registration_tokens[idx])
    print('List of tokens that caused failures: {0}'.format(failed_tokens))

Go

// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Tokens: registrationTokens,
}

br, err := client.SendMulticast(context.Background(), message)
if err != nil {
	log.Fatalln(err)
}

if br.FailureCount > 0 {
	var failedTokens []string
	for idx, resp := range br.Responses {
		if !resp.Success {
			// The order of responses corresponds to the order of the registration tokens.
			failedTokens = append(failedTokens, registrationTokens[idx])
		}
	}

	fmt.Printf("List of tokens that caused failures: %v\n", failedTokens)
}

C#

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

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

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

Konulara mesaj gönderin

Bir konu oluşturduktan sonra, istemci uygulaması örneklerini istemci tarafında konuya abone olarak veya sunucu API'si aracılığıyla ayarlayabilirsiniz. FCM için ilk kez gönderme isteği oluşturuyorsanız önemli arka plan ve kurulum bilgileri için sunucu ortamınız ve FCM'niz kılavuzuna 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);

Python

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

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

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

Go

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

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

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

C#

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

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

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

REST

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

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

cURL 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 bir koşul belirtin. Bu, hedef konuları belirten bir boole ifadesidir. Örneğin, aşağıdaki koşul TopicA ve TopicB ya da TopicC abonesi olan cihazlara mesaj gönderir:

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

FCM önce parantez içindeki tüm koşulları değerlendirir, ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede, herhangi bir konuya abone olan kullanıcı mesajı almaz. Benzer şekilde, TopicA abonesi olmayan bir kullanıcı da mesajı almaz. Şu 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);

Python

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

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

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

Go

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

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

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

C#

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

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

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

REST

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

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

cURL 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

Cihaz gruplarına mesaj gönderme

Cihaz gruplarına mesaj göndermek için HTTP v1 API'yi kullanın. Şu anda HTTP veya XMPP için kullanımdan kaldırılan eski gönderme API'lerini ya da eski protokollere bağlı olarak Node.js için Firebase Admin SDK'nın eski sürümlerinden birini kullanarak cihaz gruplarına gönderim yapıyorsanız en kısa sürede HTTP v1 API'ye geçmenizi kesinlikle öneririz. Eski gönderme API'leri Haziran 2024'te devre dışı bırakılacak ve kaldırılacaktır.

Bir cihaz grubuna mesaj gönderme, tek bir cihaza mesaj göndermeye çok benzer. Aynı gönderme isteklerini yetkilendirme yöntemini kullanır. token alanını grup bildirimi anahtarına ayarlayın:

REST

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

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

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

cURL komutu

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

İletileri toplu olarak gönderme

Yönetici SDK'ları iletilerin toplu olarak gönderilmesini destekler. 500'e kadar mesajı tek bir toplu grupta gruplandırabilir ve bunların tümünü tek bir API çağrısında gönderebilirsiniz. Her mesaj için ayrı HTTP istekleri gönderilmesine kıyasla önemli bir performans artışı sağlarsınız.

Bu özellik, özelleştirilmiş bir mesaj grubu oluşturmak ve bunları konular veya belirli cihaz kayıt jetonları gibi farklı alıcılara göndermek için kullanılabilir. Örneğin, ileti gövdesinde biraz farklı ayrıntılara sahip farklı 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");

Python

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

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

Go

// Create a list containing up to 500 messages.
messages := []*messaging.Message{
	{
		Notification: &messaging.Notification{
			Title: "Price drop",
			Body:  "5% off all electronics",
		},
		Token: registrationToken,
	},
	{
		Notification: &messaging.Notification{
			Title: "Price drop",
			Body:  "2% off all books",
		},
		Topic: "readers-club",
	},
}

br, err := client.SendAll(context.Background(), messages)
if err != nil {
	log.Fatalln(err)
}

// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)

C#

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

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

Doğrudan başlatma özelliğinin etkin olduğu iletiler gönderme (yalnızca Android)

HTTP v1 veya eski HTTP API'lerini kullanarak doğrudan başlatma modundaki cihazlara mesaj gönderebilirsiniz. Doğrudan başlatma modundaki cihazlara göndermeden önce, istemci cihazların doğrudan başlatma modunda FCM mesajlarını almasını etkinleştirmeye ilişkin adımları tamamladığınızdan emin olun.

FCM v1 HTTP API'yi kullanarak gönder

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

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

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

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, o anda doğrudan başlatma modunda olan (ve bu modda değilken) cihazlardaki uygulamalar tarafından işlenebilir.

Farklı platformlardaki mesajları özelleştirme

Hem Firebase Admin SDK hem FCM v1 HTTP protokolü, mesaj isteklerinizin message nesnesindeki tüm alanları ayarlamasına olanak tanır. Bunlardan bazıları:

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

Platforma özgü engellemeler, mesajları farklı platformlar için özelleştirme esnekliği sağlar. Böylece mesajların alındığında doğru bir şekilde ele alınırlar. FCM arka ucu, belirtilen tüm parametreleri dikkate alır ve mesajı her bir platform için özelleştirir.

Ortak alanlar ne zaman kullanılır?

Genel alanları şu durumlarda kullanabilirsiniz:

  • 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 özel alanlar ne zaman kullanılır?

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

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

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

Belirli teslimat seçeneklerine sahip iletiler gönderiyorsanız, bunları ayarlamak için platforma özel alanları kullanın. İsterseniz her platform için farklı değerler belirtebilirsiniz. Ancak, platformlar arasında temelde aynı değeri ayarlamak istediğinizde bile platforma özel alanları kullanmanız gerekir. Bunun nedeni, her platformun değeri biraz farklı yorumlayabilmesidir. Örneğin, geçerlilik süresi Android'de saniye cinsinden geçerlilik süresi, Apple'da ise geçerlilik bitiş tarihi olarak ayarlanır.

Örnek: renk ve simge seçenekleri olan bildirim mesajı

Bu örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı ve içerik gönderir. Bununla birlikte, Android cihazlara platforma özel bazı geçersiz kılmalar da gönderir.

Android için istek, Android cihazlarda görüntülenecek özel bir simge ve renk ayarlar. AndroidBildirim referansında belirtildiği gibi, renk #rrggbb biçiminde belirtilir ve resim, Android uygulamasına özgü bir çekilebilir simge kaynağı olmalıdır.

Kullanıcının cihazındaki görsel efektin yaklaşık bir örneğini aşağıda bulabilirsiniz:

Birinde özel bir simge ve renk gösterilen 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();

Python

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

Go

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

C#

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

REST

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

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

İleti gövdesinde platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerini inceleyin.

Örnek: özel resim içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir ancak resim de gönderir. Kullanıcının cihazı üzerindeki görsel etkinin bir tahmini şu şekildedir:

Ekran bildirimindeki bir resmin 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);
  });

REST

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

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

İleti gövdesinde platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerini inceleyin.

Örnek: ilişkili bir tıklama işlemi içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir ancak aynı zamanda uygulamanın bildirimle etkileşimde bulunan kullanıcıya yanıt olarak gerçekleştirmesi için bir işlem de gönderir. Kullanıcının cihazındaki görsel efektin yaklaşık bir örneğini aşağıda bulabilirsiniz:

Bir kullanıcının web sayfasını açmak için dokunduğu basit çizim

Node.js

const topicName = 'industry-tech';

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

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

REST

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

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

İleti gövdesinde platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerini inceleyin.

Örnek: Yerelleştirme seçenekleri olan bildirim mesajı

Aşağıdaki gönderme isteği örneği, yerelleştirilmiş mesajları görüntülemek için istemciye yerelleştirme seçenekleri gönderir. Kullanıcının cihazındaki görsel efektin yaklaşık bir örneğini aşağıda bulabilirsiniz:

İngilizce ve İspanyolca metnin gösterildiği 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);
  });

REST

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

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

İleti gövdesinde platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntılar için HTTP v1 referans belgelerini inceleyin.

HTTP v1 API için REST hata kodları

HTTP v1 API için HTTP hata yanıtları; hata kodu, hata mesajı ve hata durumu içerir. Hatayla ilgili daha fazla ayrıntı içeren bir details dizisi de içerebilirler.

Aşağıda iki hata yanıtı örneği verilmiştir:

1. Örnek: HTTP v1 API isteğinden alınan ve veri mesajında geçersiz bir değere sahip hata yanıtı

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

2. Örnek: Geçersiz kayıt jetonuna sahip HTTP v1 API isteğinden alınan hata yanıtı

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

Her iki mesajın da aynı kod ve duruma sahip olduğunu, ancak ayrıntılar dizisinin farklı türlerde değerler içerdiğini unutmayın. İlk örnekte, istek değerlerinde bir hata olduğunu gösteren type.googleapis.com/google.rpc.BadRequest türü bulunmaktadır. type.googleapis.com/google.firebase.fcm.v1.FcmError türündeki ikinci örnekte FCM'ye özgü bir hata var. Ayrıntılar dizisi, birçok hata için hata ayıklamak ve bir çözüm bulmak için ihtiyaç duyacağınız bilgileri içerir.

Aşağıdaki tabloda FCM v1 REST API hata kodları ve açıklamaları listelenmiştir.

Hata Kodu Açıklama ve Çözüm Adımları
UNSPECIFIED_ERROR Bu hata hakkında başka bilgi yok. Yok.
INVALID_ARGUMENT (HTTP hata kodu = 400) İstek parametreleri geçersizdi. Hangi alanın geçersiz olduğunu belirtmek için google.rpc.BadRequest türünde bir uzantı döndürülür. Olası nedenler arasında geçersiz kayıt, geçersiz paket adı, ileti çok büyük, geçersiz veri anahtarı, geçersiz TTL veya diğer geçersiz parametreler bulunur.
Geçersiz kayıt: Sunucuya ilettiğiniz kayıt jetonunun biçimini kontrol edin. Bu kodun, istemci uygulamasının FCM'ye kaydolma işleminden aldığı kayıt jetonuyla eşleştiğinden emin olun. Jetonu kırpmayın veya ek karakter eklemeyin.
Geçersiz paket adı: İletinin, paket adı istekte iletilen değerle eşleşen bir kayıt jetonuna yönlendirildiğinden emin olun.
İleti çok büyük: Bir iletiye dahil edilen yük verilerinin toplam boyutunun FCM sınırlarını aşmadığından emin olun: çoğu ileti için 4.096 bayt, konulara gönderilen iletilerde 2.048 bayt. Bu, hem anahtarları hem de değerleri içerir.
Geçersiz veri anahtarı: Yük verilerinde, FCM tarafından dahili olarak kullanılan bir anahtar (from, gcm ya da google ön ekine sahip herhangi bir değer gibi) bulunmadığından emin olun. FCM tarafından da bazı kelimelerin (örneğin collapse_key) kullanıldığını ancak yükte izin verildiğini unutmayın. Bu durumda yük değeri FCM değeri tarafından geçersiz kılınır.
Geçersiz TTL: ttl'da kullanılan değerin, 0 ile 2.419.200 (4 hafta) arasında saniye cinsinden bir süreyi temsil eden tam sayı olduğundan emin olun.
Geçersiz parametreler: Sağlanan parametrelerin doğru ada ve türe sahip olduğundan emin olun.
UNREGISTERED (HTTP hata kodu = 404) Uygulama örneğinin kaydı FCM'den kaldırıldı. Bu genellikle kullanılan jetonun artık geçerli olmadığı ve yeni bir jeton kullanılması gerektiği anlamına gelir. Bu hata, eksik kayıt jetonları veya kaydedilmemiş jetonlardan kaynaklanıyor olabilir.
Eksik Kayıt: İletinin hedefi bir token değeriyse isteğin kayıt jetonu içerip içermediğini kontrol edin.
Kayıtlı değil: Aşağıdakiler de dahil olmak üzere çeşitli senaryolarda mevcut bir kayıt jetonunun geçerliliği durdurulabilir:
- İstemci uygulamasının FCM'deki kaydı silinirse.
- İstemci uygulamasının kaydı otomatik olarak silinirse bu durum, kullanıcı uygulamanın yüklemesini kaldırırsa meydana gelebilir. Örneğin, iOS'te APNs Geri Bildirim Hizmeti APNs jetonunu geçersiz olarak bildirmiştir.
- Kayıt jetonunun süresi dolarsa (örneğin, Google kayıt jetonlarını yenilemeye karar verebilir veya iOS cihazlar için APNs jetonunun süresi dolmuş olabilir).
- İstemci uygulaması güncellenir, ancak yeni sürüm mesaj alacak şekilde yapılandırılmamışsa.
Tüm bu durumlarda, bu kayıt jetonunu uygulama sunucusundan kaldırın ve ileti göndermek için artık kullanmayın.
SENDER_ID_MISMATCH (HTTP hata kodu = 403) Kimliği doğrulanmış gönderen kimliği, kayıt jetonunun gönderen kimliğinden farklı. Kayıt jetonu, belirli bir gönderen grubuna bağlıdır. Bir istemci uygulaması FCM'ye kaydolduğunda, hangi gönderenlerin ileti göndermesine izin verildiğini belirtmesi gerekir. İstemci uygulamasına ileti gönderirken bu gönderen kimliklerinden birini kullanmalısınız. Farklı bir gönderene geçerseniz mevcut kayıt jetonları çalışmaz.
QUOTA_EXCEEDED (HTTP hata kodu = 429) İleti hedefi için gönderme sınırı aşıldı. Hangi kotanın aşıldığını belirtmek için google.rpc.QuotaFailure türünde bir uzantı döndürülür. Bu hata, ileti hızı kotasının veya cihaz ileti hızı kotasının aşılmasından ya da konu ileti hızı kotasının aşılmasından kaynaklanabilir.
İleti hızı aşıldı: İleti gönderme oranı çok yüksek. Toplam ileti gönderme hızınızı azaltmanız gerekir. Reddedilen iletileri yeniden denemek için minimum 1 dakikalık bir başlangıç gecikmesiyle eksponansiyel geri yükleme kullanın.
Cihaz mesaj hızı aşıldı: Belirli bir cihaza gönderilen mesaj oranı çok yüksek. Tek bir cihaza yönelik mesaj hızı sınırı başlıklı makaleyi inceleyin. Bu cihaza gönderilen ileti sayısını azaltın ve göndermeyi yeniden denemek için eksponansiyel geri yükleme kullanın.
Konu mesaj oranı aşıldı: Belirli bir konunun abonelerine gelen mesaj oranı çok yüksek. Bu konu için gönderilen mesaj sayısını azaltın ve göndermeyi yeniden denemek için en az 1 dakikalık bir başlangıç gecikmesiyle eksponansiyel geri yükleme kullanın.
UNAVAILABLE (HTTP hata kodu = 503) Sunucu aşırı yüklü. Sunucu isteği zamanında işleyemedi. Aynı isteği yeniden deneyin. Ancak şunları yapmanız gerekir:
- FCM Bağlantı Sunucusu'ndan gelen yanıtta yer alıyorsa Retry-After üstbilgisini dikkate alın.
- Yeniden deneme mekanizmanıza eksponansiyel geri yükleme uygulayın. (ör.ilk yeniden denemeden önce bir saniye beklediyseniz sonrakinden önce en az iki saniye, daha sonra 4 saniye bekleyin vb.). Birden çok mesaj gönderiyorsanız ses dalgalanması uygulamayı deneyin. Daha fazla bilgi için Yeniden denemeleri yönetme bölümüne bakın. Sorunlara neden olan gönderenler, reddedilenler listesine alınma riskiyle karşı karşıyadır.
INTERNAL (HTTP hata kodu = 500) Bilinmeyen dahili bir hata oluştu. Sunucu, isteği işlemeye çalışırken bir hatayla karşılaştı. Yeniden denemeleri yönetme bölümündeki önerileri izleyerek aynı isteği yeniden deneyebilirsiniz. Hata devam ederse lütfen Firebase destek ekibiyle iletişime geçin.
THIRD_PARTY_AUTH_ERROR (HTTP hata kodu = 401) APNs sertifikası veya web push kimlik doğrulama anahtarı geçersiz ya da eksikti. iOS cihaza hedeflenen bir mesaj veya web push kaydı gönderilemedi. Geliştirme ve üretim kimlik bilgilerinizin geçerliliğini kontrol edin.

Yönetici hata kodları

Aşağıdaki tabloda, Firebase Admin FCM API hata kodları ve önerilen çözüm adımlarıyla birlikte açıklamaları listelenmektedir.

Hata Kodu Açıklama ve Çözüm Adımları
messaging/invalid-argument Bir FCM yöntemine geçersiz bağımsız değişken sağlandı. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-recipient Hedeflenen ileti alıcısı geçersiz. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-payload Geçersiz bir mesaj yükü nesnesi sağlandı. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-data-payload-key Veri mesajı yükü geçersiz bir anahtar içeriyor. Kısıtlanmış anahtarlar için DataMessagePayload referans belgelerine bakın.
messaging/payload-size-limit-exceeded Sağlanan mesaj yükü FCM boyut sınırlarını aşıyor. Sınır çoğu mesaj için 4.096 bayttır. Konulara gönderilen mesajlar için sınır 2.048 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 jetonu sağlandı. Bu kodun, istemci uygulamasının FCM'ye kayıt yaptırarak aldığı kayıt jetonuyla eşleştiğinden emin olun. Metni kısaltmayın veya başka karakter eklemeyin.
messaging/registration-token-not-registered Sağlanan kayıt jetonu kayıtlı değil. Daha önce geçerli olan kayıt jetonunun kaydı, aşağıdakiler dahil çeşitli nedenlerle iptal edilebilir:
  • İstemci uygulamasının FCM kaydını iptal etti.
  • İstemci uygulamasının kaydı otomatik olarak iptal edildi. Bu durum, kullanıcı uygulamayı kaldırırsa veya Apple platformlarında APNs Geri Bildirim Hizmeti APNs jetonunu geçersiz olarak bildirmişse ortaya çıkabilir.
  • Kayıt jetonunun süresi doldu. Örneğin, Google kayıt jetonlarını yenilemeye karar verebilir veya Apple cihazlar için APN jetonunun süresi dolmuş olabilir.
  • İstemci uygulaması güncellendi ancak yeni sürüm mesaj alacak şekilde yapılandırılmamış.
Tüm bu durumlarda bu kayıt jetonunu kaldırın ve mesaj göndermek için artık kullanmayın.
messaging/invalid-package-name Mesaj, paket adı sağlanan restrictedPackageName seçeneğiyle eşleşmeyen bir kayıt jetonuna gönderildi.
messaging/message-rate-exceeded Belirli bir hedefe gönderilen iletilerin oranı çok yüksek. Bu cihaza veya konuya gönderilen mesajların sayısını azaltın ve bu hedefe göndermeyi hemen tekrar denemeyin.
messaging/device-message-rate-exceeded Belirli bir cihaza gönderilen iletilerin oranı çok yüksek. Bu cihaza gönderilen mesaj sayısını azaltın ve bu cihaza göndermeyi hemen tekrar denemeyin.
messaging/topics-message-rate-exceeded Belirli bir konuda abonelere gönderilen mesajların oranı çok yüksek. Bu konu için gönderilen mesajların sayısını azaltın ve bu konuya göndermeyi hemen tekrar denemeyin.
messaging/too-many-topics Bir kayıt jetonu maksimum sayıda konuya abone oldu ve artık artık abone olamaz.
messaging/invalid-apns-credentials Gerekli APNs SSL sertifikası yüklenmediğinden veya süresi dolduğundan Apple cihazına hedeflenen 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 bilgisinin, sağlanan kayıt jetonuna karşılık gelen cihaza mesaj gönderme izni yok. Kimlik bilgisi ve kayıt jetonunun aynı Firebase projesine ait olduğundan emin olun. Firebase Admin SDK'larının kimliğini doğrulama ile ilgili belgeler için Uygulamanıza Firebase'i ekleme bölümüne bakın.
messaging/authentication-error SDK, FCM sunucularının kimliğini doğrulayamadı. Firebase Admin SDK'nın kimliğini, FCM mesajları göndermek için uygun izinlere sahip bir kimlik bilgisi ile doğruladığınızdan emin olun. Firebase Admin SDK'larının kimliğini doğrulama ile ilgili belgeler için Uygulamanıza Firebase'i ekleme bölümüne bakın.
messaging/server-unavailable FCM sunucusu isteği zamanında işleyemedi. Aynı isteği yeniden denemeniz gerekir ancak şunları yapmanız gerekir:
  • FCM Connection Server'dan gelen yanıta dahil edilmişse Retry-After üst bilgisini dikkate alın.
  • Yeniden deneme mekanizmanıza eksponansiyel geri yükleme uygulayın. Örneğin, ilk yeniden denemeden önce bir saniye beklediyseniz sonrakinden önce en az iki saniye, ardından dört saniye bekleyin ve bu şekilde devam edin. Birden fazla mesaj gönderiyorsanız aynı anda tüm mesajlar için yeni bir istek gönderilmesini önlemek amacıyla her mesajı ayrı bir rastgele sayı kadar erteleyin.
Sorunlara neden olan 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 koşulları uygulayarak aynı isteği tekrar 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 ileti gönderme

Şu anda eski protokolleri kullanıyorsanız mesaj isteklerini bu bölümde gösterildiği gibi oluşturun. HTTP üzerinden birden fazla platforma gönderim yapıyorsanız v1 protokolünün mesaj isteklerinizi büyük ölçüde basitleştirebileceğini unutmayın.

Belirli cihazlara mesaj gönderme

Belirli cihazlara mesaj göndermek için to anahtarını ilgili uygulama örneğine ait kayıt jetonu olarak ayarlayın. Kayıt jetonları hakkında daha fazla bilgi edinmek için platformunuzla ilgili 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 başka seçenekler sağlar. Sunucu yanıtı biçimi bölümünü inceleyin.

İ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önderin

Firebase Cloud Messaging konusuna mesaj gönderme, tek bir cihaza veya 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ını seçebilir: "/topics/[a-zA-Z0-9-_.~%]+".

Birden çok konunun kombinasyonuna e-posta 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 ya da TopicC abonesi olan cihazlara mesaj göndermek için:

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

FCM önce parantez içindeki tüm koşulları değerlendirir, daha sonra ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede, tek bir konuya abone olan kullanıcı mesajı almaz. Benzer şekilde, TopicA'ya abone olmayan bir kullanıcı da mesajı almaz. Aşağıdaki kombinasyonlar bunu alır:

  • TopicA ve TopicB
  • TopicA ve TopicC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz. 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önderilir:

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önderilir:

<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 yanıtı döndürmeden önce 30 saniyeye kadar gecikme yaşanabilir. İstekte uygulama sunucusunun zaman aşımı değerini uygun şekilde ayarladığınızdan emin olun.

Cihaz gruplarına mesaj gönderme

Kullanımdan kaldırılan eski API'leri kullanarak bir cihaz grubuna mesaj göndermek, tek bir cihaza mesaj göndermeye çok benzer. to parametresini, cihaz grubunun benzersiz bildirim anahtarına ayarlayın. Bu bölümdeki örnekler, eski HTTP ve XMPP protokollerindeki cihaz gruplarına nasıl veri mesajı gönderileceğini gösterir.

Cihaz Grubu HTTP POST İsteği

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ı

"Başarı"nın bir örneği aşağıda verilmiştir. notification_key ile ilişkilendirilmiş 2 kayıt jetonu vardır ve mesaj her ikisine de başarıyla gönderilmiştir:

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

Aşağıda, "kısmi başarı" örneği verilmiştir: notification_key, kendisiyle ilişkilendirilmiş 3 kayıt jetonuna sahiptir. Mesaj, yalnızca kayıt jetonlarından birine başarıyla gönderildi. Yanıt mesajında mesajı alamayan kayıt jetonları (registration_ids) listelenir:

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

Bir mesaj, notification_key ile ilişkili kayıt jetonlarından birine veya daha fazlasına teslim edilemediğinde, uygulama sunucusunun yeniden denemeler arasında geri yükleme yaparak yeniden denemesi gerekir.

Sunucu, üyesi olmayan bir cihaz grubuna mesaj göndermeye çalışırsa yanıt, 0 başarılı ve 0 başarısız olmak üzere 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 ACK ile yanıt verir. Gruptaki tüm cihazlara gönderilen tüm mesajlar başarısız olursa XMPP bağlantı sunucusu NACK ile yanıt verir.

"Başarı"nın bir örneği şu şekildedir: notification_key, kendisiyle ilişkilendirilmiş 3 kayıt jetonuna sahiptir ve mesaj bunların tümüne başarıyla gönderilmiştir:

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

Aşağıda, "kısmi başarı" örneği verilmiştir: notification_key, kendisiyle ilişkilendirilmiş 3 kayıt jetonuna sahiptir. Mesaj, yalnızca kayıt jetonlarından birine başarıyla gönderildi. Yanıt mesajında, mesajı alamayan kayıt jetonları listelenir:

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

FCM bağlantı sunucusu gruptaki tüm cihazlara dağıtım yapamadığında. Uygulama sunucusu bir Nack yanıtı alır.

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

Firebase Admin SDK eski gönderme yöntemleri

Firebase Admin Node.js SDK'sı, Eski FCM Server API'sini temel alan mesajları (FCM) gönderme yöntemlerini destekler. Bu yöntemler, send() yöntemine kıyasla farklı bağımsız değişkenleri kabul eder. Mümkün olduğunda send() yöntemini kullanmalı ve yalnızca tek tek cihazlara veya cihaz gruplarına mesaj gönderirken bu sayfada açıklanan yöntemleri kullanmalısınız.

Tek tek cihazlara gönder

sendToDevice() yöntemine kayıt jetonu göndererek bu cihaza mesaj gönderebilirsiniz:

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, tek bir kayıt jetonu yerine bir kayıt jetonu dizisi ileterek bir çoklu yayın mesajı da (yani birden çok cihaza 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'nin yanıtını içeren bir MessagingDevicesResponse nesnesiyle çözümlenen bir söz döndürür. Döndürme türü, tek bir kayıt jetonunu veya kayıt jetonu dizisi iletirken aynı biçime sahiptir.

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

Cihaz grubuna gönder

sendToDeviceGroup() yöntemi, bir cihaz grubunun bildirim anahtarını belirterek söz konusu cihaz grubuna mesaj göndermenize olanak tanır:

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'nin yanıtını içeren bir MessagingDevicesResponse nesnesiyle çözümlenen bir söz döndürür.

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

Mesaj yükünü tanımlama

Eski FCM protokollerini temel alan yukarıdaki yöntemler, ikinci bağımsız değişken olarak bir mesaj yükünü kabul eder ve hem bildirim hem de veri mesajlarını destekler. data ve / veya notification anahtarlarıyla bir nesne oluşturarak mesaj türlerinden birini ya da her ikisini belirtebilirsiniz. Örneğin, farklı mesaj yükü türlerinin nasıl tanımlanacağı 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ştirilmiş 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, geçerli özelliklerin önceden tanımlanmış bir 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 göz atın.

Veri mesajı yükleri, tüm değerlerin dize olması dahil olmak üzere, birkaç kısıtlamaya tabi ö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

Eski FCM protokollerini temel alan yukarıdaki yöntemler, mesaj için bazı seçenekleri belirten isteğe bağlı üçüncü bir bağımsız değişkeni kabul eder. Örneğin, aşağıdaki örnek 24 saat sonra süresi dolan bir cihaza yüksek öncelikli 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 göz atın.