> ## 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/ko/example-full-integration-overview.md)의 일부입니다. 앱은 공유 주택을 위한 청소 당번표 앱인 **Clean Beans**이며, Expo(React Native)와 Supabase 백엔드로 만들어졌습니다.

밀어서 지운 푸시는 사라집니다. Clean Beans는 앱 안에 7일간의 기록을 보관하며, 모든 화면의 헤더에 읽지 않은 수를 표시합니다.

![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**에서 다음과 같이 스트림을 만드세요.

* **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`만 필요합니다. 자체 웹훅에서 사용하는 다른 키는 한 줄씩 추가하세요.
>
> 큰따옴표가 포함된 값도 JSON을 깨뜨립니다. Kudos 푸시에는 사용자가 입력한 텍스트가 들어 있으므로, `"`가 포함된 kudos 메시지는 함수가 파싱할 수 없는 본문을 만들고 그 푸시는 수신함에 도달하지 않습니다.

> [!NOTE]
>
> 이 스트림은 모든 기기에 전달된 모든 푸시마다 이벤트를 하나씩 보내며, 각 이벤트는 요금제의 메시지 이벤트 사용량에 포함됩니다. 사용하는 이벤트만 선택하세요.

## 이벤트 받기 \\

함수는 다른 작업보다 먼저 시크릿을 확인합니다.

```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 렌더링하기 \\

스트림은 OneSignal이 수신자별로 개인화하기 전, 작성된 그대로의 메시지를 보고합니다. 백엔드에서 보낸 푸시는 이미 최종 텍스트를 가지고 있지만, Journey 푸시는 그렇지 않습니다. Clean Beans의 Journey 메시지 중 하나는 다음 제목을 사용합니다.

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

휴대폰에는 "Kitchen cleaned ✅"가 표시됩니다. 웹훅은 위의 줄을 받으며, 수신함의 첫 번째 버전은 이를 그대로 표시했습니다.

이제 함수는 값 조회와 `default` 필터를 처리하는 작은 렌더러로 제목과 본문을 저장하기 전에 직접 렌더링합니다. 값은 두 곳에서 가져옵니다.

* **태그**는 데이터베이스에서 읽습니다. 앱은 저장해 둔 값으로 각 태그를 설정하므로 함수는 같은 값을 읽습니다. 스트림 본문에 `{{ user.tags.user_name }}`을 전달하는 방법도 동작하지만, 이름에 큰따옴표가 있으면 본문이 유효하지 않은 JSON이 됩니다.
* **Journey 이벤트 속성**은 스트림에서 사용할 수 없습니다. 함수는 커스텀 이벤트를 발생시킨 청소 세션에서 이를 다시 구성합니다.

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

## 이메일 설정 동기화하기 \\

같은 스트림으로 두 번째 문제도 해결할 수 있습니다. 누군가 이메일에서 **Unsubscribe**를 탭하면 OneSignal은 그 사람에게 이메일 보내기를 중단하지만, 앱 자체의 "Weekly Email Summary" 스위치는 여전히 켜져 있습니다. 설정 화면이 틀리게 되고, 백엔드는 계속 전송을 시도합니다.

스트림에 이메일 이벤트 네 가지를 추가하면 이 문제가 해결됩니다. 함수는 이들을 모두 같은 방식으로 처리합니다. 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);
```

수신함이 이미 사용하는 필드(`event_kind`, `event_id`, `external_id`)로 충분하므로 스트림 본문을 바꿀 필요가 없습니다.

> [!NOTE]
>
> 이는 앱을 OneSignal에 맞추는 것이지 그 반대가 아닙니다. 누군가 앱에서 이메일을 다시 켜도 OneSignal 구독은 여전히 수신 거부 상태입니다. 다시 구독시키려면 백엔드에서 OneSignal의 구독 API를 호출해야 합니다.

> [!TIP]
>
> 같은 Event Stream 패턴으로 이메일 열람, 인앱 메시지 클릭, SMS 전송 등 OneSignal이 아는 모든 정보와 자체 시스템을 동기화할 수 있습니다.

> [card] [Event Streams](https://documentation.onesignal.com/docs/ko/event-streams.md)
>
> 스트림을 설정하고 이벤트를 선택하세요.

> [card] [Event Stream 데이터](https://documentation.onesignal.com/docs/ko/event-streams-data.md)
>
> 본문 템플릿에서 사용할 수 있는 모든 필드.


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