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

# Example app: SMS verification codes and invitations

> How the Clean Beans example app verifies phone numbers with one-time codes and invites people by SMS or email using OneSignal.

This page is part of [Example app: a full OneSignal integration](https://documentation.onesignal.com/docs/en/example-full-integration-overview.md), which follows one real app from end to end. The app is **Clean Beans**, a cleaning rota for shared homes, built with Expo (React Native) and a Supabase backend.

Clean Beans uses SMS for two jobs that push and email cannot do well: proving that a phone number belongs to the person who typed it, and reaching someone who does not have the app yet.

| Message | Sent to | Trigger |
| - | - | - |
| Verification code | The number a signed-in user just entered | Call from the app |
| Household invitation | A phone number or email address of someone with no account | Call from the app |

Both are sent to a **raw contact**, a phone number or email address, not to an External ID. That is the main difference from every other send in this guide.

## Verify a phone number with a one-time code

In User Profile, a user can add a mobile number. The app asks the backend to text a 6-digit code, the user types it in, and the backend checks it. Only then does the number count as verified.

![The phone number card in three states: entering a number, entering a code, and verified](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-phone-verification.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=ae377258019c7454d600dc86bb722cce)

Adding a phone number: enter the number, enter the code, verified.

OneSignal delivers the text message. It does not create or check the code. Everything else is your backend's job.

**1. Generate a code and store it hashed**

The code comes from a cryptographic random source. Only a keyed hash is stored, bound to the user and the phone number, so the table alone cannot be turned back into codes. The key is a dedicated secret, `OTP_HASH_SECRET`, used for nothing else. Both functions refuse to run if it is not set.

```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. Send it by SMS through OneSignal**

`include_phone_numbers` targets the number directly. If OneSignal has never seen it, it creates an SMS subscription for it.

```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. Check the code**

The backend hashes what the user typed and compares it with the stored hash. A wrong guess is counted. After five, the code is dead and a new one must be requested.

```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. Register the number as an SMS subscription**

Once the backend confirms the code, the app adds the number to the signed-in user.

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

The app repeats this after every sign-in, so a verified number follows the user to a new device.

```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]
>
> Call `addSms()` after `login()`, as with email. A send to a raw phone number creates a subscription that belongs to no one. `addSms()` from a signed-in app attaches that subscription to the user. Until then, it appears in the dashboard as a separate user record.

## Protect the endpoint

A function that sends a text message on request costs money each time it runs, and it is a target for abuse. Clean Beans applies these limits.

| Rule | Value |
| - | - |
| Code lifetime | 10 minutes |
| Wrong attempts allowed | 5 |
| Wait before resending | 30 seconds |
| Codes per user | 3 every 10 minutes |
| Uses per code | One. A new code replaces any earlier one |

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

The verified number is kept in its own table. Only the backend can write to it, so the app cannot mark a number as verified, and other members of a household cannot read it.

```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()
);
```

## Ask for consent where the number is entered

A phone number on its own is not permission to text it. For verification codes, a disclosure next to the phone field is enough, and it must say who is sending, what they will send, that rates may apply, and how to stop.

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

## Invite someone who is not a user yet

On the Household screen, a member can invite someone by text or by email. The invitee has no account, no device registered, and no External ID. The backend sends to the raw contact, with a link that opens the app's join screen.

![The invite dialog and the invitation text message it sends](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-invitation.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=78d087c22898bc9876dbdd1f90c56033)

Inviting a housemate by text or email, and the message they receive.

The same endpoint handles both channels. SMS uses `include_phone_numbers`. Email uses `email_to`, with the subject and HTML body passed inline.

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

The link is a Universal Link, set up in [Open the app from ordinary web links](https://documentation.onesignal.com/docs/en/example-full-integration-deep-links.md#open-the-app-from-ordinary-web-links). Two details keep it working:

* **Email click tracking is turned off.** Tracking rewrites links to pass through a tracking domain, and a rewritten link no longer opens the app.
* **The SMS does not use a tracked short link**, for the same reason.

When the invitee installs the app and signs in, the app's `login()` and `addEmail()` or `addSms()` calls attach the subscription that the invitation created to their new user.

> [!WARNING]
>
> The invitee has not agreed to hear from your app. Rules for unsolicited texts and emails vary by country and can be strict. Clean Beans includes this flow to show how sending to a raw contact works, and limits each member to ten invitations a day. Before using the pattern in production, check the rules for the places you send to, and consider having the inviter send the message from their own phone.

## Things to know

* **A sender is required.** Choose a default sender in **Settings > SMS**, or pass `sms_from` with each request. With neither, the request is rejected with "A valid number is required for 'From' field".
* **A `200` response does not always mean a message was sent.** Check for a message `id` in the response, not only the status code.
* **Store numbers in E.164 format**, a plus sign followed by the country code and number, and reject anything else before calling the API.
* **OneSignal Verify is the managed alternative.** It generates and checks codes for you. Clean Beans builds its own to show the whole flow.

**Dashboard setup.** Complete [SMS setup](https://documentation.onesignal.com/docs/en/sms-setup.md) and choose a default sender that can reach the countries your users are in.

> [card] [One-time passwords](https://documentation.onesignal.com/docs/en/sms-verify.md)
>
> OneSignal Verify and building your own.

> [card] [SMS opt-in and collection](https://documentation.onesignal.com/docs/en/sms-opt-in-and-collection.md)
>
> Consent and disclosure requirements.

> [card] [SMS API reference](https://documentation.onesignal.com/reference/sms.md)
>
> Every SMS parameter.


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