---
title: "Onboarding SDK for React Native"
url: "https://platformdocs.coinme.com/#/docs/onboarding-sdk-react-native"
markdown: "https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md"
summary: "The Coinme Onboarding SDK for React Native onboards a customer to Coinme-as-a-Service (CAAS) from your iOS or Android app built with React Native, returns the new `customerId`, and then verifies the customer's phone with a code texted to the number they onboarded with. It is one package, `@coinme-security/onboarding-sdk-react-native`, with the same drop-in form, field components and hooks as the JavaScript & React SDK, built from native components."
surface: "caas"
platform: "reactNative"
package: "@coinme-security/onboarding-sdk-react-native"
version: "1.2.1"
peerDependencies: {"@vgs/collect-react-native":"^1.1.6","react":">=18","react-native":">=0.76"}
updated: "2026-11-06"
---

# Onboarding SDK for React Native

The Coinme Onboarding SDK for React Native onboards a customer to Coinme-as-a-Service (CAAS) from your iOS or Android app built with React Native, returns the new `customerId`, and then verifies the customer's phone with a code texted to the number they onboarded with. It is one package, `@coinme-security/onboarding-sdk-react-native`, with the same drop-in form, field components and hooks as the [JavaScript & React SDK](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md), built from native components.

This SDK leverages the Coinme Vault so that the customer's Social Security Number is typed into a secure field provided by the vault, and your code and your servers never receive the raw SSN. Everything else (email, name, address, phone, date of birth) is collected in ordinary `TextInput`s that you style however you like.

The endpoint itself is described in Coinme's [customer onboarding guide](https://docs.coinme.com/docs/customer-onboarding-overview).

## Why use it

Collecting an SSN yourself puts your app, your logs and your servers in scope for handling it. This SDK keeps it out of your code: the customer types it into the vault's secure field, and it goes from that field to the vault without passing through your code. Your code only sees whether the SSN is valid and, once it is, its last four digits, never the full number.

You get:

- **A drop-in form.** `<CustomerOnboardingForm>` collects every field the endpoint requires and calls you back with `{ customerId, phoneNumber }` or a typed error.
- **Headless building blocks.** A provider, individual field components (including the secure SSN field) and a `useCustomerOnboarding` hook, for teams that build their own UI.
- **Phone verification after onboarding.** `<PhoneVerificationStep>` (or the `usePhoneVerification` hook) texts the new customer a code and checks it, so you know the number they onboarded with is verified before you treat their KYC as complete.
- **Pass-through styling.** Every field accepts the same props as the component underneath it. There's no theme contract to learn and no Coinme branding.
- **Typed outcomes.** `CoinmeOnboardingError` tells you whether a failure is terminal (duplicate, age, jurisdiction, sanctions) or worth retrying.

## Install

The package is published to Coinme's private npm registry. Configure the `@coinme-security` scope with the registry token Coinme provides, then install.

`.npmrc` (npm / Yarn Classic):

```properties
@coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/
//npm.coinme.com/coinme-security-wrapper/:_authToken=${COINME_REGISTRY_TOKEN}
```

`.yarnrc.yml` (Yarn Berry v2+):

```yaml
nodeLinker: node-modules

npmScopes:
  coinme-security:
    npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/'
    npmAuthToken: '${COINME_REGISTRY_TOKEN}'
    npmAlwaysAuth: true
```

Then export the token and install the package with its secure field peer:

```bash
export COINME_REGISTRY_TOKEN=<your-token>
npm install @coinme-security/onboarding-sdk-react-native @vgs/collect-react-native
# or: yarn add @coinme-security/onboarding-sdk-react-native @vgs/collect-react-native
# or, in an Expo app: npx expo install @coinme-security/onboarding-sdk-react-native @vgs/collect-react-native
```

`COINME_REGISTRY_TOKEN` is the registry access token. Request it from your Coinme integration contact. The token is used only for the `@coinme-security` scope; `@vgs/collect-react-native` comes from the public npm registry.

`react`, `react-native` and `@vgs/collect-react-native` are peer dependencies. The Coinme Vault SDK (`@coinme-security/vault-sdk-react-native`), which connects the secure field to the vault, is installed with the package.

### Expo and bare React Native

This package, the Coinme Vault SDK and the current `1.x` line of `@vgs/collect-react-native` are all JavaScript, with no native module of their own. There's nothing to link: no config plugin, no prebuild, no `pod install` or Gradle changes for them, and nothing to configure for either React Native architecture.

- **Expo:** it runs in Expo Go. Start your app as usual with `npx expo start`. You need a development build only if your app adds other native modules.
- **Bare React Native:** there's nothing to link, so these packages need no `pod install` and no Gradle sync. Adding them changes only JavaScript: restart Metro with a clean cache, as below, and reload the app. Rebuild the native app only if you added other native modules at the same time.

After installing, restart Metro with a clean cache (`npx expo start --clear` or `npx react-native start --reset-cache`).

## Compatibility

| Requirement | Supported |
| --- | --- |
| React Native | 0.76 or later (`react-native` peer), tested with 0.87.1 |
| React | 18 or later, as bundled with your React Native release (`react` peer) |
| Expo | SDK 52 or later (the first SDK on React Native 0.76), including Expo Go |
| Secure field library | `@vgs/collect-react-native` 1.1.6 or later within `1.x`, tested with 1.2.1. A peer dependency: you install it, and your app's copy is the one used. |
| Platforms | iOS and Android |
| React Native architecture | Old and New Architecture; there's no native code to configure |
| TypeScript | Full typings ship with the package |

The secure field library is JavaScript bundled into your app by Metro, not loaded at runtime, so the version is whichever `1.x` your app installs.

**iOS privacy manifest.** Our vault provider documents an optional set of iOS privacy-manifest entries for its product-interaction analytics (no customer data, no tracking) that you can merge into your app's `PrivacyInfo.xcprivacy` if your release process calls for it; see the vault provider's [privacy details](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/react-native-sdk/privacy-details).

## Before you start

The SDK covers two steps: onboarding the customer, then verifying their phone. Before a customer reaches your onboarding form:

1. **Have a way to get two tokens from your backend.** The onboarding request needs a token minted for the customer's sign-up session. Phone verification needs a second token, minted for the `customerId` that onboarding returns. Never your partner access token. You write the backend routes that mint them; [You build](#you-build) lists what each one does.
2. **Plan for phone verification right after onboarding, and on later sign-ins with incomplete 2FA.** A newly onboarded customer needs to confirm the code texted to the phone number they onboarded with. If the code isn't confirmed, the customer should not be considered to have completed KYC. See the [recommended integration flow](#recommended-integration-flow).

The SDK doesn't pre-fill or verify the customer's identity from other sources. If you already hold some of their details, pass them to the form with `defaultValues`.

## Recommended integration flow

Onboarding is complete only once the customer's phone is verified. Build your integration in this order:

> **Every call after onboarding uses a token for that customer.**
>
> Sending the code and checking it are authorized by a Transient Auth Token your backend mints for the `customerId` that onboarding returned (step 4). Never use your partner access token or the sign-up session token for them. That token is the only thing that ties the two calls to the customer: there's no challenge ID, session or cookie to carry from one call to the other. See [You build](#you-build) for the backend routes this takes.

1. **Mint an onboarding token for the sign-up session.** When the customer reaches your onboarding screen, your app asks your backend for a token. Your backend calls `POST /services/browserAuth` with `scope=onboarding` and your own identifier for the sign-up session as `customerId`: any ID you choose, such as your internal session ID. The customer doesn't exist at Coinme yet.
2. **Onboard the customer with that token.** Return it from the form's (or provider's) `getHeaders`. When onboarding succeeds, `onSuccess` receives `{ customerId, phoneNumber }`.
3. **Send the real `customerId` to your backend.** From `onSuccess`, send the `customerId` to your backend and link it to the sign-up session, together with `phoneNumber`, the number the customer onboarded with. Keep both: you need them for verification now and whenever the customer comes back.
4. **Mint a new token for the real `customerId`.** Your backend calls `POST /services/browserAuth` again, this time with the `customerId` from onboarding as `customerId`. Use **this** token for every phone verification call; the sign-up session token from step 1 won't work for them. Your backend reads the `customerId` from the record it saved in step 3, not from the app, so an app can only ever get a token for its own customer.
5. **Start phone verification with that same number.** Your app shows `PhoneVerificationStep` (or uses `usePhoneVerification`) with `phoneNumber` from the onboarding result, and its `getHeaders` returns the token from step 4. Coinme texts the customer a code.
6. **Validate the code for that number.** The customer types the code. Once it checks out, `onVerified` runs; record on your backend that this customer's phone is verified.
7. **Only now treat the customer as onboarded.** A customer whose phone isn't verified hasn't completed KYC. Don't give them access to anything that needs a completed onboarding.
8. **Send a returning customer back to verification.** If a customer whose phone isn't verified signs in again later, take them to phone verification before anything else: mint a fresh token for their `customerId` as in step 4, and use the `phoneNumber` you stored in step 3.

Two rules hold in every case:

- **No verified phone, no completed onboarding.** Never consider a customer onboarded or KYC-complete until their phone number is verified, whatever your own records or UI show.
- **The verification number is the onboarding number.** Never let the customer give one phone number for onboarding and another for verification. Pass `phoneNumber` from the onboarding result (or the copy you stored in step 3), and don't offer a phone input at the verification step. Coinme texts whatever number the SDK sends and, once the code checks out, records it as the customer's verified phone. It doesn't compare it with the onboarded number, so passing the onboarded number is up to you.

## Quickstart

The quickest integration is the drop-in form followed by the drop-in phone verification step. The form collects every field the endpoint needs, the SSN included, and calls you back with the new `customerId` and the phone number it onboarded. The step then texts that number a code and checks it.

The SDK runs in your app, but it needs a few routes on **your** backend, which you write. The code below calls them; the [You build](#you-build) table after it says what each one does.

```tsx
import {
  CustomerOnboardingForm, // Coinme SDK
  PhoneVerificationStep, // Coinme SDK
  type CustomerOnboardingResult, // Coinme SDK
} from '@coinme-security/onboarding-sdk-react-native';
import { useState } from 'react';
import { ScrollView } from 'react-native';

// YOUR code, not part of the SDK. YOUR_BACKEND is your own server, and these two helpers call
// routes on it (see "You build" below). The URL and paths are examples. Keep the tokens in
// memory only: never store or log them.
const YOUR_BACKEND = 'https://your-backend.example.com';

const postToYourBackend = async (
  path: string,
  body?: unknown
): Promise<Response> => {
  // React Native's fetch has no timeout of its own, so give each call one.
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 15_000);
  try {
    const response = await fetch(`${YOUR_BACKEND}${path}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // YOUR code: your app's own sign-in credential for your backend, not a Coinme token.
        Authorization: `Bearer ${await getYourAppSessionToken()}`,
      },
      body: JSON.stringify(body ?? {}),
      signal: controller.signal,
    });
    if (!response.ok)
      throw new Error(`Request to ${path} failed (${response.status})`);
    return response;
  } finally {
    clearTimeout(timer);
  }
};

const getTokenFromYourBackend = async (path: string): Promise<string> => {
  const { token } = await (await postToYourBackend(path)).json();
  return token;
};

export const Onboarding = () => {
  const [onboarded, setOnboarded] = useState<CustomerOnboardingResult>();

  return (
    <ScrollView
      contentContainerStyle={{ padding: 16 }}
      automaticallyAdjustKeyboardInsets
      keyboardDismissMode="on-drag"
      keyboardShouldPersistTaps="handled"
    >
      {onboarded ? (
        <PhoneVerificationStep
          environment="sandbox"
          phoneNumber={onboarded.phoneNumber} // the number from onboarding; never ask for another
          // Called before every send and every check. It sends no customerId: YOUR route already
          // knows which customer this is (see "You build").
          getHeaders={async () => ({
            Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
          })}
          onVerified={() => {
            void postToYourBackend(
              '/your-api/phone-verification/verified'
            ).then(() => {
              // YOUR code: take the customer to your next screen.
            });
          }}
        />
      ) : (
        <CustomerOnboardingForm
          environment="sandbox"
          // Called before every submit. YOUR route returns a token for this sign-up session.
          getHeaders={async () => ({
            Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
          })}
          // Save the result on YOUR backend before moving on: the next token is minted from it.
          onSuccess={(result) => {
            void postToYourBackend(
              '/your-api/onboarding/complete',
              result
            ).then(() => setOnboarded(result));
          }}
        />
      )}
    </ScrollView>
  );
};
```

> **This is one way to do it, not the only way.**
>
> The backend URL, the route paths, the helper names, how your app signs in to your backend and how you show errors are all yours to choose. What matters is what each route does, in the table below. A real integration also handles a failed request (show a retry), and shows the verification step again to a customer who signs back in before verifying (step 8 of the [recommended integration flow](#recommended-integration-flow)).

### You build

These routes run on **your** backend. Coinme doesn't provide them: the paths are examples, so name them however you like. Only the Coinme API calls they make are fixed.

| Your route (example path) | What it does |
| --- | --- |
| `POST /your-api/onboarding/token` | Mints a Transient Auth Token for the sign-up session: calls Coinme's `POST /services/browserAuth` with `scope=onboarding` and your own ID for the session as `customerId`. Returns `{ token }`. |
| `POST /your-api/onboarding/complete` | Saves the `customerId` and `phoneNumber` from the onboarding result on the signed-in user, in your own database. |
| `POST /your-api/phone-verification/token` | Looks up the signed-in user, reads the `customerId` you saved for them, and mints a Transient Auth Token for **that** `customerId` (`scope=onboarding`). Returns `{ token }`. It never takes a `customerId` from the app. |
| `POST /your-api/phone-verification/verified` | Records on the signed-in user that their phone is verified. |

Your partner access token (from Coinme's `POST /services/authorize`) is what these routes use to call `browserAuth`. It stays on your backend and never reaches the device.

**This is how customer IDs can't get mixed up.** Each of your users has one saved `customerId`, and the verification token route only ever mints for that one. The app never says which customer it is, so it can't ask for the wrong one. Example code for all four routes is in [Example: both tokens, end to end](#example-both-tokens-end-to-end).

The later examples reuse `getTokenFromYourBackend`, `postToYourBackend` and these route paths, and `getHeaders` and `onSuccess` stand for the onboarding form's functions shown here. `goToWelcome`, `startPhoneVerification`, `reportOnboardingFailure` and `reportVerificationFailure` stand for your own navigation and error display.

The form is a plain `View`, not a scroll view, so render it inside your own `ScrollView`. On iOS, keep `automaticallyAdjustKeyboardInsets` on it (or wrap it in a `KeyboardAvoidingView`) so the bottom fields can be scrolled into view while the keyboard is open.

The form comes unstyled: its inputs have no border until you give them one. See [Style the whole form](#style-the-whole-form) for a complete example.

Switch `environment` to `'live'` for real customers.

## How it works

- **`environment` selects everything else.** `'sandbox'` or `'live'` picks the onboarding vault and the Coinme onboarding endpoint, both built into the package. You never configure a vault ID or URL.
- **The vault is created when the form mounts.** The form (or `CoinmeOnboardingProvider`) creates it on mount and disposes of it on unmount.
- **The SSN goes from the secure field to the vault.** The customer types the SSN into the vault's secure field. When you submit, the request goes through the vault, which puts the SSN into it. The SSN never passes through your code, but until the vault receives it, it is in your app's JavaScript runtime; see [Security](#security).
- **The other fields are plain inputs.** Their values are in React state, so you can prefill, read and validate them.
- **You see only metadata for the SSN.** Whether it's valid, empty, focused or touched, and its last four digits once it's valid. Never the full number.
- **Every failure is one error type.** Client-side validation failures, network failures, HTTP errors and CAAS error codes all become a `CoinmeOnboardingError` with a `kind` and a `retryable` flag.

**Terms used in this guide:**

- **Vault:** the Coinme Vault connection that holds the secure SSN field. The form or `CoinmeOnboardingProvider` creates one and cleans it up for you.
- **Secure field / SSN field:** the vault's field the customer types the SSN into.
- **Plain fields:** every other field. They're ordinary inputs whose values live in React state.
- **Mount:** when React first renders a component. A prop that's "read once on mount" is read then; changing it later has no effect.
- **Touched:** a field the customer has left (blurred) at least once. After a submit attempt, every field counts as touched. Inline errors show only for touched fields.

## Authentication and headers

You supply the request headers through `getHeaders`, which the SDK calls just before each request. It can be async, so fetch a fresh token inside it. Whatever it returns is sent as the request headers.

| Header | Value |
| --- | --- |
| `Authorization` | `Bearer <token>`, with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend minted with `scope=onboarding`. |
| `X-Device-Fingerprint` | Optional from 1.2.0, which always sends one; see [Device fingerprint](#device-fingerprint). With an older release, send the value you give the Risk SDK. |

> **Never give the Onboarding SDK your partner access token.**
>
> `getHeaders` must always return a Transient Auth Token your backend mints from `POST /services/browserAuth` with `scope=onboarding`, never your partner access token (from `POST /services/authorize`).

The two steps need different tokens, both minted by your backend with `POST /services/browserAuth` and both lasting 10 minutes:

| Step | Minted for (`customerId` when minting) | Passed through |
| --- | --- | --- |
| Onboarding | Your identifier for the customer's sign-up session, with `scope=onboarding`. The customer doesn't exist at Coinme yet. | The form's or provider's `getHeaders` |
| Phone verification | The `customerId` that onboarding returned, with `scope=onboarding`. | `PhoneVerificationStep`'s or `usePhoneVerification`'s `getHeaders` |

> **`scope=onboarding` is sandbox-only for now.**
>
> Coinme's `live` environment doesn't mint `scope=onboarding` tokens yet, so neither step can run in `live` until it does. Check with your Coinme integration contact before going live.

Each phone verification call (sending a code, checking it) asks `getHeaders` again, so mint a fresh token there rather than reusing one: a customer who waits for the text can easily pass the 10 minutes.

- **Never send your partner access token.** The SDK refuses a request whose `Authorization` header carries a partner access token and throws a `configuration` `CoinmeOnboardingError` before anything is sent. If you see it, your backend is returning the partner access token to the app. Change that route to mint a Transient Auth Token from `POST /services/browserAuth` (with `scope=onboarding`) and return only its `access_token`. The partner access token is a long-lived credential that must stay on your backend.
- **Never put your Coinme credentials or your partner access token in the app.** Only the Transient Auth Tokens reach the device, and only for the requests that need them. Get them from your own backend.
- **Don't store the token.** Fetch it just in time and don't keep it in `AsyncStorage`, secure storage or anywhere else on the device.
- **Time out your token request.** `timeoutMs` starts once `getHeaders` resolves, so it doesn't cover your token call, and React Native's `fetch` has no timeout of its own. On a bad network a hanging token request leaves the submit button spinning with no error. Give it its own timeout:

```tsx
const getHeaders = async () => {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 15_000);
  try {
    // YOUR backend route (the URL is an example); see "You build". The Quickstart's
    // helpers already include this timeout.
    const response = await fetch(
      'https://your-backend.example.com/your-api/onboarding/token',
      {
        method: 'POST',
        signal: controller.signal,
      }
    );
    const { token } = await response.json();
    return { Authorization: `Bearer ${token}` };
  } finally {
    clearTimeout(timer);
  }
};
```

An error thrown here, including the abort, fails the submit (or the phone verification call) as `unknown`, with the original on `error.cause`.

**The verification token is what ties verification to the customer.** Sending the code sends only the phone number, and checking it sends only the code. Coinme works out which customer the calls are for from the token, so there's no challenge ID, session or cookie to carry between them. That's why the token must be minted for that one `customerId`, and why your partner access token must never be used in its place: it isn't tied to any customer, and it must never reach the device.

The SDK also adds tracing headers (`X-B3-TraceId`, `X-B3-SpanId`) to each request.

### Device fingerprint

Coinme ties risk checks to a device ID sent as the `X-Device-Fingerprint` header, and phone verification is refused without it. From 1.2.0, with Risk SDK for React Native 1.1.0 or later, the SDK adds it to the onboarding submit and to both phone verification calls, so you don't have to supply one. With an older release of either, send it yourself from `getHeaders`, with the same value you give the Risk SDK.

- If you pass a fingerprint (an `X-Device-Fingerprint` header from `getHeaders`, any casing), this SDK uses it and shares it with the other Coinme SDKs in your app. Pass the same value to every Coinme SDK, or pass it to the Risk SDK first, which shares it with the others.
- If you don't, the SDK uses the one another Coinme SDK already set in your app, or creates one.
- Every Coinme SDK in your app must send the same value. If they differ, adding a payment method and placing orders fail with `WEB_SESSION_ID_MISMATCH`.
- Calls your server makes to Coinme for this user (for example orders) must send the same value. Read it in the app with `await getDeviceFingerprint()` (it returns a Promise) and send it to your server with the request. Never call `getDeviceFingerprint()` on your server.
- A `:` in the value is replaced with `-`.
- A risk session tag lives 30 minutes from when it was first issued. Call the Risk SDK's `getPartnerSessionTag()` right before adding a payment method or placing an order, and send the tag it returns as `webSessionId`.

The value only has to match across the Coinme SDKs within one launch of your app; it is not a permanent device ID. When the Coinme Risk SDK for React Native is installed, it also keeps the value in the app's native storage, so it survives relaunches, and this SDK waits up to a few seconds for that value to load before sending. Without it, each launch gets a new value.

Import `@coinme-security/risk-sdk-react-native` at the top of your app's entry file (`index.js`), before anything else that uses a Coinme SDK. React Native loads modules when they are first used, so otherwise this SDK can send a request before the stored value has loaded.

```javascript
// index.js
import '@coinme-security/risk-sdk-react-native';
```

### Questions about the two tokens

**How do I make sure I don't mix up customer IDs? How does my backend know which customer to mint the verification token for?** From its own records, never from the app. When onboarding succeeds, the app sends the result to your backend, which saves the `customerId` on the signed-in user. When the app later asks for the verification token, your backend looks up the signed-in user and mints the token for the `customerId` it saved. Each user has one saved `customerId`, so the app can't ask for someone else's.

**Do I pass the `customerId` to the send or check calls?** No. Neither takes one. The token carries the customer, which is why it has to be minted for that `customerId`.

**Can I use my partner access token for phone verification?** No. It isn't tied to any customer, and it must never reach the device. Use it only on your backend, to mint Transient Auth Tokens.

**Can I reuse the onboarding token?** No. It was minted for the sign-up session, before the customer existed at Coinme. Mint a new one for the `customerId` that onboarding returned.

### Example: both tokens, end to end

> **This is one way to do it, not the only way.**
>
> The route names, paths, host, how your app signs in to your backend, the framework and the storage are yours to choose; only the Coinme API calls and the SDK's props are fixed. It does follow what we recommend:
>
> - your backend reads the `customerId` from its own record, never from the app;
> - your partner access token is minted and cached on your server only;
> - each `getHeaders` call fetches a fresh token, kept in memory only and never stored or logged;
> - the phone number is the one from the onboarding result.

Who provides what:

|  | What | Where it runs |
| --- | --- | --- |
| **Coinme provides** | `POST https://caas-staging.coinme.com/services/authorize`: your partner access token (Coinme API) | Called from your backend only |
| **Coinme provides** | `POST https://caas-staging.coinme.com/services/browserAuth`: a Transient Auth Token (Coinme API) | Called from your backend only |
| **Coinme provides** | `CustomerOnboardingForm`, `PhoneVerificationStep` and their props (this SDK) | Your app |
| **You build** | `POST https://your-backend.example.com/your-api/onboarding/token`, `…/your-api/onboarding/complete`, `…/your-api/phone-verification/token`, `…/your-api/phone-verification/verified` | Your backend. These are examples: Coinme doesn't provide them, so name and shape them however you like. What each does: [You build](#you-build). |

In production, use the base URL your Coinme integration contact gives you in place of `https://caas-staging.coinme.com`.

**Your backend** (YOUR code, shown with Express; the routes are examples):

```typescript
import express from 'express';
// Your own code: `requireSession` checks YOUR app's sign-in for the person using the app, and `users`
// is YOUR user store. `mintTransientAuthToken` wraps the two Coinme API calls above; the
// Transient Auth Token guide has a complete version.
import { mintTransientAuthToken, requireSession, users } from './your-app';

const app = express();
app.use(express.json());

// Token 1: for the sign-up session. The customer doesn't exist at Coinme yet.
app.post('/your-api/onboarding/token', requireSession, async (req, res) => {
  const { token } = await mintTransientAuthToken(req.session.id, 'onboarding');
  res.json({ token });
});

// Save what onboarding returned against YOUR user, so later tokens come from your record.
app.post('/your-api/onboarding/complete', requireSession, async (req, res) => {
  const { customerId, phoneNumber } = req.body;
  await users.update(req.session.userId, {
    coinmeCustomerId: customerId,
    onboardedPhone: phoneNumber,
    phoneVerified: false,
  });
  res.sendStatus(204);
});

// Token 2: for this customer. The app never says which customer: the ID comes from your
// record, so an app can only get a token for its own customer.
app.post(
  '/your-api/phone-verification/token',
  requireSession,
  async (req, res) => {
    const user = await users.get(req.session.userId);
    if (!user?.coinmeCustomerId) return res.sendStatus(409);
    const { token } = await mintTransientAuthToken(
      user.coinmeCustomerId,
      'onboarding'
    );
    res.json({ token });
  }
);

// The app reports that the code checked out. Coinme checked the code itself.
app.post(
  '/your-api/phone-verification/verified',
  requireSession,
  async (req, res) => {
    await users.update(req.session.userId, { phoneVerified: true });
    res.sendStatus(204);
  }
);
```

**Your app** is the [Quickstart](#quickstart) code: it calls these four routes through `getTokenFromYourBackend` and `postToYourBackend`.

**Local development.** If `getHeaders` calls a backend running on your machine, the address depends on where the app runs:

- **iOS Simulator:** `http://localhost:<port>` works. The React Native template allows plain HTTP to `localhost`.
- **Android emulator:** `localhost` is the emulator itself. Use `http://10.0.2.2:<port>` for your machine. Plain HTTP is allowed only in debug builds by default.
- **Physical device:** use your machine's network address, and HTTPS for anything beyond local testing.

## Field keys and field paths

Each field has two names, used by different props:

- **Field key**, such as `firstName`. Used by the drop-in form and `OnboardingFormField`: `fieldProps`, `labels`, `hiddenFields`, the custom layout's `fields` and `OnboardingFormField`'s `field`.
- **Field path**, such as `fullName.firstName`. The field's place in the onboarding data, used for values and errors: `defaultValues`, `values`, `setValue`, `fieldErrors`, `touched` and `OnboardingInputField`'s `path`.

| Field | Field key | Field path | Required | In the drop-in form |
| --- | --- | --- | --- | --- |
| Email | `email` | `email` | yes | yes |
| First name | `firstName` | `fullName.firstName` | yes | yes |
| Middle name | `middleName` | `fullName.middleName` | no | yes; can be hidden |
| Last name | `lastName` | `fullName.lastName` | yes | yes |
| Other names (for example a second last name) | — | `fullName.otherNames.0`, `fullName.otherNames.1`, … | no | no; render with `OnboardingInputField` |
| Street address | `addressLine1` | `address.line1` | yes | yes |
| Apartment, suite, etc. | `addressLine2` | `address.line2` | no | yes; can be hidden |
| City | `city` | `address.city` | yes | yes |
| State | `state` | `address.state` | yes | yes |
| ZIP code | `postalCode` | `address.postalCode` | yes | yes |
| Country | — | `address.country` | no; defaults to `USA` | no |
| Phone number | `phoneNumber` | `phoneNumber` | yes | yes |
| Date of birth | `dateOfBirth` | `dateOfBirth` | yes | yes |
| SSN | `ssn` | none: the SSN never leaves the secure field, so it can't be prefilled or read | yes | yes |

Other-name paths are numbered with whole numbers from `0`, with no gaps; any other index is ignored.

```tsx
<CoinmeOnboardingProvider
  environment="sandbox"
  defaultValues={{ email: user.email, 'address.state': 'WA' }}
>
  <OnboardingInputField
    path="fullName.otherNames.0"
    placeholder="Second last name"
  />
  …
</CoinmeOnboardingProvider>
```

## Drop-in form

`<CustomerOnboardingForm>` renders:

- a label, field and inline error for each of: email, first, middle and last name, street address, apartment, city, state, ZIP, phone number, date of birth and SSN;
- a message for submit failures;
- a submit button.

Inline errors appear once a field has been left (blurred). The submit button stays disabled until every field, including the SSN, is valid, while a submit is in flight, and after a successful submit.

It doesn't collect other names or a country; the country is sent as `USA`.

No colours, fonts or borders are applied. Unstyled, each row stacks label, field and error, with 16 points between rows and 4 points inside a row.

**Style it through pass-through props:**

```tsx
<CustomerOnboardingForm
  environment="sandbox"
  getHeaders={getHeaders}
  onSuccess={onSuccess}
  styles={{
    label: styles.label,
    fieldError: styles.error,
    alert: styles.alert,
    submit: styles.button,
    submitText: styles.buttonText,
  }}
  fieldProps={{
    email: { style: styles.input, placeholder: 'you@example.com' },
    state: { style: styles.stateTrigger, textStyle: styles.stateText },
    ssn: {
      placeholder: '123-45-6789',
      style: styles.input,
      invalidStyle: styles.inputInvalid,
    },
  }}
  submitProps={{ children: 'Create my account' }}
/>
```

Give the SSN field the same `style` as your other inputs and it renders at the same size. The state picker takes its box in `style` and its font in `textStyle`. See [Styling](#styling) for the rest, and [Style the whole form](#style-the-whole-form) for a complete example.

**Essential**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | — | **Required.** Which Coinme environment to onboard into: `'sandbox'` for testing, `'live'` for real customers. Read once on mount. |
| `getHeaders` | `() => Record<string, string> \| Promise<Record<string, string>>` | — | Returns the headers for the onboarding request, for example `{ Authorization: 'Bearer <token>' }`. Called just before each submit, so it can fetch a fresh token. Optional in the types but needed in practice: without an `Authorization` header, every submit fails as `unauthorized`. See [Authentication and headers](#authentication-and-headers). |
| `verifiedPhone` | `{ countryCode: string; number: string }` (`VerifiedPhone`) | — | Optional: a phone number the customer already verified with your own checks, for example `{ countryCode: '1', number: '2065550100' }`. While it's set, the phone field is read-only and shows this number, and the request sends it. Changes apply as they happen. See [Lock the phone to the verified number](#lock-the-phone-to-the-verified-number). |

**Callbacks**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onSuccess` | `(result: { customerId: string; phoneNumber: string }) => void` (`CustomerOnboardingResult`) | — | Called once the customer is onboarded, with their new Coinme customer ID and the phone number they onboarded with (10 digits). Send the `customerId` to your backend from here, since the phone verification token is minted for it, then move the customer on to [phone verification](#phone-verification) (see below). If it throws, the form still counts the submit as a success and stays locked, so the customer can't be sent twice. |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when a submit fails: Coinme rejected it, or it didn't complete. Branch on `error.kind`; see [Error handling](#error-handling). |
| `onVaultError` | `(error: CoinmeOnboardingError) => void` | — | Called when the form can't create its secure SSN field's vault, for example because the package has no configuration for the environment. The form can't be submitted until it's mounted again. |

**Text**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultValues` | `Partial<Record<OnboardingFieldPath, string>>` | `{}` | Values to prefill, keyed by [field path](#field-keys-and-field-paths), for example `{ email: user.email, 'address.state': 'WA' }`. The SSN can't be prefilled. Read once on mount. |
| `labels` | `Partial<Record<CustomerOnboardingFormFieldKey, ReactNode>>` | English (`DEFAULT_FORM_LABELS`) | Label per field, keyed by [field key](#field-keys-and-field-paths), for example `{ ssn: 'SSN' }`. Text or an element. |
| `validationMessages` | `Partial<Record<OnboardingValidationCode \| 'invalidSsn', string>>` | English (`DEFAULT_VALIDATION_MESSAGES`) | Inline error text per validation code (listed under [Input and validation](#input-and-validation)), for example `{ required: 'Required' }`. `invalidSsn` is the SSN field's message. |
| `errorMessages` | `Partial<Record<CoinmeOnboardingErrorKind, string>>` | English (`DEFAULT_ERROR_MESSAGES`) | Text shown when a submit fails, per error kind (listed under [Error handling](#error-handling)), for example `{ duplicate: 'You already have an account.' }`. Without an entry, a non-retryable `invalidRequest` shows the terminal text rather than "try again". |
| `hiddenFields` | `('middleName' \| 'addressLine2')[]` | `[]` | Optional fields to leave out, for example `['middleName']`. Required fields can't be hidden. |

**Styling**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `fieldProps` | `CustomerOnboardingFormFieldProps` (an object keyed by [field key](#field-keys-and-field-paths)) | `{}` | Props passed straight to each field, for example `{ email: { style: styles.input, placeholder: 'you@example.com' } }`. Every key except `state` and `ssn` takes anything a `TextInput` accepts. `state` takes the state picker's props and `ssn` the secure field's; see [Styling](#styling). |
| `style` | `StyleProp<ViewStyle>` | — | Style of the `View` wrapping the form. Same as `styles.form`, applied on top of it. |
| `styles` | `CustomerOnboardingFormStyles` | — | Styles for each part of the form, applied on top of its layout defaults. [Styling](#styling) lists which element each key targets. |
| `submitProps` | `Pressable` props, except `onPress` | — | Props for the submit button. `children` is its label (default `'Continue'`). `style` and `children` may be functions of the press state. The button stays disabled while the form is invalid or submitting, and after a successful submit, whatever `disabled` says. |

**Advanced**

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `timeoutMs` | `number` | `60000` | Fail the submit with a `network` error if no response arrives within this many milliseconds. It starts once `getHeaders` resolves; see [Authentication and headers](#authentication-and-headers). The request may still have reached Coinme; see [Error handling](#error-handling). Pass `Infinity` to wait without a timeout. |
| `children` | `(layout: CustomerOnboardingFormLayout) => ReactNode` | — | Your own layout instead of the default single column. `layout` holds `fields` (one ready-made row per field key), `alert`, `submitButton`, `submit`, `isValid`, `status` and `error`. See [Layout control](#layout-control). |
| `vault` | `CoinmeVault` | — | A vault you created with `createOnboardingVault`, used instead of the form creating its own. Most integrations leave it out. |
| `testID` | `string` | — | Test ID of the `View` wrapping the form, for your tests. |

**Change the text or translate it** with `labels`, `validationMessages` and `errorMessages`. Anything you leave out keeps its English default:

```tsx
<CustomerOnboardingForm
  environment="live"
  getHeaders={getHeaders}
  onSuccess={onSuccess}
  labels={{ email: 'Correo electrónico', firstName: 'Nombre' }}
  validationMessages={{ required: 'Campo obligatorio.' }}
  errorMessages={{ duplicate: 'Ya tienes una cuenta.' }}
/>
```

The English defaults are exported as `DEFAULT_FORM_LABELS`, `DEFAULT_VALIDATION_MESSAGES` and `DEFAULT_ERROR_MESSAGES`, as a checklist of every key to translate.

By default, an `invalidRequest` that isn't retryable shows the terminal text instead of "try again". An `errorMessages.invalidRequest` you provide is shown in both cases, so word it to fit both, for example by not promising that a retry will work.

**After `onSuccess`, move the customer on to phone verification.** Replace the form with `<PhoneVerificationStep>` (see [Phone verification](#phone-verification)). Otherwise the form stays on screen with its values; the submit button stays disabled, so the same customer can't be submitted twice.

### Lock the phone to the verified number

Optional. If you already verified the customer's phone with your own checks before onboarding, pass the number as `verifiedPhone`. The phone field then shows it read-only, and the request sends it, whatever was typed or set in `defaultValues`. This doesn't replace [phone verification](#phone-verification) after onboarding.

```tsx
import {
  CustomerOnboardingForm,
  type VerifiedPhone,
} from '@coinme-security/onboarding-sdk-react-native';

const Onboarding = ({ verifiedPhone }: { verifiedPhone: VerifiedPhone }) => (
  <CustomerOnboardingForm
    environment="sandbox"
    getHeaders={getHeaders}
    onSuccess={onSuccess}
    verifiedPhone={verifiedPhone} // for example { countryCode: '1', number: '2065550100' }
  />
);
```

- **Pass exactly `countryCode: '1'` and a 10-digit `number`, digits only.** Onboarding takes US numbers only, and neither the area code nor the exchange (the first and fourth digits) can be `0` or `1`. Anything else, such as another country code, a `+`, a 9-digit typo or `1005550100`, shows as invalid (`invalidPhone`), and `submit()` rejects with a `'validation'` error.
- **Check the number before you pass it.** The customer can't edit a locked field, so they can't fix a bad verified number themselves: the phone row stays invalid and submit stays disabled. If your own checks can verify a non-US number, catch that before showing the form, for example by telling the customer onboarding needs a US number.
- **The lock can't be lifted from `fieldProps`.** The SDK sets `editable={false}` and `readOnly` on the phone input after your props, so `fieldProps={{ phoneNumber: { editable: true, readOnly: false } }}` has no effect. To style the locked state, pass a different `style` when you pass `verifiedPhone`.
- **It follows the prop.** Unlike `defaultValues`, a new `verifiedPhone` applies straight away. Set it to `undefined` to unlock the field; it then shows what the customer typed before, if anything.

`CoinmeOnboardingProvider` takes the same prop for a [headless](#headless-react-native) form, where `PhoneField` locks the same way. If you render a phone input of your own instead, make it read-only when `lockedPaths` from `useCustomerOnboarding()` includes `'phoneNumber'`:

```tsx
const MyPhoneInput = () => {
  const { values, setValue, lockedPaths } = useCustomerOnboarding();
  return (
    <TextInput
      keyboardType="phone-pad"
      value={values.phoneNumber}
      onChangeText={(text) => setValue('phoneNumber', text)}
      editable={!lockedPaths.includes('phoneNumber')}
    />
  );
};
```

## Layout control

Choose how much of the structure you control. Styling works the same way at every level.

| Level | What you control | How |
| --- | --- | --- |
| **Drop-in** | Styling and copy | `<CustomerOnboardingForm>` with `fieldProps`, `styles`, `labels`, … |
| **Custom layout** | The whole structure: sections, headings, columns, your own content between fields | The form's `children` render prop, which receives the pre-wired rows, the alert and the submit button |
| **Headless** | Everything, including the submit button | `CoinmeOnboardingProvider` with `OnboardingFormField` rows or the bare field components, and `useCustomerOnboarding` |

**Custom layout.** The render prop keeps the SDK's labels, inline errors, accessibility wiring, failure alert and submit button, and lets you place them:

```tsx
<CustomerOnboardingForm
  environment="sandbox"
  getHeaders={getHeaders}
  onSuccess={onSuccess}
>
  {({ fields, alert, submitButton }) => (
    <>
      <Text style={styles.heading}>About you</Text>
      <View style={styles.columns}>
        <View style={styles.column}>{fields.firstName}</View>
        <View style={styles.column}>{fields.lastName}</View>
      </View>
      {fields.email}
      {fields.dateOfBirth}
      <Text style={styles.heading}>Home address</Text>
      {fields.addressLine1}
      {fields.city}
      <View style={styles.columns}>
        <View style={styles.column}>{fields.state}</View>
        <View style={styles.column}>{fields.postalCode}</View>
      </View>
      <MyDisclosure />
      {fields.phoneNumber}
      {fields.ssn}
      {alert}
      {submitButton}
    </>
  )}
</CustomerOnboardingForm>
```

- `fields` holds one row per field. Rows in `hiddenFields` are `null`, and optional fields you don't place are left out.
- **Place every required field**, or the form can never become valid.
- The render prop also receives `submit` (for a button of your own instead of `submitButton`), `isValid`, `status` and `error`. `submit` does nothing while a submit is in flight or after one succeeded.
- The SDK keeps the wrapping `View` and the submit handling.

**Headless with the SDK's rows.** `OnboardingFormField` is one labelled row (label, field and inline error). Use it anywhere inside `CoinmeOnboardingProvider`:

```tsx
<CoinmeOnboardingProvider environment="sandbox">
  <Text style={styles.heading}>About you</Text>
  <OnboardingFormField field="firstName" fieldProps={{ style: styles.input }} />
  <OnboardingFormField field="lastName" fieldProps={{ style: styles.input }} />
  <OnboardingFormField
    field="ssn"
    label="SSN"
    fieldProps={{ style: styles.input }}
  />
  <SubmitButton />
</CoinmeOnboardingProvider>
```

`SubmitButton` is yours; see [Headless React Native](#headless-react-native).

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `field` | `CustomerOnboardingFormFieldKey` | — | **Required.** Which field the row renders, by [field key](#field-keys-and-field-paths), for example `'email'` or `'ssn'`. |
| `label` | `ReactNode` | The English label | The row's label. Text or an element. A text label is also the field's default `accessibilityLabel`. |
| `fieldProps` | Depends on `field` | — | As the drop-in form's `fieldProps` entry for that field, for example `{ style: styles.input }`. |
| `validationMessages` | `Partial<Record<OnboardingValidationCode \| 'invalidSsn', string>>` | English | As for the drop-in form. |
| `styles` | `{ row?, label?, control?, fieldError? }` | — | Styles for the row's parts. |
| `testID` | `string` | — | Test ID of the row. The label gets `<testID>_label`, the `View` around the field `<testID>_control` and the inline error `<testID>_error`. |

## Headless React Native

Build your own onboarding UI from a provider, field components and one hook.

```tsx
import {
  AddressLine1Field,
  CityField,
  CoinmeOnboardingError,
  CoinmeOnboardingProvider,
  CoinmeSsnField,
  DateOfBirthField,
  EmailField,
  FirstNameField,
  LastNameField,
  PhoneField,
  PostalCodeField,
  StateField,
  useCustomerOnboarding,
} from '@coinme-security/onboarding-sdk-react-native';
import { Button, Text } from 'react-native';

const SubmitButton = () => {
  const { isValid, submit, status, error } = useCustomerOnboarding({
    getHeaders: async () => ({
      // YOUR backend route; see "You build".
      Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
    }),
    onSuccess: (result) => {
      // Save the result on YOUR backend first: the verification token is minted from it.
      void postToYourBackend('/your-api/onboarding/complete', result).then(() =>
        startPhoneVerification(result)
      );
    },
  });

  return (
    <>
      <Button
        title="Continue"
        // Also disabled after success, so the same customer isn't submitted twice.
        disabled={!isValid || status === 'submitting' || status === 'success'}
        onPress={() =>
          submit().catch((failure: unknown) => {
            // Shown below from `error`; rethrow anything your onSuccess threw.
            if (!(failure instanceof CoinmeOnboardingError)) throw failure;
          })
        }
      />
      {error && (
        <Text accessibilityRole="alert">
          {error.retryable ? 'Please try again.' : "We couldn't onboard you."}
        </Text>
      )}
    </>
  );
};

export const Onboarding = () => (
  <CoinmeOnboardingProvider environment="sandbox">
    <EmailField
      placeholder="Email"
      accessibilityLabel="Email"
      style={styles.input}
    />
    <FirstNameField
      placeholder="First name"
      accessibilityLabel="First name"
      style={styles.input}
    />
    <LastNameField
      placeholder="Last name"
      accessibilityLabel="Last name"
      style={styles.input}
    />
    <AddressLine1Field
      placeholder="Street address"
      accessibilityLabel="Street address"
      style={styles.input}
    />
    <CityField
      placeholder="City"
      accessibilityLabel="City"
      style={styles.input}
    />
    <StateField accessibilityLabel="State" style={styles.input} />
    <PostalCodeField
      placeholder="ZIP"
      accessibilityLabel="ZIP code"
      style={styles.input}
    />
    <PhoneField accessibilityLabel="Phone number" style={styles.input} />
    <DateOfBirthField accessibilityLabel="Date of birth" style={styles.input} />
    <CoinmeSsnField
      placeholder="123-45-6789"
      style={styles.input}
      invalidStyle={styles.inputInvalid}
    />
    <SubmitButton />
  </CoinmeOnboardingProvider>
);
```

`submit()` returns a promise that rejects when the submit fails, and the hook also exposes the failure as `error`. When you render from `error`, as above, catch the `CoinmeOnboardingError` so the rejection isn't reported as unhandled, and rethrow anything else, such as an error thrown by your `onSuccess`.

The fields in this example have placeholders but no visible labels, so each gets an `accessibilityLabel` for screen readers. In a real form, show a label too, or use `OnboardingFormField` rows, which come labelled.

### `CoinmeOnboardingProvider`

Creates the onboarding vault for `environment` (`'sandbox'` or `'live'`), disposes of it on unmount, and holds the form's values and submit state. Render the field components and use `useCustomerOnboarding` anywhere inside it.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | — | **Required.** As for the drop-in form. Read once on mount; mount the provider again to switch. |
| `defaultValues` | `Partial<Record<OnboardingFieldPath, string>>` | `{}` | As for the drop-in form: values to prefill, keyed by [field path](#field-keys-and-field-paths). Read once on mount. |
| `verifiedPhone` | `VerifiedPhone` | — | As for the drop-in form: the number the customer verified. `PhoneField` (and any `OnboardingInputField` with `path="phoneNumber"`) becomes read-only and shows it, and the request sends it. Changes apply as they happen. See [Lock the phone to the verified number](#lock-the-phone-to-the-verified-number). |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when the vault can't be created. This matches the drop-in form's `onVaultError`, not its `onError`: submit failures go to `useCustomerOnboarding`'s `onError`. |
| `vault` | `CoinmeVault` | — | A vault you created with `createOnboardingVault`, used instead of the provider creating its own. The provider won't clean it up. Most integrations leave it out. |
| `children` | `ReactNode` | — | Your form: field components, and components that call `useCustomerOnboarding`. |

### Field components

| Component | Field path | Default props |
| --- | --- | --- |
| `EmailField` | `email` | `keyboardType="email-address"`, `autoCapitalize="none"`, `autoCorrect={false}`, `autoComplete="email"`, `textContentType="emailAddress"` |
| `FirstNameField` | `fullName.firstName` | `autoComplete="given-name"`, `textContentType="givenName"` |
| `MiddleNameField` | `fullName.middleName` | `autoComplete="additional-name"`, `textContentType="middleName"` |
| `LastNameField` | `fullName.lastName` | `autoComplete="family-name"`, `textContentType="familyName"` |
| `AddressLine1Field` | `address.line1` | `autoComplete="address-line1"`, `textContentType="streetAddressLine1"` |
| `AddressLine2Field` | `address.line2` | `autoComplete="address-line2"`, `textContentType="streetAddressLine2"` |
| `CityField` | `address.city` | `autoComplete="postal-address-locality"`, `textContentType="addressCity"` |
| `StateField` (a picker) | `address.state` | Lists the US states and DC by full name; each option's value is the two-letter code. See below. |
| `PostalCodeField` | `address.postalCode` | `keyboardType="number-pad"`, `autoComplete="postal-code"`, `textContentType="postalCode"` |
| `PhoneField` | `phoneNumber` | `keyboardType="phone-pad"`, `autoComplete="tel-national"`, `textContentType="telephoneNumber"`, `placeholder="(000) 000-0000"`, formats as `(206) 555-0100` |
| `DateOfBirthField` | `dateOfBirth` | `keyboardType="number-pad"`, `autoComplete="birthdate-full"`, `textContentType="birthdate"`, `placeholder="mm/dd/yyyy"`, formats as `MM/DD/YYYY` |
| `OnboardingInputField` | any (`path` prop) | none; use it for fields without a named component |
| `CoinmeSsnField` | the secure SSN | see below |

- **The SDK owns only what binds a field:** `value`, `defaultValue` and `onChangeText`. Every other prop goes straight onto the `TextInput` (`style`, `placeholder`, `testID`, `accessibility*`, `keyboardType`, …, and the defaults above, which you can override).
- **The one exception is a locked field.** While the provider has a `verifiedPhone`, the SDK also owns the phone input's `editable` and `readOnly` and always locks it, so your `editable` or `readOnly={false}` can't unlock it.
- Your `onBlur` still runs.
- `invalidStyle` is applied on top of `style` once a field is touched and invalid.
- Each field forwards its `ref` to the `TextInput`.
- **`PhoneField` and `DateOfBirthField` format as the customer types.** The phone takes US numbers only (see [Phone verification](#phone-verification)): it keeps only digits, so `+` and other characters can't be entered, and it drops a pasted or autofilled `+1`. A longer number keeps all its digits and is reported as `invalidPhone`, never shortened into a different US number. A digit typed into a complete phone number or date is ignored. The date of birth is typed as `MM/DD/YYYY` and sent as the `YYYY-MM-DD` the endpoint expects. A one-digit month or day followed by `/` gets a leading zero (`6/15/1990` shows as `06/15/1990`), and a pasted, autofilled or `defaultValues` date in `YYYY-MM-DD` form is shown as `MM/DD/YYYY`. Pass `mask={undefined}` to turn formatting off. Any plain field takes a `mask` of your own (see below).

**Format a field as the customer types.** Give any plain field a `mask`, an `OnboardingInputMask` with two functions: `toDigits` keeps the digits the field allows, and `format` shows them. `toDigits` gets the stored value, and the field's full new text (separators included) when the customer types, pastes or autofills; after a deletion it gets only the digits left. Add each separator only once a digit follows it, so backspace never gets stuck on one:

```tsx
import {
  PostalCodeField,
  type OnboardingInputMask,
} from '@coinme-security/onboarding-sdk-react-native';

// ZIP+4: 98101-1234
const zipMask: OnboardingInputMask = {
  toDigits: (value) => value.replace(/\D/g, '').slice(0, 9),
  format: (digits) =>
    digits.length > 5 ? `${digits.slice(0, 5)}-${digits.slice(5)}` : digits,
};

<PostalCodeField mask={zipMask} style={styles.input} />;
// In the drop-in form: fieldProps={{ postalCode: { mask: zipMask } }}
```

The value is stored as shown, so the formatted value must still pass [validation](#input-and-validation) (`98101-1234` does). It's also read back through `toDigits` on every render, so `format(toDigits(format(digits)))` must equal `format(digits)`. A `format` that adds digits, such as a `+1 ` prefix, breaks this: `+1 (206` reads back as `1206`. Keep such text outside the value, for example in the label.

**`StateField`.** React Native has no `<select>`, so the state picker is a pressable trigger showing the selected state's name. Pressing it opens a `Modal` with a `FlatList` of the US states and DC, by full name, in alphabetical order. The value submitted is the two-letter code.

- The SDK owns the trigger's `onPress` and `children`, the modal's `visible` and `onRequestClose`, and the list's `data`, `renderItem` and `keyExtractor`. Every other trigger prop is spread onto the `Pressable`, and its `ref` is the `Pressable`'s.
- `style` and `invalidStyle` style the trigger, `textStyle` its text, and `placeholderTextColor` the text while nothing is selected. The trigger is a `Pressable` around a `Text`, not a `TextInput`, so it doesn't take your input style as-is: put the box (size, border, padding, background) in `style` with `justifyContent: 'center'` to centre the text vertically, and the font and colour in `textStyle`. Font and colour in `style` are ignored.
- `emptyOptionLabel` is the trigger's text while nothing is selected (default `'Select a State'`).
- `options` replaces the list, for example to translate it: `options={[{ value: 'NY', label: 'Nueva York' }, …]}`. Values must be two-letter state codes.
- `modalProps` and `listProps` pass through to the `Modal` and `FlatList`. `optionStyle` and `optionTextStyle` style the built-in rows, and `renderOption` replaces them.
- The list opens as a page sheet by default (`presentationStyle: 'pageSheet'`), which iOS customers can swipe down to close; Android's back button closes it. If you make it full-screen through `modalProps`, also pass a `renderHeader` with a button that calls `close`, or iOS customers can't leave the list without choosing a state.
- Closing the list marks the field as touched.

```tsx
<StateField
  accessibilityLabel="State"
  style={styles.stateTrigger}
  textStyle={styles.stateText}
  placeholderTextColor="#9ca3af"
  renderHeader={({ close }) => <Button title="Done" onPress={close} />}
/>
```

**`CoinmeSsnField`** renders the vault's secure field.

- The SDK owns the field's name, `type: 'ssn'` and its validation, the `###-##-####` mask, and submits the nine digits without dashes. The mask can't be changed or turned off.
- Typed digits are hidden by default (`secureTextEntry`). Pass `secureTextEntry={false}` to show them, or add a show/hide button (see below).
- On iOS, typing into the field again after leaving it replaces the whole SSN: iOS clears a hidden text field when editing starts again. A show/hide button lets the customer fix a digit without retyping all nine.
- The SDK sets `accessibilityLabel` to `'Social Security Number'` (in `OnboardingFormField` and `CustomerOnboardingForm`, to the row's label when it's text). Pass `accessibilityLabel` to change it, for example when you translate the form.
- Every other secure field (`VGSTextInput`) prop passes straight through: `placeholder`, `placeholderTextColor`, `containerStyle`, `textStyle`, `testID`, `accessibilityHint`, and props the vault provider adds later.
- `onStateChange` is called with the field's metadata only: `type`, `fieldName`, `isValid`, `isEmpty`, `isDirty`, `isFocused`, `inputLength`, `validationErrors` and, once the SSN is valid, `last4`. Any other key the vault reports is dropped. Never the full number.
- `style` and `invalidStyle` take the same style as your plain fields; see [Styling](#styling).
- Its `ref` is the secure field, with `focus()` and `blur()`. The type is `CoinmeSsnFieldRef`.

**Let the customer show the SSN digits.** Toggle `secureTextEntry`:

```tsx
const [hidden, setHidden] = useState(true);

<>
  <CoinmeSsnField secureTextEntry={hidden} style={styles.input} />
  <Button
    title={hidden ? 'Show' : 'Hide'}
    accessibilityState={{ checked: !hidden }}
    onPress={() => setHidden(!hidden)}
  />
</>;
```

Only the display changes; the SSN stays inside the secure field.

### `useCustomerOnboarding(options)`

Call it in any component inside `CoinmeOnboardingProvider`. Its options:

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `getHeaders` | `() => Record<string, string> \| Promise<Record<string, string>>` | — | As for the drop-in form: returns the request headers, called just before each submit. Needed in practice. |
| `timeoutMs` | `number` | `60000` | Fail the submit with a `network` error if no response arrives within this many milliseconds. It starts once `getHeaders` resolves; see [Authentication and headers](#authentication-and-headers). The request may still have reached Coinme; see [Error handling](#error-handling). Pass `Infinity` to wait without a timeout. |
| `onSuccess` | `(result: CustomerOnboardingResult) => void` | — | Called when a submit made with this hook's `submit` succeeds, with `{ customerId, phoneNumber }`. If it throws, `status` stays `'success'` and `submit()` rejects with your error. It isn't awaited, so only a synchronous throw reaches `submit()`; a rejected `async` callback is an unhandled rejection. |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when a submit made with this hook's `submit` fails, including when client-side validation stops it (`kind: 'validation'`). |

It returns:

| Property | Type | Description |
| --- | --- | --- |
| `values` | `OnboardingFormValues` | The current value of each plain field as shown, keyed by [field path](#field-keys-and-field-paths), for example `values['address.city']`. A formatted field holds its formatted value, such as `'(206) 555-0100'` or `'06/15/1990'`; it's converted to the request's format on submit. With a `verifiedPhone`, `phoneNumber` holds it formatted the same way, `'(206) 555-0100'` (or, for a number that isn't a US one, `'+65 91234567'`, marked `invalidPhone`). |
| `setValue` | `(path: OnboardingFieldPath, value: string) => void` | Sets a plain field's value. The field components call it for you; use it for inputs of your own. Ignored for a locked field, so unlocking brings back what was entered before the lock. |
| `fieldErrors` | `Partial<Record<OnboardingFieldPath, OnboardingValidationCode>>` | The validation code for each plain field that's currently invalid, touched or not, for example `{ 'address.postalCode': 'invalidPostalCode' }`. Empty when every plain field is valid. |
| `touched` | `Partial<Record<OnboardingFieldPath, boolean>>` | Which fields are touched, for example `{ email: true }`. Show a field's error only once it's touched. |
| `lockedPaths` | `readonly OnboardingFieldPath[]` | The fields the customer can't edit: `['phoneNumber']` while the provider has a `verifiedPhone`, otherwise `[]`. The field components handle this; check it to make inputs of your own read-only too. |
| `ssnState` | `OnboardingSsnState \| null` | The SSN field's state: `isValid`, `isEmpty`, `isDirty`, `isFocused`, `isTouched`, `errorMessages` and, once the SSN is valid, `last4`. Empty and invalid from the moment `CoinmeSsnField` is rendered; `null` while no SSN field is rendered or the vault isn't ready. Never the full SSN. |
| `isValid` | `boolean` | `true` when the vault is ready and every field, including the SSN, is valid. Use it to enable your submit button. |
| `vaultStatus` | `'loading' \| 'ready' \| 'error'` | Whether the vault for the secure SSN field is ready. |
| `vaultError` | `CoinmeOnboardingError \| null` | Why the vault couldn't be created, when `vaultStatus` is `'error'`. |
| `submit` | `() => Promise<CustomerOnboardingResult>` | Validates and submits. Resolves with `{ customerId, phoneNumber }`, or rejects with a `CoinmeOnboardingError`, or with your own error if `onSuccess` throws. Rejects with `validation`, before anything is sent, when no `CoinmeSsnField` is rendered. Calling it again while a submit is in flight returns the same promise instead of submitting twice. |
| `status` | `'idle' \| 'submitting' \| 'success' \| 'error'` | The state of the most recent submit; `'idle'` before the first one. |
| `error` | `CoinmeOnboardingError \| null` | Why the most recent submit failed. |
| `result` | `CustomerOnboardingResult \| null` | The result of the most recent successful submit: `{ customerId, phoneNumber }`. |

To show an error only after the customer has left a field:

```tsx
import {
  DEFAULT_VALIDATION_MESSAGES,
  EmailField,
  useCustomerOnboarding,
  type OnboardingFieldPath,
} from '@coinme-security/onboarding-sdk-react-native';
import { Text } from 'react-native';

const FieldError = ({ path }: { path: OnboardingFieldPath }) => {
  const { fieldErrors, touched } = useCustomerOnboarding();
  const code = touched[path] ? fieldErrors[path] : undefined;
  return code ? (
    <Text style={styles.error}>{DEFAULT_VALIDATION_MESSAGES[code]}</Text>
  ) : null;
};

// Inside CoinmeOnboardingProvider:
<>
  <EmailField style={styles.input} />
  <FieldError path="email" />
</>;
```

### Types for the vault and the SSN field

The types you need to name in your code are all exported from this package:

- `CoinmeVault`: the `vault` prop, and what `createOnboardingVault` returns.
- `CoinmeSsnFieldRef`: the `ref` of `CoinmeSsnField`.
- `CoinmeSsnFieldProps`: the SSN field's props, including `style` and `invalidStyle`.

```tsx
import {
  CoinmeSsnField,
  type CoinmeSsnFieldRef,
} from '@coinme-security/onboarding-sdk-react-native';
import { useRef } from 'react';

const ssnRef = useRef<CoinmeSsnFieldRef>(null);
// …
<CoinmeSsnField ref={ssnRef} style={styles.input} />;
// Later, for example to move focus to the SSN:
ssnRef.current?.focus();
```

`CoinmeVault` comes from the Coinme Vault SDK, which this package installs for you. You don't need to add it to your own dependencies.

## Styling

Styling is pass-through at every level: no theme object, no bundled colours or fonts, no Coinme branding.

**Form and row styles.** The drop-in form takes `style` for its wrapping `View` and a `styles` object for its parts; `OnboardingFormField` takes the row keys. Each style goes on top of the form's minimal layout defaults, so yours win:

| Element | `styles` key | Default |
| --- | --- | --- |
| The `View` wrapping the form | `form` (or `style`) | 16 points between rows |
| Each row (label, field and inline error) | `row` | 4 points between its parts |
| Each label `Text` | `label` | — |
| The `View` around each field | `control` | — |
| Inline field error `Text` | `fieldError` | — |
| Submit-failure message `Text` | `alert` | — |
| Submit button (`Pressable`) | `submit` | centred content, 12 points of vertical padding |
| Submit button's label `Text`, when it's text | `submitText` | — |
| Submit button while disabled, on top of `submit` | `submitDisabled` | `opacity: 0.5` |

For a pressed look, pass a function as `submitProps.style`, for example `({ pressed }) => pressed && styles.buttonPressed`.

**Plain fields.** Pass any `TextInput` prop through `fieldProps` (drop-in) or directly on the field component (headless): `style`, `placeholder`, `placeholderTextColor`, `testID`, …. Style the invalid state with `invalidStyle`, which is applied on top of `style` once the field is touched and invalid.

**The state picker is a `Pressable`, not a `TextInput`.** Unlike the SSN field, it doesn't split your input style for you:

- **`style` and `invalidStyle`** take the box: size, border, padding, background. Add `justifyContent: 'center'`, or the text sits at the top of the box.
- **`textStyle`** takes the font and colour, and `placeholderTextColor` the colour while nothing is selected. Font and colour in `style` are ignored.
- **The list is unstyled.** Its rows are plain text with no padding or dividers, and the sheet is white. Style the rows with `optionStyle` and `optionTextStyle` (or draw your own with `renderOption`), colour the list with `listProps.style`, and add a title or a Done button with `renderHeader`. `modalProps` passes through to the `Modal`.
- **On Android the list is full screen.** In an edge-to-edge app (the default for new React Native and Expo projects) it draws under the status and navigation bars. Wrap your `renderHeader` in a `SafeAreaView` from `react-native-safe-area-context` with `edges={['top']}`, and pad the end of the list with `listProps={{ contentContainerStyle: { paddingBottom: insets.bottom } }}` (from `useSafeAreaInsets()`).

See [`StateField`](#field-components) for every prop.

**The SSN field is the vault's secure field, not a `TextInput`.** It takes a container style and a text style instead of one `style`. The SDK bridges the two:

- **Give it the same `style` as your plain fields.** The SDK splits it: text styles (font, colour, alignment) and padding go to the input, everything else (size, border, background, margins) to its container. So the SSN field renders at the same size as your other inputs.
- **`invalidStyle`** is split the same way and applied once the SSN is touched and invalid.
- **`containerStyle` and `textStyle`** are the secure field's own props. They're applied on top, for anything the split doesn't cover.
- `placeholder` and `placeholderTextColor` pass straight through.
- Until the vault is ready, the field renders an empty box styled like its container, so the layout doesn't jump.
- **No field has a focused style built in.** For plain fields, track focus with `onFocus` and `onBlur` (yours still run). For the SSN field, read `isFocused` from `onStateChange`, or from `ssnState` in `useCustomerOnboarding`, and pass a `containerStyle`.

```tsx
const styles = StyleSheet.create({
  input: {
    height: 44,
    borderWidth: 1,
    borderColor: '#d1d5db',
    borderRadius: 8,
    paddingHorizontal: 12,
    fontSize: 16,
    color: '#1a1a1a',
  },
  inputInvalid: { borderColor: '#dc2626' },
});

<CoinmeSsnField
  placeholder="123-45-6789"
  placeholderTextColor="#9ca3af"
  style={styles.input}
  invalidStyle={styles.inputInvalid}
/>;
```

**Masks.** `PhoneField` and `DateOfBirthField` format as the customer types. Turn that off with `mask={undefined}`, or pass your own `mask` to any plain field; see [Field components](#field-components). The SSN field's `###-##-####` mask is fixed.

### Style the whole form

The drop-in form has no "style every input" shortcut: each field takes its own `fieldProps` entry. Define the input props once and reuse them. The plain fields and the SSN field share them; the state picker gets the same box split into `style` and `textStyle`:

```tsx
import {
  CustomerOnboardingForm,
  type CustomerOnboardingFormFieldProps,
} from '@coinme-security/onboarding-sdk-react-native';
import { Button, ScrollView, StyleSheet, View } from 'react-native';

const box = {
  height: 44,
  borderWidth: 1,
  borderColor: '#d1d5db',
  borderRadius: 8,
  paddingHorizontal: 12,
  backgroundColor: '#ffffff',
};
const text = { fontSize: 16, color: '#111827' };

const styles = StyleSheet.create({
  input: { ...box, ...text },
  inputInvalid: { borderColor: '#dc2626' },
  // The state picker: the same box with its text centred, and the text styled separately.
  stateTrigger: { ...box, justifyContent: 'center' },
  stateText: text,
  listHeader: {
    alignItems: 'flex-end',
    padding: 8,
    backgroundColor: '#ffffff',
  },
  list: { backgroundColor: '#ffffff' },
  option: {
    paddingVertical: 14,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#e5e7eb',
  },
  label: { fontSize: 14, fontWeight: '600', color: '#111827' },
  error: { fontSize: 13, color: '#dc2626' },
  alert: { fontSize: 14, color: '#dc2626' },
  button: { borderRadius: 8, backgroundColor: '#111827' },
  buttonText: { fontSize: 16, fontWeight: '600', color: '#ffffff' },
});

const input = {
  style: styles.input,
  invalidStyle: styles.inputInvalid,
  placeholderTextColor: '#9ca3af',
};

const fieldProps: CustomerOnboardingFormFieldProps = {
  email: { ...input, placeholder: 'you@example.com' },
  firstName: input,
  middleName: input,
  lastName: input,
  addressLine1: input,
  addressLine2: input,
  city: input,
  postalCode: input,
  phoneNumber: input,
  dateOfBirth: input,
  state: {
    style: styles.stateTrigger,
    invalidStyle: styles.inputInvalid,
    textStyle: styles.stateText,
    placeholderTextColor: '#9ca3af',
    listProps: { style: styles.list },
    optionStyle: styles.option,
    optionTextStyle: text,
    renderHeader: ({ close }) => (
      <View style={styles.listHeader}>
        <Button title="Done" onPress={close} />
      </View>
    ),
  },
  ssn: { ...input, placeholder: '123-45-6789' },
};

export const Onboarding = () => (
  <ScrollView
    contentContainerStyle={{ padding: 16 }}
    automaticallyAdjustKeyboardInsets
    keyboardDismissMode="on-drag"
    keyboardShouldPersistTaps="handled"
  >
    <CustomerOnboardingForm
      environment="sandbox"
      getHeaders={getHeaders}
      onSuccess={onSuccess}
      fieldProps={fieldProps}
      styles={{
        label: styles.label,
        fieldError: styles.error,
        alert: styles.alert,
        submit: styles.button,
        submitText: styles.buttonText,
      }}
    />
  </ScrollView>
);
```

The colours are fixed here. For dark mode, pick them with `useColorScheme()`, including the list's and the header's backgrounds, which otherwise stay white. With the headless components, pass the same props directly to each field.

For every secure field option, see our vault provider's [React Native SDK reference](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/react-native-sdk); everything except the props the SDK owns passes through `CoinmeSsnField`.

## Phone verification

> **A first version.**
>
> Phone verification is a first version of this step and will be extended.

> **US phone numbers only.**
>
> Onboarding and SMS verification presently support US phone numbers only: a 10-digit number with country code `1`, whose area code and exchange don't start with `0` or `1`. If Coinme adds support for other jurisdictions, it will release an update.

> **Authorize it with a token for this customer.**
>
> Every send and every check needs a Transient Auth Token your backend mints for the `customerId` that onboarding returned. Not your partner access token, and not the sign-up session token you onboarded with. The token is the only thing that ties the calls to the customer. Your backend mints it for the `customerId` it saved when onboarding succeeded; the app never sends one. See [You build](#you-build).

Coinme doesn't consider KYC complete until a newly onboarded customer verifies their phone. Verification covers steps 4 to 8 of the [recommended integration flow](#recommended-integration-flow): it runs right after onboarding, and again whenever an unverified customer signs back in, always against the phone number the customer onboarded with. It succeeds only when the code checks out; anything else is a failure, and the customer hasn't completed KYC.

Pass `phoneNumber` from the onboarding result (or the copy you stored on your backend) as is. Don't let the customer type a different number at this step. Coinme texts whatever number it's sent and, once the code checks out, records that number as the customer's verified phone; it doesn't check it against the onboarded number. Making sure it's the onboarded number is up to you.

A code works for about a minute (60 seconds) after it's sent. Coinme currently reports an expired code as `codeIncorrect`, not `codeExpired`, so when a code is rejected, offer to send a new one as well as to type it again. The drop-in step always shows a resend button for this.

The calls go to the Coinme API host for the `environment`, which is built into the package: `caas-staging.coinme.com` in sandbox and `caas.coinme.com` in live. That's a different host from the onboarding submit.

### `PhoneVerificationStep`

The drop-in step. It shows where the code will go (all but the last 4 digits hidden), sends the code when the customer presses the button, takes the code, and calls `onVerified` once it checks out. Nothing is sent until the customer presses the button. See the [Quickstart](#quickstart) for it in context:

```tsx
<PhoneVerificationStep
  environment="sandbox"
  phoneNumber={onboarded.phoneNumber}
  // YOUR backend route; it mints the token for the customerId it saved. See "You build".
  getHeaders={async () => ({
    Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
  })}
  onVerified={() => goToWelcome(onboarded.customerId)}
  onError={(error) => reportVerificationFailure(error.kind)}
/>
```

Like the form, the step is a plain `View`: render it inside your own `ScrollView`. It moves through three screens (the `screen` a custom layout receives):

- `'send'`: "we'll text a code to (•••) •••-0100" and the send button. A failed send stays here.
- `'code'`: one box per digit (6 by default; set `codeLength` to change it), the verify button and a resend button. The code is checked as soon as the last box is filled; Verify stays as a fallback. Typing a digit moves to the next box, Backspace on an empty box clears and goes back to the previous one, and non-digits are ignored. The boxes open the number pad, and the first one has `textContentType="oneTimeCode"` (iOS) and `autoComplete="sms-otp"` (Android), so the keyboard can offer the code from the text: the autofilled code, or a pasted one, fills every box at once. A paste with fewer or more digits than the code replaces the boxes but isn't checked until the customer completes it or taps Verify. So is a code that lands in a box already holding its first or last digit, because it can't be told apart from a partial paste merged with that digit. A failed check stays here, with the error alert:
  - a wrong or expired code clears the boxes and puts the customer back in the first one;
  - too many attempts with a wait (`retryAfterSeconds`) disables the boxes, Verify and resend and shows a countdown until the customer can try again;
  - once every attempt is used (`attemptsExhausted`), everything stays disabled and the alert points the customer to support.
- `'verified'`: the phone is verified.

Once the customer has pressed a button, the step moves focus to the first code box when it appears and reads each new screen's text, any error and the start of a countdown aloud with the platform screen reader.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | — | **Required.** The environment you onboarded in. |
| `phoneNumber` | `string` | — | **Required.** `phoneNumber` from the onboarding result. |
| `getHeaders` | `() => Record<string, string> \| Promise<Record<string, string>>` | — | Returns the headers for each verification call: `{ Authorization: 'Bearer <token>' }` with a Transient Auth Token your backend mints for the new `customerId`, never your partner access token or the sign-up session token. Called before every send and every check, so fetch a fresh token inside it. |
| `onVerified` | `() => void` | — | Called once the code checks out. If it throws, the step stays verified. |
| `onError` | `(error: CoinmeOnboardingError) => void` | — | Called when a send or a check fails. See the kinds below. |
| `codeLength` | `number` | `6` | How many digits the code has: one box per digit. |
| `timeoutMs` | `number` | `60000` | Fail a call as `network` if no response arrives in this many milliseconds. It starts once `getHeaders` resolves. |
| `apiBaseUrl` | `string` | Coinme's | Send the calls to this base URL instead, for example a route on your own server that forwards them to Coinme. |
| `labels` | `Partial<PhoneVerificationStepLabels>` | English | The step's text, as strings so it can be read aloud. `sendPrompt`, `codeSent` and `verified` are functions that get the masked number; `digit(position, length)` is each box's `accessibilityLabel` (default `'Digit 1 of 6'`); `retryIn(seconds)` is the countdown text. The defaults are exported as `DEFAULT_PHONE_VERIFICATION_LABELS`. |
| `errorMessages` | `Partial<Record<CoinmeOnboardingErrorKind, string>>` | English | The error alert text per kind. Without an entry, the step uses the form's `DEFAULT_ERROR_MESSAGES`, and points the customer to support once every attempt is used. |
| `inputProps` | `TextInput` props, except `value`, `defaultValue` and `onChangeText` | — | Pass-through props spread onto every code box `TextInput` (`style`, `placeholder`, `placeholderTextColor`, …). `testID` gets `_<index>` appended on each box, for example `code_0`. `keyboardType` (`'number-pad'`), `selectTextOnFocus`, `accessibilityLabel` (`labels.digit`) and, on the first box only, `textContentType` and `autoComplete` (`'off'` on the others) are defaults you can replace. Don't set `maxLength`: the autofill drops the whole code into one box. Your `onKeyPress` and `onSubmitEditing` run before the step's own handling. |
| `submitProps`, `resendProps` | `Pressable` props, except `onPress` and `children` | — | Pass-through props for the send/verify button and the resend button (`testID`, `hitSlop`, …). The text comes from `labels`. `style` may be a function of the press state. The step keeps both disabled while a call is in flight, during a countdown and once every attempt is used, and the verify button until every box is filled, whatever `disabled` says. |
| `style` | `StyleProp<ViewStyle>` | — | Style of the `View` wrapping the step. Same as `styles.form`, applied on top of it. |
| `styles` | `PhoneVerificationStepStyles` | — | Styles for each part, applied on top of the step's layout defaults: `form` (16 points between parts), `message`, `row` (4 points between label and boxes), `label`, `control`, `codeGroup` (the boxes' `View`; a row with 8 points between boxes), `codeBox` (each box, under `inputProps.style`; centred text and a 32-point minimum width), `hint` (the countdown), `alert`, `submit` and `resend` (centred, 12 points of vertical padding), `submitText`, `resendText` and `submitDisabled` (on top of a disabled button; default `opacity: 0.5`). |
| `children` | `(layout: PhoneVerificationStepLayout) => ReactNode` | — | A custom layout. Receives the pre-wired `codeField` (the labelled boxes), `submitButton`, `resendButton`, `message`, `retryHint` (the countdown) and `alert` (each `null` when it doesn't belong on the current `screen`), plus `screen`, `status`, `error`, `retryInSeconds` and `submit` (what `submitButton` does, for your own button). |
| `testID` | `string` | — | Test ID of the `View` wrapping the step. |

### `usePhoneVerification(options)`

The hook the step is built on, for your own UI. It takes the same `environment`, `phoneNumber`, `getHeaders`, `onVerified`, `onError`, `timeoutMs` and `apiBaseUrl`, and works without `CoinmeOnboardingProvider`.

| Returns | Type | Description |
| --- | --- | --- |
| `status` | `'idle' \| 'sending' \| 'codeSent' \| 'verifying' \| 'verified' \| 'error'` | Where verification is. |
| `error` | `CoinmeOnboardingError \| null` | Why the last call failed, when `status` is `'error'`. |
| `codeSentAt` | `number \| null` | When the last code was sent (milliseconds since the epoch). `null` until one is sent, so after a failure it tells you whether to keep showing the code input. |
| `sendCode` | `() => Promise<void>` | Texts a code to `phoneNumber`. Calling it again sends a new code, and the previous one stops working. |
| `verifyCode` | `(code: string) => Promise<void>` | Checks the code the customer typed. Spaces and dashes are ignored. |
| `reset` | `() => void` | Back to `'idle'`, dropping any result in flight. |

`sendCode` and `verifyCode` reject with the same `CoinmeOnboardingError` that's put in `error` and passed to `onError`, so catch them. While a call is in flight, calling the same one again returns that call's promise instead of sending a second request, and calling the other one waits for it to settle first. After `reset` or unmount, a call in flight resolves without changing anything, so act on success in `onVerified` (or when `status` is `'verified'`), not on the promise alone.

```tsx
const VerifyPhone = ({ customerId, phoneNumber }: CustomerOnboardingResult) => {
  const [code, setCode] = useState('');
  const { status, error, codeSentAt, sendCode, verifyCode } =
    usePhoneVerification({
      environment: 'sandbox',
      phoneNumber,
      // YOUR backend route; it mints the token for the customerId it saved. See "You build".
      getHeaders: async () => ({
        Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
      }),
      onVerified: () => goToWelcome(customerId),
    });
  const ignoreSdkError = (caught: unknown) => {
    // SDK failures are in `error`; rethrow anything your callbacks threw.
    if (!(caught instanceof CoinmeOnboardingError)) throw caught;
  };

  if (status === 'verified') return <Text>Your phone is verified.</Text>;
  if (codeSentAt === null) {
    return (
      <View>
        {error && <Text accessibilityRole="alert">{error.message}</Text>}
        <Button
          title="Text me a code"
          disabled={status === 'sending'}
          onPress={() => sendCode().catch(ignoreSdkError)}
        />
      </View>
    );
  }
  return (
    <View>
      <TextInput
        accessibilityLabel="Verification code"
        keyboardType="number-pad"
        textContentType="oneTimeCode"
        autoComplete="sms-otp"
        value={code}
        onChangeText={setCode}
      />
      {error && <Text accessibilityRole="alert">{error.message}</Text>}
      <Button
        title="Verify"
        disabled={status === 'verifying'}
        onPress={() => verifyCode(code).catch(ignoreSdkError)}
      />
      <Button
        title="Send a new code"
        onPress={() => sendCode().catch(ignoreSdkError)}
      />
    </View>
  );
};
```

### When verification fails

The failures specific to this step (see [Error handling](#error-handling) for the full list):

| `kind` | What to tell the customer |
| --- | --- |
| `codeIncorrect` | The code is wrong, or it expired (a code works for about a minute). Let them type it again or send a new one. |
| `codeExpired` | The code expired. Send a new one. |
| `tooManyAttempts` | Too many failed checks, or the account's phone number has been changed too often. `error.retryAfterSeconds` says how long to wait. When `error.attemptsExhausted` is `true`, they've used every attempt: point them to support. |
| `smsNotSent` | Coinme didn't confirm the text was sent. Try again. |
| `phoneNotSupported` | The number can't receive verification texts (not a mobile number, a carrier that isn't allowed, or recently used by another account). Point them to support. |
| `phoneAlreadyInUse` | The number belongs to another Coinme account. Point them to support. |
| `unauthorized` | The token was missing or expired, or wasn't a Transient Auth Token minted for this `customerId`: a partner access token or the sign-up session token is rejected too. Mint a fresh one for the customer and try again. |

Until a code checks out, the customer hasn't completed KYC, whatever your UI shows. A customer who leaves before verifying still exists at Coinme: a second onboarding with the same details fails as `duplicate`. Send them back to verification when they return (step 8 of the [recommended integration flow](#recommended-integration-flow)).

## Core API

The core functions let you create the vault and submit yourself, without the drop-in form or `useCustomerOnboarding`. The React Native components are built on them; the secure SSN field still comes from `CoinmeSsnField` inside a `CoinmeOnboardingProvider`.

### 1. Create the onboarding vault and the secure SSN field

```tsx
import {
  CoinmeOnboardingProvider,
  CoinmeSsnField,
  createOnboardingVault,
  type CoinmeVault,
} from '@coinme-security/onboarding-sdk-react-native';
import { useEffect, useState } from 'react';

const OnboardingScreen = () => {
  const [vault, setVault] = useState<CoinmeVault | null>(null);

  useEffect(() => {
    let cancelled = false;
    let created: CoinmeVault | undefined;
    createOnboardingVault({ environment: 'sandbox' }).then(
      (newVault) => {
        // Unmounted before the vault was ready: dispose of it, don't use it.
        if (cancelled) {
          newVault.dispose();
          return;
        }
        created = newVault;
        setVault(newVault);
      },
      (error) => reportOnboardingFailure(error.kind)
    );
    return () => {
      cancelled = true;
      created?.dispose();
    };
  }, []);

  if (!vault) return null;
  return (
    <CoinmeOnboardingProvider environment="sandbox" vault={vault}>
      <CoinmeSsnField style={styles.input} />
      {/* your own inputs, and a button that calls submitCustomerOnboarding */}
    </CoinmeOnboardingProvider>
  );
};
```

- `CoinmeSsnField` needs a `CoinmeOnboardingProvider` above it. Give the provider your vault and it won't create or dispose of one itself.
- Call `vault.dispose()` when the form goes away.
- `createOnboardingVault` rejects with a `configuration` error when the package has no onboarding configuration for the environment.

### 2. Collect the other details and submit

```typescript
import {
  CoinmeOnboardingError,
  submitCustomerOnboarding,
} from '@coinme-security/onboarding-sdk-react-native';

try {
  const { customerId, phoneNumber } = await submitCustomerOnboarding(
    vault,
    {
      email: 'jane.doe@example.com',
      fullName: { firstName: 'Jane', lastName: 'Doe' },
      address: {
        line1: '123 Main St',
        city: 'Seattle',
        state: 'WA',
        postalCode: '98101',
      },
      phoneNumber: '(206) 555-0100',
      dateOfBirth: '1990-06-15',
    },
    {
      headers: {
        // YOUR backend route; see "You build".
        Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
      },
    }
  );
} catch (error) {
  if (error instanceof CoinmeOnboardingError) {
    // See "Error handling" below.
  }
}
```

`submitCustomerOnboarding` validates the input first. If validation fails, it throws a `'validation'` error and sends nothing. The SSN comes from the secure field; you never pass it in.

Its options are `headers`, `timeoutMs` (default 60 000; `Infinity` waits without a timeout; after a timeout the request may still have reached Coinme, see [Error handling](#error-handling)) and `now` (the date ages are measured against; defaults to today).

**Submitting through the vault yourself.** In the next examples, `input` is the customer details object from the example above, and `headers` the headers object. For full control of the request, `buildCustomerOnboardingRequest(input)` returns the `{ extraData, customRequestStructure }` pair for `vault.submit`, and `toCoinmeOnboardingError` normalizes whatever it throws:

```typescript
try {
  const result = await vault.submit({
    ...buildCustomerOnboardingRequest(input),
    headers,
  });
} catch (error) {
  throw toCoinmeOnboardingError(error);
}
```

- This skips client-side validation, so call `validateCustomerOnboardingInput` first.
- `toCoinmeOnboardingError` classifies a failed (non-2xx) response by its HTTP status only, so it can't read a CAAS error code from the response body. `submitCustomerOnboarding` reads the body, so it also recognizes the codes in [Error handling](#error-handling).

### 3. Verify the phone

Once onboarding returns, text the customer a code with `sendPhoneVerificationCode`, then check the code they type with `validatePhoneVerificationCode`. Both take a Transient Auth Token your backend mints for the new `customerId`, never your partner access token (see [You build](#you-build)), so fetch fresh headers for each call. This example reuses the Quickstart's helpers; it's one way to do it, not the only way:

```typescript
import {
  CoinmeOnboardingError,
  sendPhoneVerificationCode,
  validatePhoneVerificationCode,
} from '@coinme-security/onboarding-sdk-react-native';

const result = await submitCustomerOnboarding(vault, input, { headers });
// Save customerId and phoneNumber on YOUR backend first: the verification token is minted from it.
await postToYourBackend('/your-api/onboarding/complete', result);

const verificationOptions = async () => ({
  environment: 'sandbox' as const,
  // YOUR backend route; it mints the token for the customerId it saved. See "You build".
  headers: {
    Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/phone-verification/token')}`,
  },
});

// When the customer asks for the code:
await sendPhoneVerificationCode(
  { phoneNumber: result.phoneNumber },
  await verificationOptions()
);

// When they submit it:
try {
  await validatePhoneVerificationCode(
    { validationCode: code },
    await verificationOptions()
  );
  showVerified();
} catch (error) {
  if (!(error instanceof CoinmeOnboardingError)) throw error;
  // An expired code is currently reported as codeIncorrect, so offer a new code there too.
  if (error.kind === 'codeIncorrect') showTryAgainOrSendNewCode();
  else if (error.kind === 'codeExpired') showSendNewCode();
  else showVerificationFailed(error.kind); // see "When verification fails"
}
```

- `sendPhoneVerificationCode` rejects with `'validation'` (`fieldErrors.phoneNumber: 'invalidPhone'`) before sending when the number isn't a US number, and with `'smsNotSent'` when Coinme's response doesn't confirm the text went out. A code works for about a minute. Calling it again sends a new code, and the previous one stops working.
- `validatePhoneVerificationCode` ignores spaces and dashes in the code, and rejects with `'codeIncorrect'` before sending when what's left isn't all digits. It sends the code to Coinme as `phoneValidationCode`.
- Both take `environment`, `headers`, `timeoutMs` (default 60 000), `apiBaseUrl` and `signal` (an `AbortSignal`; an aborted call rejects with the abort error, the signal's reason where the runtime records one, otherwise fetch's `AbortError`, rather than a `CoinmeOnboardingError`).
- A resolved `validatePhoneVerificationCode` means Coinme accepted the code. Coinme is the authority on whether the phone is verified: record the result on your backend, and don't rely on client-side state alone.

### Input and validation

| Field | Format | Notes |
| --- | --- | --- |
| `email` | email address | Required. |
| `fullName.firstName`, `fullName.lastName` | text | Required. Printable ASCII only. |
| `fullName.middleName` | text | Optional. Printable ASCII only. |
| `fullName.otherNames` | array of text | Optional. Printable ASCII only. Blank entries are dropped, and the field is left out when none remain. Validation errors and the React Native components use the paths `fullName.otherNames.0`, `fullName.otherNames.1`, …: whole numbers from 0, with no gaps. |
| `address.line1`, `address.city` | text | Required. Printable ASCII only. |
| `address.line2` | text | Optional. Printable ASCII only. |
| `address.state` | two-letter US state code or `DC` | Required. Any of the 50 states or DC. Case-insensitive; sent upper-case. |
| `address.postalCode` | `12345` or `12345-6789` | Required. |
| `address.country` | three-letter country code | Optional; defaults to `USA`. |
| `phoneNumber` | US number | Required. US numbers only. Formatting is ignored; sent as `{ countryCode: '1', number: '<10 digits>' }`. |
| `dateOfBirth` | `YYYY-MM-DD` | Required. The customer must be 18 or older. |

Values are trimmed before sending.

`validateCustomerOnboardingInput(input)` checks these rules, for example as the customer types. It returns `{ valid, fieldErrors }`, where `fieldErrors` maps a field path (for example `'address.postalCode'`) to one code:

| Code | Meaning |
| --- | --- |
| `required` | The field is empty. |
| `invalidEmail` | Not a well-formed email address: letters, digits and `._%+-` before the `@` (not starting or ending with a dot), a domain whose labels don't start or end with a hyphen, a letter-only top-level domain, and no consecutive dots. |
| `invalidDate` | Not a real date in `YYYY-MM-DD` form. `DateOfBirthField` converts the `MM/DD/YYYY` the customer types before validating. |
| `underMinimumAge` | The customer is younger than 18. |
| `overMaximumAge` | The date of birth is more than 120 years ago. |
| `invalidState` | Not a US state code. |
| `invalidPostalCode` | Not a 5-digit ZIP or ZIP+4. |
| `invalidPhone` | Not a 10-digit US number. |
| `invalidCountry` | Not a three-letter country code. |
| `nonAscii` | Contains characters outside printable ASCII (for example accents). |

Only the first failure per field is reported. They're codes rather than messages, so the copy is yours. Client-side validation is for the customer's benefit; Coinme's service makes the final decision.

## Error handling

Every failure is a `CoinmeOnboardingError` with a `kind` you can branch on and a `retryable` flag.

```typescript
try {
  const { customerId } = await submitCustomerOnboarding(vault, input, {
    headers,
  });
} catch (error) {
  if (!(error instanceof CoinmeOnboardingError)) throw error;
  switch (error.kind) {
    case 'validation':
      // Nothing was sent. Plain fields: error.fieldErrors; SSN: error.secureFieldErrors.
      showFieldErrors(error.fieldErrors);
      break;
    case 'unauthorized':
      // Get a fresh token and try again.
      break;
    default:
      if (error.retryable) showTryAgain();
      else showCannotOnboard(error.kind); // duplicate, sanctions, jurisdiction, …
  }
}
```

| `kind` | Meaning | `retryable` |
| --- | --- | --- |
| `validation` | Input failed client-side checks; see `fieldErrors` and `secureFieldErrors` (SSN). Nothing was sent. | yes, after fixing |
| `duplicate` | The customer is already onboarded with your program. | no |
| `ageRequirement` | The customer doesn't meet the minimum age. | no |
| `jurisdiction` | The customer's state isn't supported. | no |
| `prohibited` | An identifier is on a prohibited list. | no |
| `sanctions` | The customer matched a sanctions list. | no |
| `identityVerificationFailed` | The identity couldn't be verified with the details given. | per the service (usually yes) |
| `invalidRequest` | The request was rejected as invalid: either by the service (CAAS codes `206-400-100-999`, and `270-400-203-668` for a name with characters other than letters, spaces, `'`, `-` and `.`) or as any HTTP 4xx other than 401, 403, 408 and 429 that carries no CAAS error code, such as a rejection by the secure-field proxy for a misconfigured vault. | per the service; no for a 4xx without a code |
| `server` | The service failed (5xx), or asked for the request to be tried later: timed out waiting for it (408) or rate-limited it (429). | yes |
| `network` | No response arrived: the device is offline, the request was blocked, or it timed out. After a timeout the customer may already be onboarded; see below. | yes |
| `unauthorized` | The `Authorization` header was missing, expired or rejected (401/403). | no |
| `notReady` | `submit()` was called before the secure SSN field's vault was ready. Wait for `vaultStatus` to be `'ready'`, or enable your submit button only when `isValid` is `true`. | yes |
| `configuration` | No onboarding configuration for the environment (contact Coinme), or the `Authorization` header carries a partner access token, so nothing was sent; see [Authentication and headers](#authentication-and-headers). | no |
| `unknown` | Anything else, including an error thrown by your `getHeaders`, an error code the SDK doesn't know, and a phone verification response that reports success but has no `data`. | no |
| `codeIncorrect` | Phone verification: the code doesn't match, or it expired (Coinme currently reports an expired code this way). | yes |
| `codeExpired` | Phone verification: the code expired. | yes, with a new code |
| `tooManyAttempts` | Phone verification: too many failed checks, or the account's phone number has been changed too often. See `retryAfterSeconds` and `attemptsExhausted`. | per the service (usually yes, after `retryAfterSeconds`); never once `attemptsExhausted` |
| `smsNotSent` | Phone verification: Coinme's response didn't confirm the text was sent. | yes |
| `phoneNotSupported` | Phone verification: the number can't receive verification texts (not a mobile number, a carrier that isn't allowed, or recently used by another account). | no |
| `phoneAlreadyInUse` | Phone verification: the number belongs to another Coinme account. | no |
| `phoneNotVerified` | Not currently returned. It stays in the type so code that handles it still compiles. You don't need to handle it separately: treat it like any other failure. | no |

**A timeout doesn't mean nothing was sent.** When no response arrives within `timeoutMs` (60 seconds by default), the submit fails as `network`, but the request may still have reached Coinme and onboarded the customer. If the customer then retries with the same details and gets `duplicate`, the first attempt probably succeeded, even though you never received their `customerId`.

When the service's response includes a retry flag, `retryable` follows it. Otherwise it comes from the error-code table below. An `invalidRequest` without a CAAS error code is not retryable, and the drop-in form then shows its terminal message ("We're unable to complete your onboarding.") instead of "try again", unless you override it with `errorMessages`.

**CAAS error codes.** When Coinme returns an error code, it's on `error.errorCode`, and `ONBOARDING_ERROR_CODES` maps each known code to its `kind`:

| Code | `kind` |
| --- | --- |
| `206-400-100-001`, `270-400-203-603` | `duplicate` |
| `206-400-100-011` | `ageRequirement` |
| `206-400-100-012` | `jurisdiction` |
| `206-400-100-014` | `prohibited` |
| `206-400-100-020` | `identityVerificationFailed` |
| `206-400-100-031` to `206-400-100-036` | `sanctions` |
| `206-400-100-999`, `270-400-203-668` | `invalidRequest` |
| `206-500-100-999`, `270-500-203-604`, `270-500-203-999` | `server` |

`PHONE_VERIFICATION_ERROR_CODES` does the same for the phone verification calls:

| Code | Returned when | `kind` |
| --- | --- | --- |
| `203-400-115-001` | Sending or checking: too many failed checks | `tooManyAttempts` |
| `203-400-115-003` | Sending: the account's phone number has been changed too often | `tooManyAttempts` |
| `203-400-115-004` | Sending: another account used the number recently | `phoneNotSupported` |
| `203-400-115-006` | Sending: not a mobile number, or a phone type that isn't allowed | `phoneNotSupported` |
| `203-400-115-007` | Sending: the carrier isn't allowed | `phoneNotSupported` |
| `203-400-115-008` | Sending: the number belongs to another account | `phoneAlreadyInUse` |
| `203-400-115-009` | Checking: the code is wrong or expired | `codeIncorrect` |
| `203-400-115-010` | Checking: the code expired | `codeExpired` |

Earlier versions of this page listed `201-400-115-*`, `202-400-115-*` and `204-400-115-*` codes for phone verification. Coinme doesn't send those; the codes above are the ones it returns. If your error handling branches on the old codes, branch on `kind` instead, or on the codes above.

Coinme's phone verification endpoints can report a failure with HTTP 200. The SDK treats a 200 as success only when it carries no error (an `errorResponse`, or a top-level `errorData` or `errors` list) and has `data`; sending a code also needs Coinme to confirm the text went out, otherwise it fails as `smsNotSent`.

Other properties: `status` (the HTTP status, when the request completed), `cause` (the original error) and, for phone verification (mostly with `tooManyAttempts`), `retryAfterSeconds` (seconds until the customer can try again) and `attemptsExhausted` (`true` once every attempt is used, which also makes the error not retryable), when Coinme sends them.

- `error.message` never contains customer details, so it's safe to log.
- Don't show `error.cause` to customers. Branch on `kind` and show your own copy.

## Accessibility

The drop-in form and `OnboardingFormField` wire the basics for VoiceOver and TalkBack:

- Each field is named by its row's label: a text label becomes the field's `accessibilityLabel`, and the visible label is hidden from screen readers so it isn't read twice. With an element label, pass `fieldProps.accessibilityLabel` to name the field.
- While a field's inline error shows, it leads the field's `accessibilityHint` (followed by any hint you pass), and it's announced when it appears or changes.
- The state picker announces the selected state as its value ("State, Washington").
- The submit-failure message has `accessibilityRole="alert"` and is announced when it appears.
- The submit button reports `disabled` and, while submitting, `busy`.
- `PhoneVerificationStep` names each code box by its position (`labels.digit`, default `'Digit 1 of 6'`) under a visible `labels.code` label, announces each new screen's text, its error alert and the start of a countdown once the customer has pressed a button, moves focus to the first box when it appears and again after a wrong or expired code, and its buttons report `disabled` and `busy` the same way.

The SSN field is named `'Social Security Number'` by default, or by the row's label when it's text. Pass your own name with `accessibilityLabel`:

```tsx
fieldProps={{ ssn: { accessibilityLabel: 'Número de Seguro Social' } }}
```

Your own `accessibility*` props on any field override the SDK's defaults. With the bare field components, labels and error wiring are yours.

## Verify your integration (sandbox)

1. Render the form with `environment="sandbox"` and a sandbox onboarding token.
2. Fill it in with a sandbox test identity from Coinme. Check that the submit button enables only once every field, including the SSN, is valid.
3. Submit, and check that `onSuccess` receives a `customerId`.
4. Mount the form again, submit the same identity, and check that `onError` receives a `duplicate` error.
5. Check on both iOS and Android, and with VoiceOver and TalkBack if you support them.
6. In a release build, check that no network logger is bundled and that your monitoring doesn't record request bodies for the onboarding vault host (see [Security](#security)).
7. With a fresh sandbox identity, onboard, then render `PhoneVerificationStep` with the `phoneNumber` from `onSuccess` and a token minted for the new `customerId`. Send a code, check that a wrong code shows `codeIncorrect` and clears the boxes, then enter the right one and check that `onVerified` is called.

## Security

- **Your code never receives the raw SSN.** It's typed into the vault's secure field and goes from there to the vault. Don't try to read it or ask for it in a plain input.
- **Until the vault receives it, the SSN is in your app's JavaScript.** The secure field library (`@vgs/collect-react-native`) is JavaScript: the SSN is held in JavaScript memory and sent as plain text, inside an HTTPS request made with `fetch`, to the onboarding vault (`secure.apis.coinme.org` in sandbox, `secure.apis.coinme.com` in live), which replaces it with a token before the request reaches Coinme. Anything in your app that sees `fetch` traffic can see it, so:
  - exclude the vault host from request-body capture in monitoring and APM SDKs (Sentry, Datadog, New Relic and similar), and from any `fetch` wrapper or interceptor of your own;
  - don't ship network loggers or inspectors (Reactotron, Flipper, network-logging libraries) in release builds. In development, React Native DevTools' network panel shows the request body too.
- **Keep Coinme credentials and your partner access token out of the app.** The device only needs the Transient Auth Tokens, just in time for each request. Don't store them.
- **Don't log customer details.** `CoinmeOnboardingError` messages are safe to log. Form values (from `values` or your own inputs) are personal data.
- **No verified phone, no completed onboarding.** Coinme doesn't consider KYC complete until the customer confirms the code texted to the number they onboarded with. Never treat a customer without a verified phone as onboarded or KYC-complete, and send an unverified customer who signs back in to verification first.
- **One phone number throughout.** Verify the number the customer onboarded with: pass `phoneNumber` from the onboarding result, or the copy you stored, and never accept a different number at verification.
- **Coinme is the authority.** Client-side checks and a verified screen are UX only. Confirm the customer's status on your backend before granting access.

## Commonly asked questions

### What is the onboarding token, and how do I get one?

The onboarding token is a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) with the `onboarding` scope: a short-lived credential that authorizes one onboarding submit. Your backend mints it in two calls, both described on that page: it exchanges your API client ID and client secret for a partner access token, then calls `POST /services/browserAuth` with `scope=onboarding`. The customer does not exist at Coinme yet, so pass your identifier for the customer's sign-up session as `customerId`. Your Coinme credentials and the partner access token never belong in the app.

You own getting the token to the device. The usual shape is to fetch it inside `getHeaders`: write a `getHeaders` that calls your backend, which mints the token and returns it, and return `{ Authorization: 'Bearer <token>' }`. The SDK calls `getHeaders` just before each submit, so every submit gets a fresh token.

The SDK does not fetch tokens, refresh them or store them; it sends whatever `getHeaders` returns. Don't keep the token in `AsyncStorage`, secure storage or anywhere else on the device.

Phone verification needs a second token, minted the same way with `scope=onboarding` but for the Coinme `customerId` that onboarding returned rather than your sign-up session. The sign-up session token does not work for the verification calls. See [Authentication and headers](#authentication-and-headers).

### How do I associate an onboarding with my own backend session?

The submit goes from the customer's device to Coinme, so your backend does not see it; the new Coinme `customerId` reaches you through your app, from `onSuccess`. The customer has no account with you yet, because this one call onboards them and runs KYC, so there is no signed-in session at that moment. Your backend associates the two by keeping its own sign-up session across the two requests it does see: the one that mints the onboarding token, and the one that receives the `customerId`.

**What Coinme provides and what you build**

| Piece | Provided by |
| --- | --- |
| The onboarding form, the secure SSN field and the submit to Coinme | Coinme (this SDK) |
| The new Coinme `customerId`, passed to `onSuccess` | Coinme |
| The phone verification step, which texts the code and checks it | Coinme (this SDK) |
| Minting the onboarding token (`POST /services/browserAuth` with `scope=onboarding`) | Coinme API, called by your backend |
| Minting the phone verification token (the same call, for the new `customerId`) | Coinme API, called by your backend |
| CaaS API calls, such as fetching a customer's wallets | Coinme API, called by your backend |
| Your sign-up session and its ID | You |
| Carrying that session between your app and your backend, for example with a session token your app sends on each request | You |
| A backend endpoint that mints the onboarding token and returns it to your app | You |
| The `getHeaders` function that calls that endpoint | You |
| A backend endpoint that receives the `customerId` and `phoneNumber` from `onSuccess` and links them to your user | You |
| A backend endpoint that mints the phone verification token for that `customerId`, and a record of whether the phone is verified | You |

Coinme does not create or manage your sessions or the tokens your app carries them with. There is no Coinme call that returns which sign-up session a `customerId` was onboarded from.

**Two identifiers are involved, and they are different values.** When your backend mints the onboarding token, it passes its own sign-up session ID in the `customerId` parameter, because the customer does not exist at Coinme yet. When onboarding succeeds, `onSuccess` returns a new value: the Coinme `customerId`. Your backend stores the Coinme `customerId` against its sign-up session ID.

**How the pieces fit together**

1. The customer starts sign-up. Your backend creates a sign-up session and gives the app a way to carry it, typically a session token the app sends with each request.
2. Just before the submit, the SDK calls your `getHeaders`. It asks your backend for a token; your backend reads the sign-up session, mints the onboarding token with the sign-up session ID as `customerId`, and returns the token.
3. The SDK submits the onboarding to Coinme from the app, with the token.
4. Coinme returns the new `customerId` to `onSuccess`.
5. Your `onSuccess` sends the `customerId` and `phoneNumber` to your backend on the same sign-up session. Your backend checks the `customerId` and links both to your user.
6. Your app moves on to [phone verification](#phone-verification). Its `getHeaders` asks your backend for a token, which your backend mints for the linked `customerId`.
7. Once the code checks out, your backend records that the customer's phone is verified. Only then is the customer onboarded.

**Checks we recommend before linking a `customerId`**

Because `onSuccess` runs in the app, the `customerId` your backend receives is a value reported by the client. A CaaS API call your backend makes with it confirms that it is valid and belongs to your partner account, and rejects one that is not; it does not confirm which sign-up session it came from. We recommend your backend:

1. accepts the `customerId` only on the sign-up session that minted the onboarding token, identifying that session from what your backend issued, never from a value in the request body;
2. links one `customerId` per sign-up session, and each `customerId` to one sign-up session;
3. confirms the `customerId` with a CaaS API call made with your partner credentials.

If the request from `onSuccess` to your backend fails, retry it with the same `customerId` rather than resubmitting the form: the customer is already onboarded at Coinme, and a second submit returns `duplicate`.

> **We've provided an example implementation.**
>
> [Example: linking onboarding to your backend session](https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md) builds the onboarding pieces in the "You" rows above (the phone verification token is minted by the same function, for the linked `customerId`) for the JavaScript & React SDK in a browser and a Node.js (Express) backend. Its backend endpoints, recommended checks and database table are what a React Native app's backend needs too; its frontend code and session cookie are the web versions, so carry the sign-up session the way your app already talks to your backend. It is one possible implementation, not a Coinme requirement.

### Why does onboarding happen from the app at all?

So that the Social Security Number never reaches your code or your servers. The SSN is typed into the vault's secure field and sent from the device to the vault, which replaces it with a token before the request reaches Coinme, and that is only possible if the request starts on the device. Until then it is in your app's JavaScript runtime, so keep monitoring and network loggers away from it as [Security](#security) describes. The trade-off is that your backend does not observe the onboarding call, so the `customerId` reaches it through your app.

### Can I onboard from my backend instead?

The onboarding endpoint itself is described in Coinme's [customer onboarding guide](https://docs.coinme.com/docs/customer-onboarding-overview), and nothing stops a server-to-server integration. It means collecting and handling the SSN yourself.

## Troubleshooting

**`401` on install.** The registry token is missing or expired. Re-export `COINME_REGISTRY_TOKEN` and reinstall. See [Install](#install).

**`Unable to resolve "@vgs/collect-react-native"`.** The peer dependency isn't installed. Install it alongside this package; see [Install](#install).

**`onError` logs don't show up in the Metro terminal (bare React Native).** In bare React Native 0.77 and later, `console` output appears in React Native DevTools (press `j` in the Metro terminal to open it), not in the Metro terminal. Expo CLI still shows it in the terminal.

**Metro can't resolve the package after install.** Restart Metro with a clean cache: `npx expo start --clear` (Expo) or `npx react-native start --reset-cache` (bare).

**`Onboarding components and hooks must be rendered inside <CoinmeOnboardingProvider>`.** A field component, `OnboardingFormField` or `useCustomerOnboarding` is rendered outside the provider. Wrap them in `<CoinmeOnboardingProvider environment="…">`. The drop-in form includes its own provider.

**`vaultStatus` is `'error'` with `kind: 'configuration'`.** The package has no onboarding configuration for the selected environment. Published packages always include it, so contact Coinme.

**Submits fail with `notReady`.** The submit ran before the vault was ready, typically from a submit button that isn't disabled while `isValid` is `false`. Gate the button on `isValid` (it's `false` until the vault is ready), or wait for `vaultStatus` to be `'ready'`.

**Submits fail with `validation` but every plain field is valid.** No `CoinmeSsnField` is rendered, or the SSN is incomplete. Check `ssnState`.

**The submit button never enables.** It needs every required field valid **and** a valid SSN. With a custom layout, make sure every required field is placed. Read `fieldErrors` and `ssnState` from `useCustomerOnboarding` to see what's missing.

**The SSN field is a different size from the other inputs.** Give it the same `style` as your plain fields, not only `containerStyle` or `textStyle`; see [Styling](#styling).

**The keyboard covers the lower fields.** The form doesn't scroll by itself. Render it inside a `ScrollView`. On iOS a `ScrollView` alone doesn't make room for the keyboard: add `automaticallyAdjustKeyboardInsets` to it, or wrap it in a `KeyboardAvoidingView`, so customers can scroll to the bottom fields while the keyboard is open.

**On iOS the keyboard won't close after the SSN.** The SSN, ZIP, phone and date fields open numeric keypads, which have no return key on iOS. Add `keyboardDismissMode="on-drag"` to your `ScrollView` so a scroll closes the keyboard, or add your own Done button.

**Submits or phone verification calls fail with `configuration` before anything is sent.** The SDK refuses a request whose `Authorization` header carries a partner access token and throws a `configuration` `CoinmeOnboardingError` before anything is sent. If you see it, your backend is returning the partner access token to the app. Change that route to mint a Transient Auth Token from `POST /services/browserAuth` (with `scope=onboarding`) and return only its `access_token`. The partner access token is a long-lived credential that must stay on your backend.

**Submits fail with `unauthorized`.** `getHeaders` returned no `Authorization` header, or the token was expired or rejected. Fetch a fresh token for each submit.

**Phone verification fails with `unauthorized`.** The token was minted for the sign-up session instead of the new `customerId`, or it expired. Mint a fresh one for the `customerId` from `onSuccess` inside the step's `getHeaders`.

**A correct code is rejected as `codeIncorrect`.** The code had probably expired: a code works for about a minute, and Coinme currently reports an expired code as `codeIncorrect`. Send a new one.

**Names with digits or symbols are rejected as `invalidRequest`.** The onboarding service accepts only letters, spaces, `'`, `-` and `.` in names, and returns error code `270-400-203-668` for anything else. Ask the customer to type their name without other characters.

**Submits fail with `invalidRequest` and no `errorCode`.** The request was rejected before it reached the onboarding service: an HTTP 4xx without a Coinme error code. This is most often a proxy or configuration problem rather than the customer's details. Check `error.status` and contact Coinme.

**Submits fail with `unknown` right away.** Check that `getHeaders` resolves. An error thrown there is reported as the submit error, with the original on `error.cause`.

**Accented names are rejected.** The onboarding service accepts printable ASCII only, so the SDK reports `nonAscii` for those fields. Ask the customer to type the name without accents.
