> ## 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 如何使用 OneSignal 通过一次性验证码验证电话号码，并通过短信或邮件邀请他人。

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

Clean Beans 用短信完成两项推送和邮件不擅长的工作：证明电话号码属于输入它的人，以及联系尚未安装应用的人。

| 消息 | 发送对象 | 触发条件 |
| - | - | - |
| 验证码 | 已登录用户刚刚输入的号码 | 从应用调用 |
| 家庭邀请 | 没有账户的人的电话号码或邮箱地址 | 从应用调用 |

两者都发送到**原始联系方式**，即电话号码或邮箱地址，而不是 External ID。这是它们与本指南中其他所有发送的主要区别。

## 使用一次性验证码验证电话号码 \\

在 User Profile 中，用户可以添加手机号码。应用请求后端发送一个 6 位验证码短信，用户输入后由后端进行检查。只有这样，该号码才算已验证。

![电话号码卡片的三种状态：输入号码、输入验证码和已验证](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-phone-verification.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=ae377258019c7454d600dc86bb722cce)

添加电话号码：输入号码、输入验证码、验证完成。

OneSignal 负责投递短信。它不会生成或检查验证码。其余所有工作都由您的后端完成。

**1. 生成验证码并以哈希形式存储**

验证码来自加密安全的随机源。只存储与用户和电话号码绑定的带密钥哈希，因此仅凭数据表无法还原验证码。该密钥是专用密钥 `OTP_HASH_SECRET`，不作他用。如果未设置该密钥，两个函数都会拒绝运行。

```typescript supabase/functions/_shared/otp.ts theme={null}
export function generateCode(): string {
  const limit = 4_000_000_000; // a multiple of 1,000,000 below 2^32, so no code is more likely than another
  const buf = new Uint32Array(1);
  do {
    crypto.getRandomValues(buf);
  } while (buf[0] >= limit);
  return String(buf[0] % 1_000_000).padStart(6, '0');
}

export async function hashCode(secret: string, userId: string, phone: string, code: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign'],
  );
  const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${userId}:${phone}:${code}`));
  return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, '0')).join('');
}
```

```typescript supabase/functions/send-otp/index.ts theme={null}
const { data: inserted, error: insertErr } = await supabase
  .from('phone_otp_codes')
  .insert({
    user_id: user.id,
    phone,
    code_hash: codeHash,
    expires_at: new Date(now.getTime() + OTP_TTL_MINUTES * 60_000).toISOString(),
  })
  .select('id')
  .single();
```

**2. 通过 OneSignal 以短信发送**

`include_phone_numbers` 直接定向该号码。如果 OneSignal 从未见过这个号码，会为它创建一个短信订阅。

```typescript supabase/functions/send-otp/index.ts theme={null}
const onesignalPayload = {
  app_id: ONESIGNAL_APP_ID,
  target_channel: 'sms',
  // Targets a raw phone number. OneSignal creates an SMS subscription
  // for it if one does not exist yet.
  include_phone_numbers: [phone],
  ...(ONESIGNAL_SMS_FROM ? { sms_from: ONESIGNAL_SMS_FROM } : {}),
  name: 'Phone verification code',
  contents: {
    en: `Your Clean Beans verification code is ${code}. It expires in ${OTP_TTL_MINUTES} minutes.`,
  },
};
```

**3. 检查验证码**

后端对用户输入的内容计算哈希，并与存储的哈希进行比较。每次输错都会计数。输错五次后，该验证码失效，必须重新申请。

```typescript supabase/functions/verify-otp/index.ts theme={null}
const submittedHash = await hashCode(OTP_HASH_SECRET, user.id, phone, code);

if (!safeEqual(submittedHash, row.code_hash)) {
  const attempts = row.attempts + 1;
  await supabase.from('phone_otp_codes').update({ attempts }).eq('id', row.id);

  const left = OTP_MAX_ATTEMPTS - attempts;
  return jsonResponse({
    error: 'invalid_code',
    message: left > 0
      ? `That code is not right. ${left} ${left === 1 ? 'attempt' : 'attempts'} left.`
      : 'Too many wrong attempts. Request a new code.',
    attemptsLeft: Math.max(left, 0),
  }, 400);
}
```

**4. 将号码注册为短信订阅**

后端确认验证码后，应用会把该号码添加到已登录用户。

```typescript src/lib/phone.ts theme={null}
export async function confirmPhoneCode(phone: string, code: string): Promise<void> {
  await callFunction('verify-otp', { body: { phone, code } });
  OneSignal.User.addSms(phone);
}
```

应用会在每次登录后重复此操作，因此已验证的号码会跟随用户到新设备上。

```typescript src/lib/phone.ts theme={null}
export async function syncOneSignalSms(): Promise<void> {
  try {
    const phone = await loadVerifiedPhone();
    if (phone) {
      OneSignal.User.addSms(phone);
      console.log('[phone] SMS subscription synced');
    }
  } catch (e) {
    console.warn('[phone] syncOneSignalSms error:', e);
  }
}
```

> [!NOTE]
>
> 与邮件一样，请在 `login()` 之后调用 `addSms()`。向原始电话号码发送会创建一个不属于任何人的订阅。在已登录的应用中调用 `addSms()` 会把该订阅关联到用户。在此之前，它会在仪表板中显示为一个单独的用户记录。

## 保护端点 \\

按请求发送短信的函数每次运行都会产生费用，也容易被滥用。Clean Beans 采用以下限制。

| 规则 | 值 |
| - | - |
| 验证码有效期 | 10 分钟 |
| 允许的错误尝试次数 | 5 次 |
| 重新发送前的等待时间 | 30 秒 |
| 每位用户的验证码数量 | 每 10 分钟 3 个 |
| 每个验证码的使用次数 | 一次。新验证码会替换之前的验证码 |

```typescript supabase/functions/send-otp/index.ts theme={null}
const MAX_CODES_PER_WINDOW = 3;
const WINDOW_MINUTES = 10;
const RESEND_COOLDOWN_SECONDS = 30;
```

已验证的号码保存在单独的数据表中。只有后端可以写入，因此应用无法将号码标记为已验证，家庭中的其他成员也无法读取它。

```sql supabase/migrations/028_phone_verification_and_invites.sql theme={null}
create table if not exists public.user_phones (
  user_id     uuid primary key references public.profiles(id) on delete cascade,
  phone       text not null,                       -- E.164, e.g. +14155551234
  verified_at timestamptz not null default now()
);
```

## 在输入号码的地方征求同意 \\

仅有电话号码并不代表获得了发送短信的许可。对于验证码，在电话号码字段旁边放置一段说明即可，说明中必须写明发送方、发送内容、可能产生的费用以及如何退订。

```tsx src/components/PhoneVerificationCard.tsx theme={null}
{/* Consent disclosure: must sit next to the phone field */}
<Text style={styles.disclosure}>
  Enter your mobile number to receive verification codes by text message from Clean Beans.
  Msg & data rates may apply. Reply STOP to opt out.
</Text>
```

## 邀请尚未成为用户的人 \\

在 Household 界面中，成员可以通过短信或邮件邀请他人。被邀请者没有账户、没有已注册的设备，也没有 External ID。后端直接向原始联系方式发送消息，并附上打开应用加入界面的链接。

![邀请对话框及其发送的邀请短信](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-invitation.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=78d087c22898bc9876dbdd1f90c56033)

通过短信或邮件邀请室友，以及对方收到的消息。

同一个端点同时处理两个渠道。短信使用 `include_phone_numbers`。邮件使用 `email_to`，并在请求中直接传入主题和 HTML 正文。

```typescript supabase/functions/send-invite/index.ts theme={null}
const joinUrl = `${JOIN_URL}?code=${encodeURIComponent(household.invite_code)}`;

const onesignalPayload: Record<string, unknown> = channel === 'sms'
  ? {
      app_id: ONESIGNAL_APP_ID,
      target_channel: 'sms',
      // Raw phone number: OneSignal creates an SMS subscription if needed
      include_phone_numbers: [contact],
      ...(ONESIGNAL_SMS_FROM ? { sms_from: ONESIGNAL_SMS_FROM } : {}),
      name: 'Household invitation (SMS)',
      contents: {
        en: `${inviterName} invited you to join "${householdName}" on Clean Beans, the cleaning rota app. Join: ${joinUrl} Reply STOP to opt out.`,
      },
    }
  : {
      app_id: ONESIGNAL_APP_ID,
      target_channel: 'email',
      // Raw email address: OneSignal creates an email subscription if needed
      email_to: [contact],
      name: 'Household invitation (email)',
      email_subject: `${inviterName} invited you to Clean Beans`,
      email_preheader: `Join "${householdName}" and share the cleaning.`,
      email_body: buildInviteEmail(inviterName, householdName, joinUrl, household.invite_code),
      // Keep the join link exactly as written. Click tracking would wrap
      // it in a redirect, and it would stop opening the app directly.
      disable_email_click_tracking: true,
    };
```

该链接是在[通过普通网页链接打开应用](https://documentation.onesignal.com/docs/cn/example-full-integration-deep-links.md#open-the-app-from-ordinary-web-links)中设置的 Universal Link。有两个细节确保它正常工作：

* **关闭了邮件点击跟踪。** 跟踪会重写链接，使其经过跟踪域名，而重写后的链接无法再直接打开应用。
* **短信不使用带跟踪的短链接**，原因相同。

被邀请者安装应用并登录后，应用的 `login()` 以及 `addEmail()` 或 `addSms()` 调用会把邀请所创建的订阅关联到其新用户上。

> [!WARNING]
>
> 被邀请者并未同意接收您应用的消息。关于未经请求的短信和邮件的规定因国家/地区而异，并且可能很严格。Clean Beans 包含此流程是为了演示如何向原始联系方式发送消息，并将每位成员的邀请限制为每天十次。在生产环境中使用此模式之前，请先了解您所发送地区的规定，并考虑让邀请者用自己的手机发送消息。

## 注意事项 \\

* **必须有发送方。** 在 **Settings > SMS** 中选择默认发送方，或在每个请求中传入 `sms_from`。两者都没有时，请求会被拒绝，并返回“A valid number is required for 'From' field”。
* **`200` 响应并不总是意味着消息已发送。** 除了状态码，还要检查响应中是否有消息 `id`。
* **以 E.164 格式存储号码**，即加号后接国家/地区代码和号码，并在调用 API 之前拒绝任何其他格式。
* **OneSignal Verify 是托管的替代方案。** 它会为您生成和检查验证码。Clean Beans 自行实现，以展示完整流程。

**仪表板设置。** 完成[短信设置](https://documentation.onesignal.com/docs/cn/sms-setup.md)，并选择一个能够覆盖您用户所在国家/地区的默认发送方。

> [card] [一次性密码](https://documentation.onesignal.com/docs/cn/sms-verify.md)
>
> OneSignal Verify 和自行实现。

> [card] [短信订阅许可和收集](https://documentation.onesignal.com/docs/cn/sms-opt-in-and-collection.md)
>
> 同意和披露要求。

> [card] [短信 API 参考](https://documentation.onesignal.com/reference/sms.md)
>
> 所有短信参数。


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