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

# 예제 앱: 백엔드에서 푸시 보내기

> Create message API를 사용해 일정, 앱, 데이터베이스 트리거에서 Supabase Edge Functions로 보내는 여섯 가지 푸시 알림입니다.

이 페이지는 실제 앱 하나를 처음부터 끝까지 따라가는 [예제 앱: OneSignal 전체 통합](https://documentation.onesignal.com/docs/ko/example-full-integration-overview.md)의 일부입니다. 앱은 공유 주택을 위한 청소 당번표 앱인 **Clean Beans**이며, Expo(React Native)와 Supabase 백엔드로 만들어졌습니다.

Clean Beans의 알림 대부분은 일정이나 다른 사람의 행동에 따라 달라지므로 백엔드에서 보냅니다. 모두 같은 엔드포인트인 [Create message](https://documentation.onesignal.com/reference/create-message.md)를 호출하며 External ID로 사람을 지정합니다.

| 푸시 | 전송 시점 | 트리거 |
| - | - | - |
| 일일 요약 | 사용자가 선택한 시간, 해야 할 작업이 있는 경우 | 매시간 일정 |
| 기한 초과 알림 | 요약 6시간 후, 여전히 기한이 지난 작업이 있는 경우 | 매시간 일정 |
| 청소 알림 | 사용자의 청소 시간대 1시간 전 | 매시간 일정 |
| 세션 완료 | 하우스메이트가 청소를 마쳤을 때 | 앱에서 호출 |
| Kudos | 하우스메이트가 kudos를 보냈을 때 | 앱에서 호출 |
| 가입 승인 | 관리자가 가입 요청을 승인했을 때 | 데이터베이스 트리거 |

![Clean Beans 푸시 알림](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-push-examples.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=f26bc81be159fba77a9873e119ccb19e)

Clean Beans가 보내는 푸시의 예.

## 시간대를 고려한 예약 전송 \\

사람들은 일일 알림을 받을 시간을 직접 선택합니다. Clean Beans는 사용자마다 작업을 예약하지 않습니다. 매시간 하나의 작업을 실행하며 "지금이 그 시간인 사람은 누구인가?"를 확인합니다.

**1. 데이터베이스 일정이 매시간 함수를 호출합니다**

`pg_cron`이 Supabase Edge Function에 HTTP 요청을 보냅니다. 필요한 서비스 키는 Supabase Vault에서 읽으므로 SQL에 나타나지 않습니다.

**2. 함수가 현지 시간이 일치하는 사용자를 찾습니다**

해당 알림을 켠 모든 사람을 불러와 현재 시간을 각 사용자의 시간대로 변환하고, 선택한 시간이 지금인 사람만 남깁니다.

**3. 전할 내용이 있는지 확인합니다**

해야 할 작업이 없는 사용자에게는 푸시를 보내지 않습니다.

**4. 사용자마다 OneSignal을 한 번씩 호출합니다**

푸시마다 내용이 다르므로 각각 별도의 요청입니다.

일정:

```sql supabase/migrations/006_cron_daily_digest.sql theme={null}
select cron.schedule(
  'send-daily-digest',          -- job name
  '0 * * * *',                  -- every hour at :00
  $$
  select
    net.http_post(
      url := 'https://YOUR_PROJECT_REF.supabase.co/functions/v1/send-daily-digest',
      headers := jsonb_build_object(
        'Content-Type', 'application/json',
        'Authorization', 'Bearer ' || (select decrypted_secret from vault.decrypted_secrets where name = 'service_role_key')
      ),
      body := '{}'::jsonb
    );
  $$
);
```

시간대 일치:

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
for (const profile of profiles) {
  try {
    // Get current hour in user's timezone
    const localHour = parseInt(
      now.toLocaleString('en-US', {
        timeZone: profile.timezone || 'UTC',
        hour: 'numeric',
        hour12: false,
      }),
      10
    );

    if (localHour === profile.notification_hour) {
      eligibleUsers.push({
        id: profile.id,
        householdId: profile.household_id,
        localDate: localDate(now, profile.timezone || 'UTC'),
      });
    }
  } catch {
    // Invalid timezone — skip this user
    console.warn(`Invalid timezone for user ${profile.id}: ${profile.timezone}`);
  }
}
```

전송:

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
const onesignalPayload = {
  app_id: ONESIGNAL_APP_ID,
  // One digest per user per local day: a retried or duplicated cron
  // run reuses this key and OneSignal will not send it twice.
  idempotency_key: await idempotencyKey('daily_digest', digest.userId, digest.localDate),
  include_aliases: {
    external_id: [digest.userId],
  },
  target_channel: 'push',
  ...DELIVERY.daily_digest,
  headings: { en: heading },
  contents: { en: body },
  url: 'cleaning-rota:///(tabs)/clean',
  // App icon badge = number of tasks due. The OneSignal SDK clears the
  // badge automatically the next time the app is opened.
  ios_badgeType: 'SetTo',
  ios_badgeCount: digest.tasks.length,
  // Action buttons, revealed by expanding the notification
  buttons: TASK_BUTTONS,
  data: { type: 'daily_digest', taskCount: String(digest.tasks.length) },
};

const res = await fetch('https://api.onesignal.com/notifications', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Key ${ONESIGNAL_REST_API_KEY}`,
  },
  body: JSON.stringify(onesignalPayload),
});
```

`...DELIVERY.daily_digest`, `idempotency_key`, 배지 필드는 [안정적이고 올바르게 동작하는 푸시](https://documentation.onesignal.com/docs/ko/example-full-integration-reliable-push.md)에서 설명합니다. `data.type` 필드는 푸시를 탭했을 때 앱이 어떤 화면을 열지 판단하는 방법입니다. [딥 링크 및 알림 클릭](https://documentation.onesignal.com/docs/ko/example-full-integration-deep-links.md)을 참조하세요.

제목과 본문은 작업을 바탕으로 만들어지므로 푸시가 구체적인 내용을 전달합니다.

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
function buildDigestContent(tasks: TaskRow[]): { heading: string; body: string } {
  const count = tasks.length;
  const heading = count === 1
    ? '1 cleaning task due today'
    : `${count} cleaning tasks due today`;

  // Collect unique room names
  const rooms = [...new Set(tasks.map(t => t.room_name))];

  let body: string;
  if (rooms.length === 1) {
    body = `Your ${rooms[0]} needs some attention!`;
  } else if (rooms.length === 2) {
    body = `Your ${rooms[0]} and ${rooms[1]} need some attention!`;
  } else {
    const last = rooms.pop()!;
    body = `Your ${rooms.join(', ')}, and ${last} need some attention!`;
  }

  return { heading, body };
}
```

## 기한 초과 알림: 두 번째, 다른 방식의 알림 \\

기한 초과 알림은 같은 패턴을 두 가지만 바꿔 재사용합니다. 사용자의 요약 시간 6시간 후에 실행되며, 기한이 확실히 지난 작업만 셉니다.

```typescript supabase/functions/send-overdue-reminders/index.ts theme={null}
// Overdue hour wraps around midnight
const overdueHour = (profile.notification_hour + OVERDUE_OFFSET_HOURS) % 24;

if (localHour === overdueHour) {
  eligibleUsers.push({
    id: profile.id,
    householdId: profile.household_id,
    localDate: localDate(now, profile.timezone || 'UTC'),
  });
}
```

이 작업은 매시 30분에 실행되므로 정각에 실행되는 요약 작업과 겹치지 않습니다. 문구도 다릅니다. 첫 번째 알림을 반복하는 두 번째 알림은 무시하기 쉽기 때문입니다.

```typescript supabase/functions/send-overdue-reminders/index.ts theme={null}
function buildOverdueContent(tasks: TaskRow[]): { heading: string; body: string } {
  const count = tasks.length;
  const heading = count === 1
    ? '1 overdue task still waiting'
    : `${count} overdue tasks still waiting`;

  const rooms = [...new Set(tasks.map((t) => t.room_name))];

  let body: string;
  if (rooms.length === 1) {
    body = `Your ${rooms[0]} still needs some love today!`;
  } else if (rooms.length === 2) {
    body = `Your ${rooms[0]} and ${rooms[1]} still need some love today!`;
  } else {
    const last = rooms.pop()!;
    body = `Your ${rooms.join(', ')}, and ${last} still need some love today!`;
  }

  return { heading, body };
}
```

## 청소 알림: 여러 사람에게 한 번의 요청 \\

청소 알림은 모두에게 같은 내용을 전하므로 사람마다 요청할 필요가 없습니다. 함수는 대상이 되는 모든 사용자 ID를 모아 배치로 보냅니다.

```typescript supabase/functions/send-cleaning-reminder/index.ts theme={null}
const batchSize = 2000;
for (let i = 0; i < eligibleUserIds.length; i += batchSize) {
  const batch = eligibleUserIds.slice(i, i + batchSize);

  // One reminder per batch of recipients per hourly cron slot: a retried
  // or duplicated run in the same hour reuses this key and OneSignal
  // will not send it twice.
  const batchKey = await idempotencyKey(
    'upcoming_cleaning',
    utcHourSlot(now),
    [...batch].sort().join(','),
  );

  const onesignalPayload = {
    app_id: ONESIGNAL_APP_ID,
    idempotency_key: batchKey,
    include_aliases: {
      external_id: batch,
    },
    target_channel: 'push',
    ...DELIVERY.upcoming_cleaning,
    headings: { en: 'Cleaning time in 1 hour' },
    contents: {
      en: 'Your cleaning window starts soon. Ready to get things sparkling?',
    },
    url: 'cleaning-rota:///(tabs)/clean',
    data: { type: 'upcoming_cleaning' },
  };
```

> [!TIP]
>
> 내용이 다르면 사람마다 요청을 하나씩 보내세요. 내용이 같으면 여러 사람에게 요청 하나로 보내세요. 요청이 적을수록 실패할 곳이 줄고 속도 제한도 지키기 쉽습니다.

## 세션 완료: 앱에서 트리거되는 푸시 \\

누군가 청소 세션을 마치면 가구의 나머지 구성원에게 알려집니다. 앱은 API 키를 가지고 있으면 안 되므로 이 푸시를 직접 보낼 수 없습니다. 대신 백엔드 함수를 호출하고, 그 함수가 푸시를 보냅니다.

```typescript src/lib/database.ts theme={null}
const { error } = await supabase.functions.invoke('session-completed', {
  body: {
    householdId,
    roomName: params.roomName,
    tasksCompleted: params.tasksCompleted,
    estimatedMins: params.estimatedMins,
  },
});
```

요청에는 무엇을 청소했는지는 있지만 누가 청소했는지는 없습니다. 함수는 로그인 토큰으로 호출자를 확인하고, 가구의 활성 구성원인지 확인한 다음, 프로필에서 이름과 아바타를 가져옵니다. [호출자 확인하기](#check-who-is-calling)를 참조하세요.

그런 다음 가구의 다른 구성원을 찾고, 이 유형의 푸시를 끈 사람을 제외합니다.

```typescript supabase/functions/session-completed/index.ts theme={null}
// ── 1. Look up other active household members ──

const { data: members, error: memberErr } = await supabase
  .from('household_members')
  .select('user_id')
  .eq('household_id', householdId)
  .eq('status', 'active')
  .neq('user_id', userId);

    // ...

const { data: profiles, error: profileErr } = await supabase
  .from('profiles')
  .select('id, notifications_enabled, push_cleaning_done')
  .in('id', recipientIds)
  .eq('notifications_enabled', true)
  .eq('push_cleaning_done', true);
```

모두에게 푸시 하나를 보냅니다. 보낸 사람의 콩 아바타는 플랫폼마다 다른 필드를 사용해 이미지로 첨부합니다.

```typescript supabase/functions/session-completed/index.ts theme={null}
const onesignalPayload: Record<string, unknown> = {
  app_id: ONESIGNAL_APP_ID,
  include_aliases: {
    external_id: enabledIds,
  },
  target_channel: 'push',
  ...DELIVERY.session_completed,
  headings: { en: heading },
  contents: { en: body },
  url: 'cleaning-rota:///activity',
  data: {
    type: 'session_completed',
    roomName,
    userName,
    tasksCompleted: String(tasksCompleted),
    // Who cleaned: lets the "Send kudos" button reply to the right person
    ...(isRealUser ? { cleanerId: userId } : {}),
  },
  // "Send kudos" needs a real person to send to
  ...(isRealUser ? { buttons: SESSION_BUTTONS } : {}),
};

// Attach avatar image for rich push notifications
if (avatarImageUrl) {
  onesignalPayload.big_picture = avatarImageUrl;          // Android
  onesignalPayload.ios_attachments = { avatar: avatarImageUrl }; // iOS
}
```

![콩 아바타 이미지가 보이는 펼친 푸시 알림](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-rich-push.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=07c38920b20cb73093805ca9961841e3)

보낸 사람의 아바타가 보이도록 펼친 세션 완료 푸시.

## Kudos: 한 사람에서 다른 사람에게 \\

Kudos도 같은 방식으로 동작하며 수신자가 한 명입니다. 활동 화면에서 구성원이 하우스메이트의 세션에 있는 **Send Kudos**를 탭하고 메시지를 고르면, 앱이 `send-kudos` 함수를 호출합니다.

![미리 설정된 메시지가 있는 kudos 하단 시트](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-kudos.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=83ec608d61e91c74f16bcb65d8757927)

하우스메이트의 청소 세션에 보낼 kudos 메시지 고르기.

```typescript supabase/functions/send-kudos/index.ts theme={null}
const heading = `Kudos from ${senderName}!`;
const body = message;

    // ...

const onesignalPayload: Record<string, unknown> = {
  app_id: ONESIGNAL_APP_ID,
  include_aliases: {
    external_id: [recipientUserId],
  },
  target_channel: 'push',
  ...DELIVERY.kudos,
  headings: { en: heading },
  contents: { en: body },
  url: 'cleaning-rota:///activity',
  data: {
    type: 'kudos',
    senderName,
    roomName: roomName || '',
  },
};
```

## 가입 승인: 데이터베이스에서 트리거되는 푸시 \\

가구에 가입을 요청한 사람은 관리자의 승인을 기다립니다. 승인되면 해당 구성원 행이 `pending`에서 `active`로 바뀝니다. 이 변경에 걸린 데이터베이스 트리거가 함수를 호출하고, 함수가 가입되었다고 알려줍니다.

트리거를 데이터베이스에 두면 승인이 어떤 방식으로 이루어지든 푸시가 전송되며, 앱에는 이를 위한 코드가 필요 없습니다.

```sql supabase/migrations/027_join_approved_trigger.sql theme={null}
create trigger trg_notify_join_approved
  after update of status on public.household_members
  for each row
  when (old.status = 'pending' and new.status = 'active')
  execute function public.notify_join_approved();
```

함수는 전달받은 내용을 그대로 믿지 않습니다. 구성원 정보를 다시 읽고, 승인이 실제이며 최근인 경우에만 보냅니다.

```typescript supabase/functions/join-approved/index.ts theme={null}
// ── 1. Confirm the membership really was approved, and recently ──

const { data: membership, error: memberErr } = await supabase
  .from('household_members')
  .select('status, joined_at, households(name)')
  .eq('user_id', userId)
  .eq('household_id', householdId)
  .maybeSingle();

if (memberErr) throw memberErr;

if (!membership || membership.status !== 'active' || !membership.joined_at) {
  return jsonResponse({ sent: 0, message: 'No active membership found' });
}

const joinedAt = new Date(membership.joined_at).getTime();
if (Date.now() - joinedAt > RECENT_APPROVAL_MS) {
  return jsonResponse({ sent: 0, message: 'Membership was not approved recently' });
}
```

> [!WARNING]
>
> 요청에 따라 메시지를 보내는 함수는 다른 사람이 호출을 시도할 수 있는 대상입니다. 이 함수처럼 보내기 전에 자체 데이터베이스에서 사실을 확인하고, 검증하지 않은 호출자로부터 메시지 내용이나 수신자를 받지 마세요.

## 호출자 확인하기 \\

Supabase는 edge function에 대한 요청에 유효한 토큰이 있는지 확인하지만, 로그인한 사용자의 토큰도 스케줄러의 토큰만큼 유효합니다. 추가 확인이 없다면 어떤 사용자든 모든 사람의 일일 요약을 트리거하거나 다른 사람의 이름으로 푸시를 보낼 수 있습니다. 따라서 각 함수가 누가 호출할 수 있는지 스스로 판단합니다.

| 함수 | 호출할 수 있는 사람 | 확인 |
| - | - | - |
| 예약 전송 및 데이터베이스 트리거 | 스케줄러만 | 토큰이 service role 키여야 함 |
| 세션 완료, kudos | 로그인한 사용자 본인 | 보낸 사람은 요청 본문이 아닌 토큰에서 가져옴 |

예약된 함수는 다음 한 줄로 시작합니다.

```typescript supabase/functions/send-daily-digest/index.ts theme={null}
// Only the scheduler (service role) may run this
const denied = requireServiceRole(req);
if (denied) return denied;
```

```typescript supabase/functions/_shared/auth.ts theme={null}
export function isServiceRoleRequest(req: Request): boolean {
  const token = bearerToken(req);
  if (!token) return false;
  if (token === Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')) return true;

  try {
    const part = token.split('.')[1] ?? '';
    const base64 = part.replace(/-/g, '+').replace(/_/g, '/');
    const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
    const claims = JSON.parse(atob(padded));
    return claims?.role === 'service_role';
  } catch {
    return false;
  }
}
```

> [!WARNING]
>
> 역할 확인은 Supabase가 이미 토큰의 서명을 검증했다는 전제에 의존합니다. 기본값인 JWT 검증을 켠 상태로 이 함수들을 배포하세요. `--no-verify-jwt`로 배포하면 안 됩니다.

앱에서 호출하는 함수는 토큰으로 보낸 사람을 식별한 다음, 그 사람이 수신자에게 보낼 수 있는지 확인합니다. Kudos는 보낸 사람과 같은 가구에 속한 사람에게만 보낼 수 있으며, 푸시에 표시되는 이름은 보낸 사람의 프로필에서 읽습니다.

```typescript supabase/functions/send-kudos/index.ts theme={null}
const caller = await authenticateUser(req, supabase);
if (caller instanceof Response) return caller;

// ...

// Sender and recipient must be active members of the same household
const { data: memberships, error: memberErr } = await supabase
  .from('household_members')
  .select('user_id, household_id')
  .in('user_id', [caller.id, recipientUserId])
  .eq('status', 'active');

if (memberErr) throw memberErr;

const callerHouseholds = new Set(
  (memberships ?? []).filter((m) => m.user_id === caller.id).map((m) => m.household_id),
);
const sharesHousehold = (memberships ?? []).some(
  (m) => m.user_id === recipientUserId && callerHouseholds.has(m.household_id),
);

if (!sharesHousehold) {
  return jsonResponse({ error: 'forbidden', message: 'You can only send kudos to members of your household.' }, 403);
}
```

> [card] [Create message API](https://documentation.onesignal.com/reference/create-message.md)
>
> 모든 채널의 타겟팅, 콘텐츠, 예약.

> [card] [리치 미디어](https://documentation.onesignal.com/docs/ko/rich-media.md)
>
> 플랫폼별 푸시 알림 이미지.


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