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

# 示例应用：深度链接和通知点击

> 示例应用 Clean Beans 如何将点击的推送路由到正确的界面、处理操作按钮和稍后提醒，并通过 Universal Links 打开应用。

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

只有点击后能把您带到正确位置，通知才有用。Clean Beans 处理四种进入应用的方式：点击推送、点击推送上的按钮、自定义 scheme 链接，以及普通网页链接。

## 路由被点击的推送 \\

每条推送都带有 `data.type` 字段。应用监听点击，读取类型，然后打开对应的界面。

```typescript app/_layout.tsx theme={null}
OneSignal.Notifications.addEventListener('click', (event: NotificationClickEvent) => {
  const data = event.notification.additionalData as Record<string, string> | undefined;
  if (!data?.type) return;

  // Mark inbox message as read (best-effort, fire-and-forget)
  const notificationId = event.notification.notificationId;
  if (notificationId) {
    supabase
      .from('inbox_messages')
      .update({ read: true })
      .eq('onesignal_message_id', notificationId)
      .then();
  }

  // Small delay to let the app finish initialising if cold-launched
  setTimeout(() => {
    // A tap on an action button ("Snooze 1h", "Send kudos", ...) carries an
    // actionId. A tap on the notification itself does not.
    const action = handlePushAction(event.result.actionId, data);
    if (action.handled) {
      if (action.route) router.push(action.route as any);
      return;
    }

    switch (data.type) {
      case 'daily_digest':
      case 'upcoming_cleaning':
      case 'overdue_reminder':
      case 'reengagement':
        router.push('/(tabs)/clean');
        break;
      case 'session_completed':
      case 'kudos':
        router.push('/activity');
        break;
      case 'join_approved':
      case 'member_lapsed':
        router.push('/household');
        break;
      default:
        break;
    }
  }, 500);
});
```

| `data.type` | 打开 |
| - | - |
| `daily_digest`、`overdue_reminder`、`upcoming_cleaning` | Clean 标签页 |
| `session_completed`、`kudos` | 动态信息流 |
| `join_approved`、`member_lapsed` | 家庭界面 |
| `reengagement` | Clean 标签页 |

其中两种类型来自 Journeys，本指南不涉及。`reengagement` 设置在仪表板中构建的召回 Journey 的推送上。`member_lapsed` 是发给家庭所有者和管理员的推送，当该 Journey 报告某位成员已停止打扫时由后端发送。它们和其他推送一样在这里路由。

> [!TIP]
>
> 按您自己控制的类型路由比解析 URL 更可靠。如果某个界面移动了，您只需修改一处 `switch` 语句，变更前发送的所有推送仍能正确打开。

## 操作按钮：可点击的不止一处 \\

推送可以带有按钮。任务推送提供 **Start cleaning** 和 **Snooze 1h**，“室友完成打扫”推送提供 **Send kudos**。用户展开通知即可看到按钮，在 iOS 上需要长按。

![带有 Start cleaning 和 Snooze 1h 按钮的展开推送通知](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-action-buttons.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=0a850d439deea8f483c8dfe532fb8e93)

展开后带有两个操作按钮的提醒。

后端将按钮添加到请求中。每个按钮都有一个 `id` 和一个标签。

```typescript supabase/functions/_shared/buttons.ts theme={null}
export const TASK_BUTTONS = [
  { id: ACTION_START_CLEANING, text: 'Start cleaning' },
  { id: ACTION_SNOOZE, text: 'Snooze 1h' },
];
```

点击按钮会打开应用，上面的点击监听器会以 `event.result.actionId` 的形式收到按钮的 `id`。点击通知本身则没有 `actionId`。应用会先检查是否为按钮，否则回退到常规路由。

```typescript src/lib/pushActions.ts theme={null}
export function handlePushAction(actionId: string | undefined, data: PushData): ActionOutcome {
  if (!actionId) return { handled: false };

  // Record which button was tapped. As a custom event it can branch a
  // Journey (Wait Until this event) or feed a Conversion Metric.
  OneSignal.User.trackEvent('push_action_clicked', {
    action_id: actionId,
    notification_type: data?.type ?? 'unknown',
  });

  switch (actionId) {
    case ACTION_START_CLEANING:
      return { handled: true, route: '/(tabs)/clean' };

    case ACTION_SNOOZE:
      snoozeReminder();
      return { handled: true, route: null };

    case ACTION_SEND_KUDOS:
      sendKudosFromPush(data);
      return { handled: true, route: '/activity' };

    default:
      return { handled: false };
  }
}
```

**稍后提醒**需要后端，因为应用无法发送推送。应用会调用一个函数，用 `send_after` 安排另一条提醒。OneSignal 会保留消息直到那时，因此不需要任何程序持续运行一小时。

```typescript supabase/functions/snooze-reminder/index.ts theme={null}
const sendAt = new Date(Date.now() + SNOOZE_MINUTES * 60_000);

const onesignalPayload = {
  app_id: ONESIGNAL_APP_ID,
  include_aliases: { external_id: [user.id] },
  target_channel: 'push',
  // OneSignal holds the message and delivers it at this time
  send_after: sendAt.toISOString(),
  // ...
};
```

> [!NOTE]
>
> 每次点击按钮也会记录为自定义事件 `push_action_clicked`。Journey 无法直接根据按钮分支，但可以等待此事件并根据其 `action_id` 属性分支。

> [!NOTE]
>
> 默认情况下，点击按钮会打开应用。若要在不打开应用的情况下处理点击，需要原生代码：iOS 上需要通知类别，Android 上需要 notification service extension。

## 重写传入的链接 \\

来自应用外部的链接使用 `/clean` 这样的短路径。Expo Router 的 native intent 钩子会在导航发生前将其重写为应用的真实路由，因此应用外部的任何东西都不需要了解界面的组织方式。

```typescript app/+native-intent.tsx theme={null}
const PATH_REWRITES: Record<string, string> = {
  // Tab screens — simplified path → grouped route
  '/clean': '/(tabs)/clean',
  '/tasks': '/(tabs)/tasks',
  '/rota': '/(tabs)/rota',
  '/settings': '/(tabs)/settings',
  '/dashboard': '/(tabs)',

  // Standalone screens
  '/streaks': '/streaks',
  '/activity': '/activity',

  // Convenience aliases
  '/join': '/join-household',
  '/notifications': '/notification-settings',
};

export function redirectSystemPath({
  path,
  initial,
}: {
  path: string;
  initial: boolean;
}): string {
  try {
    // Parse the incoming URL to extract path and query string
    const url = new URL(path, 'cleaning-rota://app');
    const pathname = url.pathname || '/';
    const search = url.search || '';

    // Check for a rewrite match (exact path without query string)
    const rewritten = PATH_REWRITES[pathname];
    if (rewritten) {
      return rewritten + search;
    }

    // Universal Link / App Link with no rewrite: hand the router just the
    // path, not the full https URL
    if (url.protocol === 'https:' || url.protocol === 'http:') {
      return pathname + search;
    }

    // No rewrite needed — pass through as-is
    return path;
  } catch {
    // Never crash in this function — fall back to home screen
    return '/(tabs)';
  }
}
```

## 通过普通网页链接打开应用 \\

像 `cleaning-rota://` 这样的自定义 scheme 只有在应用已安装时才有效，而且许多应用不会让它变成可点击的链接。iOS 上的 Universal Links 和 Android 上的 App Links 解决了这个问题。它们是普通的 `https://` 链接，已安装应用时打开应用，未安装时打开网站。因此它们是邮件、短信和分享消息中链接的合适选择。

设置它们需要两端各做一次声明：应用声明自己属于哪个域名，网站声明哪个应用可以打开它的链接。

**1. 在应用中声明域名**

```json app.json theme={null}
{
  "expo": {
    "ios": {
      "associatedDomains": ["applinks:cleanbeansapp.com"]
    },
    "android": {
      "intentFilters": [
        {
          "action": "VIEW",
          "autoVerify": true,
          "data": [
            { "scheme": "https", "host": "cleanbeansapp.com", "pathPrefix": "/join" },
            { "scheme": "https", "host": "cleanbeansapp.com", "pathPrefix": "/clean" }
          ],
          "category": ["BROWSABLE", "DEFAULT"]
        }
      ]
    }
  }
}
```

**2. 发布 Apple 关联文件**

将其托管在 `/.well-known/apple-app-site-association`，通过 HTTPS 以 JSON 格式提供。应用 ID 是您的 Apple Team ID 后接 bundle identifier。

```json website/.well-known/apple-app-site-association theme={null}
{
  "applinks": {
    "details": [
      {
        "appIDs": ["YOUR_TEAM_ID.com.onesignal.cleaningapp"],
        "components": [
          { "/": "/join", "comment": "Opens /join in the Clean Beans app" },
          { "/": "/clean", "comment": "Opens /clean in the Clean Beans app" }
        ]
      }
    ]
  }
}
```

**3. 发布 Android 关联文件**

将其托管在 `/.well-known/assetlinks.json`。指纹来自应用的签名证书。使用 EAS 时，运行 `eas credentials -p android` 即可找到它。

```json website/.well-known/assetlinks.json theme={null}
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "com.onesignal.cleaningapp",
      "sha256_cert_fingerprints": ["YOUR_SHA256_FINGERPRINT"]
    }
  }
]
```

**4. 使用链接**

家庭界面会分享邀请链接。点击该链接会打开加入界面，并自动填好邀请码。

```typescript app/household.tsx theme={null}
message: `Join my household "${activeHousehold.name}" on Clean Beans! Tap https://cleanbeansapp.com/join?code=${encodeURIComponent(activeHousehold.inviteCode)} or use invite code: ${activeHousehold.inviteCode}`,
```

```typescript app/join-household.tsx theme={null}
const params = useLocalSearchParams<{ code?: string }>();
const [code, setCode] = useState(typeof params.code === 'string' ? params.code : '');
```

> [!NOTE]
>
> Clean Beans 只声明应用能够显示的路径。首页不在其中，因此营销网站仍然在浏览器中打开。iOS 会在安装或更新应用时读取关联文件，因此请在发布构建之前发布该文件。

> [card] [深度链接](https://documentation.onesignal.com/docs/cn/deep-linking.md)
>
> OneSignal 在各平台上如何处理 URL。

> [card] [通知负载](https://documentation.onesignal.com/docs/cn/osnotification-payload.md)
>
> 点击监听器中可用的所有字段。

> [card] [操作按钮](https://documentation.onesignal.com/docs/cn/action-buttons.md)
>
> 平台限制、图标和点击处理。


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