> ## 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/cn/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 定向用户。

| 推送 | 发送时机 | 触发条件 |
| - | - | - |
| 每日摘要 | 在用户选择的时间，如果有到期任务 | 每小时计划任务 |
| 逾期提醒 | 摘要后六小时，如果任务仍然逾期 | 每小时计划任务 |
| 打扫提醒 | 用户打扫时段开始前一小时 | 每小时计划任务 |
| 会话完成 | 室友完成打扫 | 从应用调用 |
| 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/cn/example-full-integration-reliable-push.md)中有说明。`data.type` 字段用于让应用知道点击推送时应打开哪个界面。请参阅[深度链接和通知点击](https://documentation.onesignal.com/docs/cn/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 };
}
```

## 逾期提醒：第二次、不一样的提醒 \\

逾期提醒沿用同样的模式，只有两处不同。它在用户的摘要时间之后六小时触发，并且只统计确实已过期的任务。

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

它的任务在每小时的半点运行，因此不会与整点运行的摘要任务冲突。文案也不同。重复第一条内容的第二条提醒很容易被忽略。

```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/cn/rich-media.md)
>
> 各平台推送通知中的图片。


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