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)

İletileri, bildirim yükü oluşturan bir bildirimle gönderebilirsiniz veri yükü veya kendi kullanıcı tanımlı alanlarınızın veri yükü içeren bir mesaj oluşturun. Görüntüleyin Mesaj türleri başlıklı makaleyi inceleyin.

Bu sayfadaki örneklerde, Firebase Yönetici SDK'sı (Bu API, Düğüm, Java, Python, C#, ve Go) ve v1 HTTP protokolü. Kullanımdan kaldırılan uygulamalar üzerinden mesaj göndermeyle ilgili talimatlar da eski HTTP ve XMPP protokollerini kullanın.

Belirli cihazlara mesaj gönderme

Belirli tek bir cihaza gönderim yapmak için cihazın kayıt jetonunu gösteriliyor. Daha fazla bilgi edinmek için platformunuza yönelik istemci kurulumu bilgilerine bakın kayıt jetonlarıdır.

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ı olursa her gönderme yöntemi bir ileti kimliği döndürür. Firebase Admin SDK'nın döndürdüğü projects/{project_id}/messages/{message_id} biçimindeki kimlik dizesi. HTTP protokolü yanıtı tek bir JSON anahtarıdır:

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

Birden çok cihaza mesaj gönderme

Yönetici FCM API'leri, mesajları çoklu yayın yapmanıza olanak tanır. bir cihaz kayıt jetonları listesine eklenir. En fazla 500 cihaz belirtebilirsiniz kayıt jetonu sayısı.

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ı. Bu, hangi jetonlarla sonuçlandığını kontrol etmek istediğinizde hatalar.

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

Bir konu oluşturduktan sonra, istemci uygulaması örneklerini müşteri tarafında veya müşteri tarafında sunucu API'sine sahipseniz, konu. FCM için gönderme isteklerini ilk kez oluşturuyorsanız kılavuzu inceleyin sunucu ortamınıza ve FCM'ye önemli arka plan ve kurulum bilgilerini sağlar.

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

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

Konulardan oluşan bir kombinasyona ileti göndermek için: bir koşul belirtin. Bu, konuları ele alalım. Örneğin, aşağıdaki koşul iletileri TopicA ve TopicB ya da TopicC aboneliklerine abone olan cihazlar:

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

FCM önce parantez içindeki koşulları değerlendirir, ardından tıklayın. Yukarıdaki ifadede, bir kullanıcı mesajı almamasını sağlayabilirsiniz. Benzer şekilde, TopicA için abone ol düğmesi, mesajı almıyor. Bu kombinasyonlar alın:

  • 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 için desteği sonlandırılmış eski gönderme API'lerini kullanarak cihaz gruplarına gönderme HTTP veya XMPP ya da Node.js için Firebase Yönetici SDK'sı eski protokollere bağlı olarak, Google Analytics 4'te HTTP v1 API'ye geçin en erken bir aşamada belirlemeye çalışın. Eski gönderme API'leri Haziran 2024'te devre dışı bırakılacak ve kaldırılacaktır.

Bir cihaz grubuna ileti göndermek, ileti göndermeye benzer göndermek için aynı yöntemi kullanarak tek bir cihaza gönderme isteklerini yetkilendirin. token cihazını ayarlayın alanını grup bildirim anahtarına ekleyin:

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 kişiye kadar gruplandırabilirsiniz tek bir toplu işlemde toplar ve tümünü tek bir API çağrısında gönderir. HTTP istekleri için ayrı HTTP isteklerine kıyasla tıklayın.

Bu özellik, özelleştirilmiş bir mesaj grubu oluşturmak ve bu mesajları göndermek için kullanılabilir. farklı alıcılara gönderebilirsiniz. Bu özelliği, örneğin şu durumlarda kullanın: farklı kitlelere aynı anda farklı mesajlar gönderebilirsiniz. karar verebilirsiniz.

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 özellikli mesajlar gönderme (yalnızca Android)

Doğrudan başlatma modundaki cihazlara mesaj göndermek için HTTP v1 veya eski HTTP API'leri. Şuraya göndermeden önce: doğrudan başlatma modunda olan cihazlarınızı kullanıyorsanız, İstemci cihazlarının FCM mesajlarını doğrudan başlatma modunda almasını etkinleştirin.

FCM v1 HTTP API'yi kullanarak gönder

Mesaj isteği,"direct_boot_ok" : true İstek gövdesinde AndroidConfig seçenek. Ö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önder

Mesaj isteği, üst taraftaki "direct_boot_ok" : true anahtarını içermelidir düzeyidir. Ö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, aşağıdaki sağlayıcılar tarafından işlenebilir: şu anda doğrudan başlatma modunda olan (ve bu modda değilken) cihaz sayısı.

Farklı platformlardan mesajları özelleştirme

Hem Firebase Admin SDK'sı hem de FCM v1 HTTP protokolü mesajınıza izin verir tüm alanları otomatik olarak ayarlayıp message nesnesini tanımlayın. Bunlardan bazıları:

  • tüm uygulama örnekleri tarafından yorumlanacak şekilde mesajı alabilir.
  • platforma özgü alan grupları (ör. AndroidConfig ve WebpushConfig), yalnızca belirtilen platformda çalışan uygulama örnekleri tarafından yorumlanır.

Platforma özel engellemeler, mesajlarınızı özelleştirmek için size bunların doğru şekilde ele alınmasını sağlamak için farklı platformlardan destek alabilirsiniz. İlgili içeriği oluşturmak için kullanılan FCM arka ucu, belirtilen tüm parametreleri dikkate alır ve mesajı görebilirsiniz.

Ortak alanlar ne zaman kullanılır?

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

  • Tüm platformlarda (Apple, Android ve web) uygulama örneklerini hedefleme
  • Konulara mesaj gönderme

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

Platforma özel 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

Değerleri yalnızca belirli platformlara göndermek istediğinizde aşağıdakini kullanmayın: ortak alanlar; kullanın. Örneğin, bir bildirim göndermek için yalnızca Apple platformları ve web için değil, Android için değil, iki ayrı biri Apple, diğeri web için.

Belirli özel amaçlı iletiler gönderirken teslim seçeneklerini inceleyin, ayarlamak için platforma özgü alanları kullanın. Şu durumlarda her platform için farklı değerler belirtebilirsiniz: istediğiniz zaman kapatabilirsiniz. Ancak, tüm platforma özgü alanları kullanmanız gerekir. Bunun nedeni, her bir platformun değeri biraz farklı yorumlayabilir. Örneğin, Android'de saniye cinsinden son kullanma süresi olarak ayarlıyken Apple'da son kullanma tarihi.

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

Bu örnek gönderme isteği, tüm kullanıcılara ortak bir bildirim başlığı ve içeriği gönderir olmakla birlikte Android'e platforma özel bazı geçersiz kılmalar da gönderir. cihazlar.

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 bir çekilebilir olmalıdır Android uygulaması için yerel simge kaynağı.

Kullanıcının cihazındaki görsel etkinin yaklaşık özeti:

Birinde özel 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"
       }
     }
   }
 }

Bkz. HTTP v1 referans belgeleri Şuradaki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntıları öğrenin: e-posta mesajı

Ö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 aynı zamanda bir resim de gönderir. Yaklaşık 10:00'luk bir Kullanıcının cihazında görsel efekt:

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

Bkz. HTTP v1 referans belgeleri Şuradaki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntıları öğrenin: e-posta mesajı

Örnek: İlişkili tıklama işlemi içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm kullanıcılara ortak bir bildirim başlığı platformlara değil, aynı zamanda uygulamanın bu tür sinyallere yanıt olarak Bildirimle etkileşimde bulunan kullanıcı. Kullanıcının cihazındaki görsel etkinin yaklaşık özeti:

Bir kullanıcının web sayfasına 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"
       }
     }
   }
 }

Bkz. HTTP v1 referans belgeleri Şuradaki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntıları öğrenin: e-posta mesajı

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

Aşağıdaki örnek gönderme isteği, yerelleştirilmiş mesajları görüntülemesi için istemciye yerelleştirme seçenekleri gönderir. Kullanıcının cihazındaki görsel etkinin yaklaşık özeti:

İngilizce ve İspanyolca metinlerin 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"],
                    },
                 },
               },
             },
  },
}'

Bkz. HTTP v1 referans belgeleri Şuradaki platforma özgü bloklarda bulunan anahtarlarla ilgili tüm ayrıntıları öğrenin: e-posta mesajı

HTTP v1 API için REST hata kodları

HTTP v1 API için HTTP hata yanıtları; hata kodu, hata mesajı ve hata durumunu içerir. Ayrıca, hatayla ilgili daha fazla ayrıntı içeren bir details dizisi de içerebilir.

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

1. Örnek: Veri mesajında geçersiz değer içeren bir HTTP v1 API isteğindeki 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 bir HTTP v1 API isteğinden gelen 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 örnek, istek değerlerinde hata olduğunu gösteren type.googleapis.com/google.rpc.BadRequest türüne sahiptir. type.googleapis.com/google.firebase.fcm.v1.FcmError türündeki ikinci örnekte FCM'ye özgü bir hata vardır. Hataların çoğu, ayrıntılar dizisinde hata ayıklamak ve çözüm bulmak için ihtiyaç duyacağınız bilgileri içerir.

Aşağıdaki tabloda FCM v1 REST API hata kodları ve teşvik edebilirsiniz.

Hata Kodu Açıklama ve Çözüm Adımları
UNSPECIFIED_ERROR Bu hata hakkında daha fazla 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 bilgilerin, istemci uygulamasının FCM'ye kaydolurken aldığı kayıt jetonuyla eşleştiğinden emin olun. Jetonu kısaltmayın veya başka karakterler eklemeyin.
. Geçersiz paket adı: İletinin, paket adı istekte iletilen değerle eşleşen bir kayıt jetonuna gönderildiğinden emin olun.
. İleti çok büyük: Bir iletideki yük verilerinin toplam boyutunun FCM sınırlarını aşmadığından emin olun: çoğu ileti için 4.096 bayt veya konulara gönderilen mesajlar için 2.048 bayt. Buna hem anahtarlar hem de değerler dahildir.
. Geçersiz veri anahtarı: Yük verilerinin, FCM tarafından dahili olarak kullanılan bir anahtar (ör. gönderen, gcm ya da google tarafından eklenen herhangi bir değer) içermediğinden emin olun. Bazı kelimelerin (daraltma_anahtarı gibi) FCM tarafından da kullanıldığını, ancak yük içinde kullanılmasına 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 dosyasında kullanılan değerin, 0 ile 2.419.200 (4 hafta) arasında saniye cinsinden bir süreyi temsil eden bir tam sayı olduğundan emin olun.
. Geçersiz parametreler: Sağlanan parametrelerin ad ve tür bakımından doğru olup olmadığını kontrol edin.
UNREGISTERED (HTTP hata kodu = 404) Uygulama örneğinin FCM kaydı iptal edildi. Bu genellikle kullanılan jetonun artık geçerli olmadığı ve yeni bir jetonun kullanılması gerektiği anlamına gelir. Bu hata, eksik kayıt jetonları veya kaydedilmemiş jetonlardan kaynaklanabilir.
. Eksik Kayıt: İletinin hedefi token değeriyse isteğin bir kayıt jetonu içerdiğinden emin olun.
. Kayıtlı değil: Mevcut bir kayıt jetonunun geçerliliği, aşağıdakiler gibi çeşitli durumlarda artık geçersiz olabilir:
- İstemci uygulamasının FCM kaydını iptal etmesi
. - İstemci uygulamasının kaydı otomatik olarak kaldırılırsa (kullanıcı uygulamayı kaldırırsa bu durum gerçekleşebilir). Örneğin, iOS'te APNs Geri Bildirim Hizmeti, APNs jetonunun geçersiz olduğunu bildirdiyse.
. - 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üncellenmişse 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 söz konusu jetonu mesaj göndermek için kullanmayı bırakın.
SENDER_ID_MISMATCH (HTTP hata kodu = 403) Kimliği doğrulanan gönderen kimliği, kayıt jetonundaki 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 belirtmelidir. İstemci uygulamasına ileti gönderirken bu gönderen kimliklerinden birini kullanmanız gerekir. Farklı bir gönderene geçiş yaparsanız 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; mesaj hızı kotasının aşılması, cihaz mesaj hızı kotasının aşılması veya konu mesaj hızı kotasının aşılmasından kaynaklanabilir.
. İleti hızı aşıldı: İletilerin gönderme hızı çok yüksek. Genel mesaj gönderme hızını azaltmanız gerekir. Reddedilen iletileri yeniden denemek için en az 1 dakikalık bir başlangıç gecikmesiyle eksponansiyel geri yükleme kullanın.
. Cihaz mesaj hızı aşıldı: Belirli bir cihaza gönderilen mesajların oranı çok yüksek. Tek bir cihazla mesaj gönderme hızı sınırını inceleyin. Bu cihaza gönderilen ileti sayısını azaltın ve göndermeyi yeniden denemek için eksponansiyel geri yükleme özelliğini kullanın.
. Konu mesaj oranı aşıldı: Belirli bir konuda abonelere gönderilen mesajların oranı çok yüksek. Bu konuda gönderilen ileti sayısını azaltın ve göndermeyi yeniden denemek için en az 1 dakikalık bir başlangıç gecikmesiyle üstel geri yüklemeyi kullanın.
UNAVAILABLE (HTTP hata kodu = 503) Sunucu aşırı yüklenmiş. 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 çekilme uygulayın. (Örneğin, ilk yeniden denemeden önce bir saniye beklediyseniz, sonraki denemeden önce en az iki saniye, ardından 4 saniye vb. bekleyin). Birden çok mesaj gönderiyorsanız ses dalgalanması özelliğini uygulayabilirsiniz. Daha fazla bilgi için Yeniden denemeleri işleme başlıklı makaleyi inceleyin. Soruna neden olan gönderenler, ret listesine alınma riskine girer.
INTERNAL (HTTP hata kodu = 500) Bilinmeyen bir dahili hata oluştu. Sunucu, isteği işlemeye çalışırken bir hatayla karşılaştı. Yeniden denemeleri işleme bölümündeki önerileri uygulayarak 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 eksik. iOS cihazı veya web push kaydına hedeflenen mesaj 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ı da dahil olmak üzere açıklamalarını içerir.

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 bilgi içermelidir.
messaging/invalid-recipient Hedeflenen ileti alıcısı geçersiz. Hata mesajı ek bilgiler içeren ekranlara öncelik verin.
messaging/invalid-payload Geçersiz bir mesaj yük nesnesi sağlandı. Hata mesajı ek bilgiler içeren ekranlara öncelik verin.
messaging/invalid-data-payload-key Veri mesajı yükü geçersiz bir anahtar içeriyor. Referansı göster belgeleri Kısıtlanmış anahtarlar için DataMessagePayload.
messaging/payload-size-limit-exceeded Sağlanan mesaj yükü, FCM boyutu sınırlarını aşıyor. İlgili içeriği oluşturmak için kullanılan sınır çoğu ileti için 4.096 bayttır. Konulara gönderilen mesajlar için sınır 2048 bayttır. İlgili içeriği oluşturmak için kullanılan toplam yük boyutuna hem anahtarlar hem de değerler dahildir.
messaging/invalid-options Geçersiz mesaj seçenekleri nesnesi sağlandı. Hata mesajı ek bilgiler içeren ekranlara öncelik verin.
messaging/invalid-registration-token Sağlanan kayıt jetonu geçersiz. Kayıtla eşleştiğinden emin olun. istemci uygulamasının FCM'ye kaydolurken aldığı jeton. Şunları yapmayın: veya başka karakterler ekleyebilirsiniz.
messaging/registration-token-not-registered Sağlanan kayıt jetonu kayıtlı değil. Daha önce geçerli olan kayıt jetonunun kaydı çeşitli nedenlerle iptal edilebilir, şunları içerir:
  • İstemci uygulaması FCM'deki kaydını iptal etti.
  • İstemci uygulamasının kaydı otomatik olarak iptal edildi. Bu durum, Kullanıcı uygulamayı kaldırır veya Apple platformlarında APNs Geri Bildirimi Hizmet, APNs jetonunun geçersiz olduğunu bildirdi.
  • Kayıt jetonunun süresi doldu. Örneğin Google, yenileme kayıt jetonları veya APNs jetonunun süresi dolmuş olabilir Apple cihazlar.
  • İstemci uygulaması güncellendi ancak yeni sürüm şu şekilde yapılandırılmadı: mesaj alabilir.
ziyaret edin. Tüm bu durumlarda, bu kayıt jetonunu kaldırın ve şu amaçlarla kullanmayı bırakın: mesaj gönder.
messaging/invalid-package-name İleti, "Paket adı" bölümünde bulunan sağlananla eşleşmiyor restrictedPackageName seçeneği gösterilir.
messaging/message-rate-exceeded Belirli bir hedefe gönderilen mesajların oranı çok yüksek. Sayıyı azaltın bu cihaza veya konuya gönderilen iletilerin sayısı ve hemen tekrar denenmez gönderiliyor.
messaging/device-message-rate-exceeded Belirli bir cihaza gönderilen mesajların oranı çok yüksek. Sayıyı azaltın ve şu adreslere hemen göndermeyi tekrar denemeyin: bu cihazda.
messaging/topics-message-rate-exceeded Belirli bir konunun abonelere gönderilen mesajların oranı çok yüksek. Bu konu için gönderilen iletilerin sayısını azalt ve hemen gerçekleştirmeyen yeniden göndermeyi dene.
messaging/too-many-topics Bir kayıt jetonu, maksimum sayıda konuya abone oldu ve daha fazla için abone olunamıyor.
messaging/invalid-apns-credentials Apple cihazı hedefleyen bir ileti, gerekli APN'lerin SSL sertifikası yüklenmedi veya süresi doldu. Kontrol edin sertifikalarınızın geçerliliğinden emin olun.
messaging/mismatched-credential Bu SDK'nın kimliğini doğrulamak için kullanılan kimlik bilgisinin şu işlemler için izni yok: sağlanan kayda uygun cihaza iletiler gönderin jeton. Hem kimlik bilgisi hem de kayıt jetonunun emin olmanız gerekir. Görüntüleyin Firebase'i uygulamanıza ekleyin inceleyin.
messaging/authentication-error SDK, FCM sunucularının kimliğini doğrulayamadı. Şunları yaptığınızdan emin olun: Firebase Admin SDK kimliğini, doğru kimlik bilgisiyle doğrulayın FCM mesajları gönderme iznidir. Görüntüleyin Firebase'i uygulamanıza ekleyin inceleyin.
messaging/server-unavailable FCM sunucusu, isteği zamanında işleyemedi. Şunları yapmalısınız: aynı isteği yeniden deneyebilir, ancak şunları yapmanız gerekir:
  • Retry-After FCM Bağlantı Sunucusu'ndan yanıt alın.
  • Yeniden deneme mekanizmanıza eksponansiyel geri çekilme uygulayın. Örneğin, İlk tekrar denemeden önce bir saniye beklediyseniz en az iki saniye, sonra dört saniye vb. Eğer birden fazla mesaj göndermek yerine her birini bir yeni bir istek gönderilmesini önlemek amacıyla rastgele ek tutar aynı anda gönderebilirsiniz.
ziyaret edin. Soruna neden olan gönderenler kara listeye alınma riskiyle karşı karşıya kalır.
messaging/internal-error FCM sunucusu, isteği gönderin. Aynı isteği aşağıdaki koşulları uygulayarak yeniden deneyebilirsiniz Yukarıdaki messaging/server-unavailable satırında listelenir. Öğe Hata devam ederse, lütfen sorunu Google Hata Raporu destek kanalı.
messaging/unknown-error Bilinmeyen bir sunucu hatası döndürüldü. Ham sunucu yanıtını hata mesajına göz atın. Bu hatayı alırsanız lütfen bildirin hata mesajının tamamını Hata Raporu destek kanalı.

Eski uygulama sunucusu protokollerini kullanarak mesaj gönderin

Şu anda eski protokolleri kullanıyorsanız mesaj isteklerini aşağıda gösterildiği gibi oluşturun ele alacağız. Birden fazla platforma HTTP ise v1 protokolü, mesaj isteklerinizi büyük ölçüde basitleştirebilir.

Belirli cihazlara mesaj gönderme

Belirli cihazlara mesaj göndermek için to anahtarını kayıt olarak ayarlayın jeton. Aşağıdaki alan için istemci kurulum bilgilerini görüntüleyin: platformuna gidin.

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 sunar. Görüntüleyin Sunucu yanıtı biçimi.

Aşağı akış gönderirken kullanılabilecek mesaj seçeneklerinin tam listesi için iletileri görmek için, seçtiğiniz uygulamanın referans bilgilerine bakın. bağlantı sunucusu protokolü HTTP veya XMPP.

Konulara mesaj gönderme

Firebase Cloud Messaging konusuna mesaj gönderme süreci, Tek bir cihaza veya kullanıcı grubuna ileti gönderme. Uygulama sunucusu, to anahtarını /topics/yourTopic gibi bir değerle ayarlar. Geliştiriciler şunları yapabilirler: normal ifadeyle eşleşen herhangi bir konu adını seçin: "/topics/[a-zA-Z0-9-_.~%]+"

Birden fazla konu kombinasyonlarına göndermek için uygulama sunucusunun condition anahtarını (to anahtarı yerine) şu boole koşuluna hedef konuları belirtir. Örneğin, abone olan cihazlara ileti göndermek için TopicA ve TopicB veya TopicC:

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

FCM önce parantez içindeki 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ı alabilir. Benzer şekilde, TopicA'ya abone olmayan bir kullanıcı da mesajı almadığında Bu kombinasyonlara izin verilir:

  • TopicA ve TopicB
  • TopicA ve TopicC

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" konularına abone olan cihazlara gönder veya "kediler" olarak tanımlar:

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" konularına abone olan cihazlara gönder veya "kediler" olarak tanımlar:

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


  </gcm>
</message>

Konu XMPP yanıtı

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

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

FCM Sunucusu'ndan önce 30 saniyeye kadar gecikme olabilir konu gönderme isteklerine başarılı veya başarısız yanıt döndürür. Şunlardan emin olun: uygulama sunucusunun zaman aşımı değerini istekte uygun şekilde ayarlayın.

Cihaz gruplarına mesaj gönderme

Desteği sonlandırılan eski API'leri kullanarak bir cihaz grubuna mesaj gönderme ve günlük hayatınızda tek bir cihaza gönderebilirsiniz. to parametresini ayarlayın ekleyin. Bu bölümdeki örneklerde nasıl veri gönderileceği gösterilmektedir mesajları eski HTTP ve XMPP protokollerindeki cihaz gruplarına gönderir.

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ı" örneği: notification_key kendisiyle ilişkilendirilmiş 2 kayıt jetonu var ve mesaj her ikisine de başarıyla gönderildi:

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

"Kısmi başarı" örneği ile başlar. notification_key ile ilişkilendirilmiş 3 kayıt jetonu var gerçekleşebilir. İleti, kayıtların 1 tanesine başarıyla gönderildi geçerlidir. Yanıt mesajında kayıt jetonları listelenir. Mesajı alamayan (registration_ids):

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

Bir ileti, notification_key ile ilişkili kayıt jetonları, Uygulama sunucusu, yeniden denemeler arasında geri yükleme yaparak tekrar denemelidir.

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

{
  "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 birine gönderildiğinde XMPP bağlantı sunucusu bir ACK ile yanıt verir. Eğer gruptaki tüm cihazlara gönderilen tüm iletiler başarısız, XMPP bağlantısı sunucu bir NACK ile yanıt verir.

"Başarı" örneği — notification_key kendisiyle ilişkilendirilmiş 3 kayıt jetonu var ve mesaj tümüne başarıyla gönderildi:

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

"Kısmi başarı" örneği ile başlar. notification_key ile ilişkilendirilmiş 3 kayıt jetonu var gerçekleşebilir. İleti, kayıtların 1 tanesine başarıyla gönderildi geçerlidir. Yanıt mesajında kayıt jetonları listelenir. bu mesajı alamayan kullanıcılar için:

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

FCM bağlantı sunucusu gruptaki tüm cihazlar Uygulama sunucusu bir nack yanıtı alır.

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

Firebase Admin SDK eski gönderme yöntemleri

Firebase Admin Node.js SDK'sı, (FCM) mesajlarının Eski FCM sunucu API'si. 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 ileti gönderirken bu sayfada açıklanan yöntemleri veya yöntemleri kullanabilirsiniz. cihaz grupları.

Cihazlara tek tek gönder

Bir kayıt jetonunu sendToDevice() yöntemi kullanabilirsiniz:

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, bir multicast mesajı (yani birden fazla cihaza gönderebilirsiniz) bunun yerine bir kayıt jetonları dizisi ileterek tek bir kayıt jetonunun bulunması gerekir:

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, MessagingDevicesResponse FCM'nin yanıtını içeren nesne. Dönüş türü aynı biçimi jeton.

Kimlik doğrulama hatası veya hız sınırlaması gibi bazı durumlarda anlamına gelir. Böyle durumlarda, sendToDevice() bir hata ile reddedildi. Hata kodlarının tam listesi için ve çözüm adımları hakkında bilgi edinmek için Yönetici FCM API Hataları.

Cihaz grubuna gönder

İlgili içeriği oluşturmak için kullanılan sendToDeviceGroup() yöntemi, o cihaz grubu için bildirim tuşu:

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, MessagingDevicesResponse FCM'nin yanıtını içeren nesne.

Kimlik doğrulama hatası veya hız sınırlaması gibi bazı durumlarda anlamına gelir. Böyle durumlarda, sendToDeviceGroup() bir hata ile reddedildi. Hata kodlarının tam listesi için ve çözüm adımları hakkında bilgi edinmek için Yönetici FCM API Hataları.

Mesaj yükünü tanımlama

Yukarıdaki yöntemler, eski FCM protokollerine dayanır ikinci bağımsız değişkeni ve destek olarak bir mesaj yükü her ikisi bildirim ve veri mesajları için ekleyebilirsiniz. data ile bir nesne oluşturarak mesaj türlerinden birini veya ikisini birden belirtebilirsiniz. ve / veya notification tuşuna basın. Örneğin, iş kırılım yapılarını tanımlama sayısı:

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üklerinin, geçerli özelliklerin önceden tanımlanmış bir alt kümesi bulunur ve hedeflediğiniz mobil işletim sistemine bağlı olarak biraz farklılık gösterir. Şu proje için referans belgelerine bakın: NotificationMessagePayload sayfasını ziyaret edin.

Veri mesajı yükleri, birkaç değer içeren özel anahtar/değer çiftlerinden oluşur. (tüm değerlerin dize olması gibi) dahil olmak üzere bazı kısıtlamalara tabidir. Bkz. referans belgeleri DataMessagePayload sayfasına bakın.

Mesaj seçeneklerini tanımlama

Yukarıdaki yöntemler, eski FCM protokollerine dayanır isteğe bağlı üçüncü bağımsız değişkeni kabul ederek şunun için mesajı alırsınız. Örneğin, aşağıdaki örnek yüksek öncelikli bir ileti gönderiyor 24 saat sonra süresi dolan bir cihaza aktarma:

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

Şu proje için referans belgelerine bakın: MessagingOptions mevcut seçeneklerin tam listesi için.