> For the complete documentation index, see [llms.txt](https://app.developers.karte.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://app.developers.karte.io/app-send-notification/app-customize-notification-payload.md).

# 通知ペイロードをカスタマイズする

{% hint style="warning" %}
**サポート対象外**

通知ペイロードのカスタマイズは、接客サービス内アクションのカスタマイズで設定することができます。\
接客のカスタマイズはサポート対象外となりますので、必ずテスト配信等行った上でご活用ください。
{% endhint %}

KARTEのプッシュ通知では、バックエンドに Firebase Cloud Messaging (以下FCM) を採用しています。\
そのため通知ペイロードをカスタマイズするにあたっては、基本的に FCM v1 APIのペイロード仕様を理解しておく必要があります。\
加えて iOS 向けの通知ペイロードをカスタマイズする場合は、別途 APNs のペイロード仕様についても理解しておく必要があります。

{% hint style="info" %}
**FCM v1 API ペイロード仕様**

<https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages>
{% endhint %}

## 通知アクションの設定について

KARTEからプッシュ通知を送信する場合は、KARTEがデフォルトで用意しているプッシュ通知テンプレートを利用して通知アクションの設定を行う必要があります。

プッシュ通知テンプレートでは一般的によく利用されるペイロード値を変数としてデフォルト定義しており、容易にプッシュ通知の送信設定を行えるようになっています。\
なおデフォルトで定義されているもの以外で送信したい値がある場合は、独自に変数を定義することで送信することが可能です。\
この方法については、[プラットフォーム固有のペイロード値の設定方法について](#プラットフォーム固有のペイロード値の設定方法について) および [アプリケーション上で利用する独自変数の設定方法について](#アプリケーション上で利用する独自変数の設定方法について) をご覧ください。

## デフォルト変数とペイロード値の対応関係について

テンプレートにはいくつかの静的変数がデフォルトで定義されています。\
デフォルトで定義されている静的変数とペイロード値との対応関係は、以下の表に記載しています。

### Android関連

| 静的変数名                | ペイロードオブジェクトパス                                             | 内容                           |
| -------------------- | --------------------------------------------------------- | ---------------------------- |
| `title`              | message.android.data.krt\_attributes.title                | 通知のタイトル                      |
| `body`               | message.android.data.krt\_attributes.body                 | 通知の本文                        |
| `sound_for_android`  | message.android.data.krt\_attributes.sound                | 通知受信時に鳴らすサウンド名               |
| `android_channel_id` | message.android.data.krt\_attributes.android\_channel\_id | チャネルID                       |
| `url`                | message.android.data.krt\_attributes.url                  | 通知開封時の遷移先（URL / ディープリンク）     |
| `attachment_url`     | message.android.data.krt\_attributes.attachment\_url      | 通知に表示するファイル（画像 / 動画 / 音声）URL |

### iOS関連

| 静的変数名               | ペイロードオブジェクトパス                              | 内容                                                                                          |
| ------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------- |
| `title`             | message.apns.payload.aps.alert.title       | 通知のタイトル                                                                                     |
| `body`              | message.apns.payload.aps.alert.body        | 通知の本文                                                                                       |
| `sound_for_ios`     | message.apns.payload.aps.sound             | 通知受信時に鳴らすサウンド名                                                                              |
| `badge_for_ios`     | message.apns.payload.aps.badge             | バッジ                                                                                         |
| `content_available` | message.apns.payload.aps.content-available | <p>サイレント通知のフラグ<br>サイレント通知の対応方法は<a href="/pages/Fducaw1IpNfPfbdjDcJi">ドキュメント</a>をご確認ください</p> |
| `thread_id`         | message.apns.payload.aps.thread-id         | スレッドID                                                                                      |
| `url`               | message.apns.payload.krt\_attributes       | 通知開封時の遷移先（URL / ディープリンク）                                                                    |
| `attachment_url`    | message.apns.payload.krt\_attributes       | 通知に表示するファイル（画像 / 動画 / 音声）URL                                                                |

{% hint style="warning" %}
**テーブルに記載がない静的変数に関して**

`app_name` や `format_type` など一部の静的変数は、KARTE内部でのみ使用される変数になるため通知ペイロードには含まれません。\
なお、これらの静的変数は動作上必要な変数であるため削除しないようにしてください。
{% endhint %}

## プラットフォーム固有のペイロード値の設定方法について

FCMの通知ペイロードにはプラットフォーム固有の値が存在します。\
デフォルト変数以外のプラットフォーム (Android / iOS) 固有の値を送信したい場合は、独自に静的変数を定義することで可能です。\
静的変数名に、ペイロードに含まれるオブジェクトのプロパティ名をドットで結合したもの（ペイロードオブジェクトパス）を指定すると、FCMの通知ペイロードに展開して配信されます。

ペイロードオブジェクトパスの指定の際は、静的変数名にドットを含める形の記述で指定可能です。\
また、KARTEの静的変数では、変数名に「ハイフン（-）」は使用できないため指定の際にエラーとなりますが、**ペイロードの指定に際しては、エラーを無視して保存する**ことで設定頂けます。

**例：プッシュ通知の有効期限 (`ttl` / `apns-expiration`) を指定する場合**

FCM v1 API ペイロード (有効期限の指定に関連する箇所だけを抜粋)

{% code title="FCM v1 API ペイロード" overflow="wrap" %}

```json
{
  "validate_only": false,
  "message": {
    ...
    "android": {
      "ttl": "86400s",
      "data": {
        ...
      }
    },
    "apns": {
      "headers": {
        "apns-expiration": "1556636400",
        ...
      },
      "payload": {
        ...
      }
    }
  }
}
```

{% endcode %}

この場合の静的変数名は以下のようになります (`message` 部分は静的変数名には含めません)

* `android.ttl`
* `apns.headers.apns-expiration`

なお上記のような、ぺイロードオブジェクトパスを静的変数名に指定したペイロードカスタマイズは、プラットフォーム固有のオブジェクト (message.android / message.apns) 配下の値に限り、利用可能です。\
その他の値は、展開されないか、配信時エラーとなります。

### Interruption levels（iOS 15以上）の設定方法について

集中モード時の通知の届き方をコントロールするために Interruption levels を設定することが可能です。\
例えば interruption-level を time-sensitive に設定したい場合、以下表のように静的変数と値を設定ください。\
なお、Time Sensitive Notifications の受信にはアプリ側の対応が必要です、詳細は [Appleの公式資料](https://developer.apple.com/videos/play/wwdc2021/10091) を参照ください。

| 静的変数名                                 | 値              |
| ------------------------------------- | -------------- |
| `apns.payload.aps.interruption-level` | time-sensitive |

### relevance score（iOS 15以上）の設定方法について

通知要約の並び順に影響を与えるために関連スコア（relevance score） を設定することが可能です。\
例えば relevance score を最大値にしたい場合、以下表のように静的変数と値を設定します。\
詳細は [Generating a Remote Notification（Apple公式ドキュメント）](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification) や[relevanceScore（Apple公式リファレンス）](https://developer.apple.com/documentation/usernotifications/unnotificationcontent/3821031-relevancescore)を参照ください。

| 静的変数名                              | 値   |
| ---------------------------------- | --- |
| `apns.payload.aps.relevance-score` | 1.0 |

## アプリケーション上で利用する独自変数の設定方法について

KARTEから配信するプッシュ通知に、アプリケーション上で利用したい独自の変数を設定することが可能です。\
アクション設定画面にて静的変数を設定することで、プッシュ通知のペイロードに展開されます。\
参考：[静的変数の利用](https://support.karte.io/post/3TPVVSzxiA6U3MYNRj25JJ#1-0)

### 独自変数の設定方法

アプリケーション上で利用する独自変数を設定したい場合は、任意の名前の静的変数を定義してください。

**例：静的変数`query` を定義する場合**

静的変数名を `query` とした変数を設定することで、下記の表のペイロードオブジェクトパスに変数が配置されます。

プラットフォーム毎に別々の変数を配信したい場合は、前項 [プラットフォーム固有のペイロード値の設定方法について](#プラットフォーム固有のペイロード値の設定方法について) を参照し、 `android.data.query` / `apns.payload.query` という変数名にすることで、配信プラットフォームを制御することができます。

| 静的変数名                                                              | プラットフォーム | ペイロードオブジェクトパス              |
| ------------------------------------------------------------------ | -------- | -------------------------- |
| <p><code>query</code><br>or<br><code>android.data.query</code></p> | Android  | message.android.data.query |
| <p><code>query</code><br>or<br><code>apns.payload.query</code></p> | iOS      | message.apns.payload.query |

{% hint style="warning" %}
**注意が必要な静的変数名**

静的変数名が `android.` および `apns.` から始まる名前を指定する場合、[プラットフォーム固有のペイロード値の設定方法について](#プラットフォーム固有のペイロード値の設定方法について) に基づいて値が設定されるため、意図した通りに値の設定が行えない点ご注意ください。
{% endhint %}

### 設定した値の参照方法

独自変数をアプリケーション上で参照したい場合は、以下を参考に実装を行なってください。

**例：静的変数`query` を参照する場合**

静的変数名 `query`（プラットフォーム毎の場合: `android.data.query` / `apns.payload.query` ） の変数は、FCMの通知ペイロードに展開されるため、下記のような実装で参照できます。

#### Android

{% tabs %}
{% tab title="Kotlin" %}
{% code title="MyFirebaseMessagingService.kt" overflow="wrap" %}

```kotlin
class MyFirebaseMessagingService : FirebaseMessagingService() {

  override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    val query = remoteMessage?.data?.get("query")
    ...
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code title="MyFirebaseMessagingService.java" overflow="wrap" %}

```java
public class MyFirebaseMessagingService extends FirebaseMessagingService {

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    String query = remoteMessage.getData().get("query");
    ...
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### iOS

{% tabs %}
{% tab title="Swift" %}
{% code title="AppDelegate.swift" overflow="wrap" %}

```swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  let query = userInfo["query"] as? String
  ...
}

// UNUserNotificationCenterDelegate (iOS10-)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  let userInfo = response.notification.request.content.userInfo
  let query = userInfo["query"] as? String
  ...
}
```

{% endcode %}
{% endtab %}

{% tab title="Objective-C" %}
{% code title="AppDelegate.m" overflow="wrap" %}

```objc
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler
{
  NSString *query = userInfo[@"query"];
  ...
}

// UNUserNotificationCenterDelegate (iOS10-)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
API_AVAILABLE(ios(10.0)) {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  NSString *query = userInfo[@"query"];
  ...
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## ペイロード未指定の場合のデフォルト値

基本的にテンプレートで指定された値のみペイロードに設定されますが、\
数点例外があり、以下のパラメータについてはKARTE側でデフォルトで設定されます。\
尚、デフォルト値は予告なく変更する可能性があります。

```
message.android.priority = 'HIGH'
message.ios.headers.apns-priority = 10
message.ios.headers.apns-push-type = alert
```

以下の値は、画像等のファイルが添付されている場合に限り設定されます。

```
message.ios.payload.aps.mutable-content = 1
```

以下の値は、設定されていたとしても削除されます。

```
message.android.notification
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://app.developers.karte.io/app-send-notification/app-customize-notification-payload.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
