سفارشی کردن یک پیام در سراسر سیستم عامل

Firebase Admin SDK و رابط برنامه‌نویسی کاربردی HTTP نسخه ۱ FCM به درخواست‌های پیام شما اجازه می‌دهند تا تمام فیلدهای موجود در شیء message را تنظیم کنند. این موارد شامل موارد زیر است:

  • مجموعه‌ای مشترک از فیلدها که باید توسط تمام نمونه‌های برنامه‌ای که پیام را دریافت می‌کنند، تفسیر شوند.
  • مجموعه‌ای از فیلدهای مختص پلتفرم، مانند AndroidConfig و WebpushConfig ، که فقط توسط نمونه‌های برنامه‌ای که روی پلتفرم مشخص‌شده اجرا می‌شوند، تفسیر می‌شوند.

Platform-specific blocks give you flexibility to customize messages for different platforms to ensure that they are handled correctly when received. The FCM backend will take all specified parameters into account and customize the message for each platform.

چه زمانی از فیلدهای مشترک استفاده کنیم

از فیلدهای مشترک در موارد زیر استفاده کنید:

  • ارسال فیلدها به هر پلتفرمی
  • ارسال پیام به موضوعات

همه نمونه‌های برنامه، صرف نظر از پلتفرم، می‌توانند فیلدهای مشترک زیر را تفسیر کنند:

چه زمانی از فیلدهای مخصوص پلتفرم استفاده کنیم

از فیلدهای مخصوص پلتفرم زمانی استفاده کنید که می‌خواهید:

  • ارسال فیلدها فقط به پلتفرم‌های خاص
  • ارسال فیلدهای مخصوص پلتفرم علاوه بر فیلدهای رایج

Whenever you want to send values only to particular platforms, use platform-specific fields. For example, to send a notification only to Apple and Web platforms but not to Android, you must use two separate sets of fields, one for Apple and one for Web.

When you are sending messages with specific delivery options, use platform-specific fields to set them. You can specify different values per platform if you want. However, even when you want to set essentially the same value across platforms, you must use platform-specific fields. This is because each platform may interpret the value slightly differently—for example, time to live is set on Android as an expiration time in seconds, while on Apple it is set as an expiration date .

پیام اعلان با گزینه‌های تحویل مخصوص پلتفرم

درخواست ارسال HTTP v1 API زیر، یک عنوان و محتوای اعلان مشترک را به همه پلتفرم‌ها ارسال می‌کند، اما برخی از لغوهای خاص پلتفرم را نیز ارسال می‌کند. به طور خاص، درخواست:

  • مدت زمان ماندگاری را برای پلتفرم‌های اندروید و وب طولانی می‌کند، در حالی که اولویت پیام‌های APN (پلتفرم‌های اپل) را روی مقدار کم تنظیم می‌کند.
  • کلیدهای مناسب را برای تعریف نتیجه ضربه کاربر روی اعلان در اندروید و اپل تنظیم می‌کند - به ترتیب click_action و category .
{
  "message":{
     "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
     "notification":{
       "title":"Match update",
       "body":"Arsenal goal in added time, score is now 3-0"
     },
     "android":{
       "ttl":"86400s",
       "notification"{
         "click_action":"OPEN_ACTIVITY_1"
       }
     },
     "apns": {
       "headers": {
         "apns-priority": "5",
       },
       "payload": {
         "aps": {
           "category": "NEW_MESSAGE_CATEGORY"
         }
       }
     },
     "webpush":{
       "headers":{
         "TTL":"86400"
       }
     }
   }
 }

To learn more, see the HTTP v1 reference page for more detail on the keys available in platform-specific blocks in the message body. For more information about building send requests that contain the message body, see Send a message using FCM HTTP v1 API .

پیام اعلان با گزینه‌های رنگ و آیکون

در مثال زیر، درخواست ارسال، یک عنوان و محتوای اعلان مشترک را به همه پلتفرم‌ها ارسال می‌کند، اما برخی از تغییرات خاص پلتفرم را نیز به دستگاه‌های اندروید ارسال می‌کند.

For Android, the request sets a special icon and color to display on Android devices. As noted in the reference for AndroidNotification , the color is specified in #rrggbb format, and the image must be a drawable icon resource local to the Android app.

در اینجا مثالی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده دو دستگاه، که یکی از آنها آیکون و رنگ سفارشی را نمایش می‌دهد

نود جی اس

const topicName = 'industry-tech';

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

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

جاوا

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

پایتون

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

برو

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

سی شارپ

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

استراحت

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

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

برای کسب اطلاعات بیشتر، به صفحه مرجع HTTP v1 مراجعه کنید تا جزئیات بیشتری در مورد کلیدهای موجود در بلوک‌های مخصوص پلتفرم در بدنه پیام را ببینید.

پیام اعلان با تصویر دلخواه

به خاطر داشته باشید:

  • تصاویر برای اعلان‌ها به اندازه ۱ مگابایت محدود شده‌اند و در غیر این صورت توسط پشتیبانی داخلی تصویر اندروید محدود شده‌اند.
  • To be able to receive and handle notification images in an Apple app, you must add a Notification Service Extension . The notification service extension allows your app to handle the image delivered in the FCM payload before displaying the notification to the end user, see Set up the notification service extension for code sample.
  • تصاویر آپلود شده با استفاده از آهنگساز اعلان‌ها به اندازه ۳۰۰ کیلوبایت محدود می‌شوند.
  • تصاویر ذخیره شده یا ارائه شده از Cloud Storage مشمول محدودیت‌های سهمیه‌بندی استاندارد هستند.

در درخواست ارسال اعلان خود، گزینه‌های زیر را تنظیم کنید تا کلاینت گیرنده بتواند تصویر ارسال شده در payload را مدیریت کند:

  • برای اندروید، گزینه AndroidConfig زیر را تنظیم کنید:
    • notification.image حاوی آدرس تصویر
  • برای iOS، گزینه‌های ApnsConfig زیر را تنظیم کنید:
    • fcm_options.image که حاوی آدرس اینترنتی تصویر است. اپل برای شناسایی صحیح نوع منبع، الزام می‌کند که آدرس اینترنتی تصویر شامل یک پسوند فایل معتبر باشد.
    • headers({ "mutable-content": 1})

درخواست ارسال زیر یک عنوان اعلان مشترک را به همه پلتفرم‌ها ارسال می‌کند، اما یک تصویر نیز ارسال می‌کند. در اینجا مثالی از جلوه بصری روی دستگاه کاربر آورده شده است:

طراحی ساده یک تصویر در یک اعلان نمایشی

نود جی اس

const topicName = 'industry-tech';

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

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

استراحت

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

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

برای کسب اطلاعات بیشتر، به صفحه مرجع HTTP v1 مراجعه کنید تا جزئیات بیشتری در مورد کلیدهای موجود در بلوک‌های مخصوص پلتفرم در بدنه پیام را ببینید.

پیام اعلان با یک اقدام کلیک مرتبط

The following send request sends a common notification title to all platforms, but it also sends an action for the app to perform in response to the user interacting with the notification. Here's an example of the visual effect on a user's device:

طراحی ساده از یک کاربر که با ضربه زدن روی صفحه وب، آن را باز می‌کند

نود جی اس

const topicName = 'industry-tech';

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

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

استراحت

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