> ## 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.

# 示例应用：使用 Event Streams 的通知收件箱

> 示例应用 Clean Beans 如何基于 Event Streams 构建应用内通知收件箱，并让邮件偏好与退订保持一致。

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

被划掉的推送就消失了。Clean Beans 在应用内保留七天的历史记录，并在每个界面的标题栏中显示未读数量。

![Clean Beans 通知收件箱](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-inbox.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=b5e476387dfc0b32a56d71201879c0d0)

收件箱列出最近的通知。

应用本身不记录通知。那样会漏掉应用关闭期间送达的所有内容。OneSignal 通过 **Event Stream** 将每条推送告知后端，由后端保存历史记录。

**1. OneSignal 为每条推送发送一个事件**

Event Stream 会在推送发送时以及被点击时，向后端函数发送 POST 请求。

**2. 函数存储或更新一行记录**

发送事件会创建一条收件箱记录。点击事件会将其标记为已读。

**3. 应用读取数据表**

收件箱界面和标题栏角标会查询用户自己的记录。

## 配置 Event Stream \\

**仪表板设置。** 在 **Data > Event Streams** 中创建一个 stream，并设置：

* **URL：** 您的函数地址。
* **请求头：** 一个共享密钥，例如 `X-Webhook-Secret`。
* **事件：** `message.push.sent` 和 `message.push.clicked`。
* **正文：** 用于构造请求的 Liquid 模板。

```json Event Stream body theme={null}
{
  "event_kind": "{{ event.kind }}",
  "event_id": "{{ event.id }}",
  "timestamp": {{ event.timestamp }},
  "external_id": "{{ event.external_id }}",
  "message_id": "{{ message.id }}",
  "title": "{{ message.title.en }}",
  "contents": "{{ message.contents.en }}",
  "data": { "type": "{{ message.data.type }}" }
}
```

> [!WARNING]
>
> 请像上面这样按名称引用每个 `data` 键。单独使用 `{{ message.data }}` 会把整个对象渲染为 Python 风格的 dict（`{'type': 'kudos'}`），这不是有效的 JSON，下面的函数在解析正文时会拒绝该请求。标题和内容使用 `.en` 读取也是同样的原因。收件箱只需要 `type`。如果您自己的 Webhook 还使用其他键，请逐行添加。
>
> 包含双引号的值同样会破坏 JSON。Kudos 推送包含用户输入的文本，因此带有 `"` 的 kudos 消息会生成函数无法解析的正文，该推送也就不会进入收件箱。

> [!NOTE]
>
> 此 stream 会为投递到每台设备的每条推送发送一个事件，每个事件都会计入您套餐的消息事件量。请只选择您需要的事件。

## 接收事件 \\

函数在执行任何其他操作之前先检查密钥。

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
const secret = req.headers.get('X-Webhook-Secret') ?? '';
if (!INBOX_WEBHOOK_SECRET || secret !== INBOX_WEBHOOK_SECRET) {
  return new Response('Unauthorized', { status: 401 });
}
```

发送事件会成为收件箱中的一行。OneSignal 的事件 ID 是唯一键，因此同一事件即使送达两次也不会创建两行。

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
if (event_kind === 'message.push.sent') {
  // ── Create inbox entry ──
  const notifType = (data?.type as string) || 'general';

  // inboxTitle and inboxBody are the title and contents with any Liquid
  // rendered. See "Render Liquid before you store it" below.

  const { error } = await supabase.from('inbox_messages').upsert(
    {
      user_id: profile.id,
      onesignal_event_id: event_id,
      onesignal_message_id: message_id,
      title: inboxTitle || 'Notification',
      body: inboxBody,
      type: notifType,
      data: data || {},
      read: false,
      created_at: payload.timestamp
        ? new Date(payload.timestamp * 1000).toISOString()
        : new Date().toISOString(),
    },
    { onConflict: 'onesignal_event_id' } // dedup
  );
```

点击事件会将对应的行标记为已读。

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
const { error, count } = await supabase
  .from('inbox_messages')
  .update({ read: true })
  .eq('onesignal_message_id', message_id)
  .eq('user_id', profile.id);
```

用于路由被点击推送的 `data.type` 字段也会随每一行存储，因此收件箱可以显示正确的图标并打开正确的界面。

## 存储前先渲染 Liquid \\

stream 报告的是消息的原始写法，即 OneSignal 为每位收件人个性化之前的内容。由后端发送的推送已经是最终文本，Journey 推送则不是。Clean Beans 的一条 Journey 消息使用以下标题：

```text Journey push title theme={null}
{{ journey.first_event.properties.room_name }} cleaned ✅
```

手机上显示的是“Kitchen cleaned ✅”。Webhook 收到的却是上面那一行，收件箱的第一个版本就原样显示了它。

现在，函数会在保存之前自行渲染标题和正文，使用一个支持取值和 `default` 过滤器的小型渲染器。它从两个地方获取值：

* **标签**从数据库中读取。应用根据其存储的值设置每个标签，因此函数读取的是相同的值。在 stream 正文中传入 `{{ user.tags.user_name }}` 也可行，但如果名字中包含双引号，正文就会变成无效的 JSON。
* **Journey 事件属性**在 stream 中不可用。函数会根据触发该自定义事件的打扫会话重新构建它们。

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
if (hasLiquid(inboxTitle) || hasLiquid(inboxBody)) {
  const context = await buildLiquidContext(supabase, payload);
  const renderedTitle = renderLiquid(inboxTitle, context);
  const renderedBody = renderLiquid(inboxBody, context);
  const unresolved = [...renderedTitle.unresolved, ...renderedBody.unresolved];

  if (unresolved.length > 0) {
    // Better no entry than one showing raw template tags
    console.warn(`Inbox: skipped ${message_id} for ${external_id}, unresolved Liquid: ${JSON.stringify(unresolved)}`);
    return jsonResponse({ skipped: true, reason: 'unresolved_liquid', unresolved });
  }

  inboxTitle = renderedTitle.text;
  inboxBody = renderedBody.text;
}
```

> [!WARNING]
>
> 如果您基于 Event Streams 构建收件箱或日志，请检查 Journey 和模板消息到达时的样子。其中的 Liquid 仍然是 Liquid。要么像这里一样自行渲染，要么排除这些消息。

## 显示收件箱 \\

行级安全机制确保每位用户只能读取自己的行，因此应用的查询无需按用户筛选。

```typescript app/inbox.tsx theme={null}
const { data, error } = await supabase
  .from('inbox_messages')
  .select('id, title, body, type, data, read, created_at')
  .order('created_at', { ascending: false })
  .limit(50);
```

```typescript src/components/InboxButton.tsx theme={null}
const fetchCount = async () => {
  const { count, error } = await supabase
    .from('inbox_messages')
    .select('id', { count: 'exact', head: true })
    .eq('read', false);

  if (!cancelled && !error && count !== null) {
    setUnreadCount(count);
  }
};
```

## 让邮件偏好保持一致 \\

同一个 stream 还能解决第二个问题。当有人点击邮件中的 **Unsubscribe** 时，OneSignal 会停止向其发送邮件，但应用自己的“Weekly Email Summary”开关仍处于开启状态。设置界面会显示错误的状态，后端也会继续尝试发送。

在 stream 中添加四个邮件事件即可解决这个问题。函数以相同方式处理所有这些事件：OneSignal 不会再给此人发送邮件，因此应用偏好也会相应关闭。

```typescript supabase/functions/inbox-webhook/index.ts theme={null}
const EMAIL_STOP_EVENTS: Record<string, string> = {
  'message.email.unsubscribed': 'unsubscribed',
  'message.email.reported_as_spam': 'reported_as_spam',
  'message.email.bounced': 'bounced',
  'message.email.suppressed': 'suppressed',
};

// ...

const { error: prefErr } = await supabase
  .from('profiles')
  .update({ email_weekly_summary: false })
  .eq('id', profile.id);
```

无需更改 stream 的正文，因为收件箱已经使用的字段（`event_kind`、`event_id`、`external_id`）就足够了。

> [!NOTE]
>
> 这会让应用与 OneSignal 保持一致，而不是反过来。如果有人在应用中重新开启邮件，其 OneSignal 订阅仍处于退订状态。要重新订阅，需要由您的后端调用 OneSignal 的订阅 API。

> [!TIP]
>
> 同样的 Event Stream 模式可以让您自己的系统与 OneSignal 掌握的任何信息保持同步：邮件打开、应用内消息点击、短信送达等。

> [card] [Event Streams](https://documentation.onesignal.com/docs/cn/event-streams.md)
>
> 设置 stream 并选择事件。

> [card] [Event Stream 数据](https://documentation.onesignal.com/docs/cn/event-streams-data.md)
>
> 正文模板中可用的所有字段。


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