> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 示例应用：可靠且表现得当的推送

> 示例应用 Clean Beans 如何用幂等键防止重复推送、针对每种推送类型调整投递方式，并设置应用图标角标。

本页面是[示例应用：完整的 OneSignal 集成](https://documentation.onesignal.com/docs/cn/example-full-integration-overview.md)的一部分，该指南从头到尾跟随一个真实应用。这个应用是 **Clean Beans**，一款面向合租家庭的打扫值日表应用，使用 Expo（React Native）和 Supabase 后端构建。

让推送送达只是第一步。本页面介绍让推送值得信赖的更细致的决定：绝不重复发送同一条推送、让过时的推送自动过期，以及让每种类型的推送都以合适的方式表现。

## 绝不重复发送同一条提醒 \\

计划任务会被重试。任务也可能被误运行两次。如果没有保护，每次重复都会多发一条推送。

OneSignal 的 `idempotency_key` 可以解决这个问题。如果两个请求带有相同的键，第二个请求不会被发送。该键必须是 UUID，OneSignal 会将其保留 30 天。

计划函数没有地方在多次运行之间保存随机键，因此 Clean Beans 根据发送本身来生成键：类型、接收者和日期。同一次发送总会生成相同的键。

```typescript supabase/functions/_shared/idempotency.ts theme={null}
/** Name-based UUID (version 5) per RFC 9562. */
export async function uuidV5(name: string, namespace: string): Promise<string> {
  const ns = uuidToBytes(namespace);
  const nameBytes = new TextEncoder().encode(name);
  const input = new Uint8Array(ns.length + nameBytes.length);
  input.set(ns);
  input.set(nameBytes, ns.length);

  const digest = new Uint8Array(await crypto.subtle.digest('SHA-1', input));
  const bytes = digest.slice(0, 16);
  bytes[6] = (bytes[6] & 0x0f) | 0x50; // version 5
  bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC variant

  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

export function idempotencyKey(...parts: string[]): Promise<string> {
  return uuidV5(parts.join(':'), CLEAN_BEANS_NAMESPACE);
}
```

| 推送 | 键的组成 | 结果 |
| - | - | - |
| 每日摘要 | 类型、用户 ID、用户本地日期 | 每位用户每天一份摘要 |
| 逾期提醒 | 类型、用户 ID、用户本地日期 | 每位用户每天一条提醒 |
| 打扫提醒 | 类型、小时、排序后的接收者 ID | 每次每小时运行中每个批次一条提醒 |
| 每周邮件 | 类型、家庭 ID、运行日期 | 每次运行每个家庭一封邮件 |
| 加入已批准 | 类型、用户 ID、家庭 ID、批准时间 | 每次批准一条推送 |

对于批量发送，键覆盖整个批次。

```typescript supabase/functions/send-cleaning-reminder/index.ts theme={null}
const batchKey = await idempotencyKey(
  'upcoming_cleaning',
  utcHourSlot(now),
  [...batch].sort().join(','),
);
```

> [!NOTE]
>
> 幂等键适用于 Create message 和 Create custom events 端点。Live Activity 请求不接受幂等键，它们通过 `activity_id` 进行标识。

## 为每种推送设定各自的行为 \\

晚到两小时的打扫提醒还不如没有提醒。Kudos 让人开心，但从不紧急。Clean Beans 在一组投递配置中统一描述这些差异，并将合适的配置展开到每个请求中。

```typescript supabase/functions/_shared/delivery.ts theme={null}
export const DELIVERY: Record<
  'daily_digest' | 'overdue_reminder' | 'upcoming_cleaning' | 'session_completed' | 'kudos' | 'join_approved' | 'member_lapsed',
  DeliveryProfile
> = {
  // Morning digest. Expires after 6h — by then the overdue nudge has taken
  // over. Grouped with the nudge under the same thread.
  daily_digest: {
    ttl: 6 * HOUR,
    thread_id: 'tasks',
    android_group: 'tasks',
    ios_interruption_level: 'active',
    ios_relevance_score: 0.6,
  },

  // Afternoon nudge. Arrives as its own alert, grouped with the digest.
  overdue_reminder: {
    ttl: 6 * HOUR,
    thread_id: 'tasks',
    android_group: 'tasks',
    ios_interruption_level: 'active',
    ios_relevance_score: 0.8,
  },

  // "Cleaning time in 1 hour". Only meaningful until the window starts,
  // so it expires after 1h. Time-sensitive: it is tied to a time the user
  // scheduled themselves, so it may break through Focus modes.
  upcoming_cleaning: {
    ttl: 1 * HOUR,
    thread_id: 'schedule',
    android_group: 'schedule',
    ios_interruption_level: 'time_sensitive',
    ios_relevance_score: 0.9,
  },

  // ...
};
```

| 推送 | 为离线设备保留的时长 | 分组 | iOS 中断级别 | 相关性 |
| - | - | - | - | - |
| 每日摘要 | 6 小时 | `tasks` | Active | 0.6 |
| 逾期提醒 | 6 小时 | `tasks` | Active | 0.8 |
| 打扫提醒 | 1 小时 | `schedule` | Time Sensitive | 0.9 |
| 会话完成 | 24 小时 | `household` | Active | 0.4 |
| Kudos | 3 天 | `household` | Passive | 0.7 |
| 加入已批准 | 3 天 | `household` | Active | 0.8 |

类型列表中的 `member_lapsed` 配置属于从 Journey Webhook 发送的推送，本指南不涉及。

各项设置的作用：

* **`ttl`** 是为离线设备保留推送的时长。打扫提醒的内容是“1 小时后”，因此一小时后就会被丢弃。
* **`thread_id`** 和 **`android_group`** 会在通知列表中将相关推送分组。
* **`ios_interruption_level`** 控制推送的提醒强度。`time_sensitive` 可以突破专注模式。`passive` 会静默送达。
* **`ios_relevance_score`** 决定推送在 iOS 通知摘要中的排序。Clean Beans 将 `1.0` 留给关键消息，并且没有发送这类消息。

**应用设置。** 只有当应用声明了该 capability 时，iOS 才会遵循 `time_sensitive`。

```json app.json theme={null}
{
  "expo": {
    "ios": {
      "entitlements": {
        "com.apple.developer.usernotifications.time-sensitive": true
      }
    }
  }
}
```

> [!WARNING]
>
> **一条经验教训：`collapse_id`。** Clean Beans 最初为摘要和逾期提醒设置了相同的 `collapse_id`，让提醒替换摘要。在 iOS 上，如果一条推送替换了仍在通知列表中的推送，它会被原地替换，没有横幅也没有声音。提醒因此被忽视，失去了意义，所以这项设置被移除了。只有在您确实需要静默更新时（例如实时比分），才使用 `collapse_id`。

## 在应用图标上显示数量 \\

两种任务推送会把应用图标角标设置为标题中的数字。

```typescript supabase/functions/send-overdue-reminders/index.ts theme={null}
// App icon badge = number of overdue tasks. The OneSignal SDK clears the
// badge automatically the next time the app is opened.
ios_badgeType: 'SetTo',
ios_badgeCount: taskCount,
```

![带有角标数字的 Clean Beans 应用图标](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-badge.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=08c9bc46b557e4e15819cd0ec42488cf)

应用图标角标显示逾期任务的数量。

这里使用 `SetTo` 而不是 `Increase`，因为角标表示的是任务数量，而不是未读通知数量。下午的提醒会替换早上的数字。

> [!NOTE]
>
> 每次打开应用时，OneSignal SDK 都会自动清除角标，因此应用无需编写重置代码。应用处于打开状态时到达的推送不会显示角标。Android 没有可以通过 API 设置的数字角标。

> [card] [幂等请求](https://documentation.onesignal.com/reference/idempotent-notification-requests.md)
>
> 键的工作方式和有效期。

> [card] [中断级别](https://documentation.onesignal.com/docs/cn/ios-focus-modes-and-interruption-levels.md)
>
> 专注模式和四种级别。

> [card] [角标](https://documentation.onesignal.com/docs/cn/badges.md)
>
> 各平台的角标行为。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.