> ## 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経由で送信する6種類のプッシュ通知。

このページは、1つの実在アプリを最初から最後まで追う[サンプルアプリ：OneSignalの完全な統合](https://documentation.onesignal.com/docs/ja/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で送信先を指定します。

| プッシュ | 送信タイミング | トリガー |
| - | - | - |
| デイリーダイジェスト | ユーザーが選んだ時刻に、期限のタスクがある場合 | 1時間ごとのスケジュール |
| 期限切れリマインダー | ダイジェストの6時間後に、まだ期限切れのタスクがある場合 | 1時間ごとのスケジュール |
| 掃除リマインダー | ユーザーの掃除時間帯の1時間前 | 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時間ごとに1つのジョブを実行し、「今がその時刻に当たるのは誰か」を判定します。

**1. データベースのスケジュールが1時間ごとに関数を呼び出す**

`pg_cron`がSupabase Edge FunctionにHTTPリクエストを送ります。必要なサービスキーはSupabase Vaultから読み取るため、SQLに現れることはありません。

**2. 関数がローカル時刻の一致するユーザーを見つける**

そのリマインダーをオンにしている全員を読み込み、現在時刻を各ユーザーのタイムゾーンに変換し、選択した時刻が今であるユーザーを残します。

**3. 伝える内容があるか確認する**

期限のタスクがないユーザーにはプッシュを送りません。

**4. ユーザーごとにOneSignalを1回呼び出す**

各プッシュの内容は異なるため、それぞれ個別のリクエストになります。

スケジュール：

```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/ja/example-full-integration-reliable-push.md)で説明しています。`data.type`フィールドにより、アプリはプッシュがタップされたときにどの画面を開くかを判断します。[ディープリンクと通知のクリック](https://documentation.onesignal.com/docs/ja/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 };
}
```

## 期限切れリマインダー：2回目の、異なる後押し \\

期限切れリマインダーは同じパターンを2点だけ変えて再利用します。ユーザーのダイジェスト時刻の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分に実行されるため、毎時0分のダイジェストのジョブと重なることはありません。文面も変えています。1回目を繰り返すだけの2回目のリマインダーは見過ごされやすいからです。

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

## 掃除リマインダー：多数のユーザーに1回のリクエスト \\

掃除リマインダーは全員に同じ内容を伝えるため、1人ずつリクエストする必要はありません。関数は対象となるすべてのユーザー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]
>
> 内容が異なる場合は1人につき1回リクエストします。内容が同じ場合は多数のユーザーに1回のリクエストで送ります。リクエストが少ないほど失敗する箇所が減り、レート制限にも収まりやすくなります。

## セッション完了：アプリからトリガーされるプッシュ \\

誰かが掃除セッションを終えると、世帯のほかのメンバーに通知されます。アプリは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);
```

全員に1つのプッシュを送信します。送信者の豆のアバターは画像として添付し、プラットフォームごとに異なるフィールドを使います。

```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も同じ仕組みで、受信者が1人だけです。アクティビティ画面でメンバーが同居人のセッションの**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 | サインイン中のユーザー本人 | 送信者はリクエスト本文ではなく必ずトークンから取得する |

スケジュールされた関数は、次の1行から始まります。

```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/ja/rich-media.md)
>
> 各プラットフォームでのプッシュ通知の画像。


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