---
name: coinme-onboarding-react-native
description: "Add Coinme customer onboarding with non-documentary KYC to an iOS or Android app built with React Native or Expo using @coinme-security/onboarding-sdk-react-native: install it and its @vgs/collect-react-native peer from the private registry, render the drop-in CustomerOnboardingForm or compose the headless pieces, supply the onboarding token through getHeaders, link the returned customerId to the backend's sign-up session, verify the customer's phone with PhoneVerificationStep, handle CoinmeOnboardingError kinds, and verify in sandbox on both platforms. Use when asked to onboard customers, collect KYC or SSN securely, verify a new customer's phone, or integrate the Coinme Onboarding SDK in a React Native or Expo app."
metadata:
  surface: "caas"
  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"
---

# Customer onboarding in a React Native app with the Onboarding SDK

## When to use this skill

The human wants to onboard a new customer to Coinme from their React Native app, bare or Expo. The SDK collects the details, takes the Social Security Number through the vault's secure field so the app's code never receives it, submits to Coinme and returns a `customerId`, then verifies the customer's phone with a texted code. For a React or JavaScript web app use the coinme-onboarding-react skill.

## Which integration this is

This skill is for the **Coinme-as-a-Service (CaaS) integration**: the partner keeps its own users and its own screens, and Coinme performs regulated services for them (onboarding and KYC, card vaulting, risk signals, transactions). The users are the partner's customers, not Coinme users. There is no Coinme Widget here, so no `rampId`, `partnerKey`, widget URL or embed allowlist. If the human wants to embed the Coinme Widget instead, this is the wrong skill: read [Two ways to build on Coinme](https://platformdocs.coinme.com/agents/surfaces.md) and pick a Widget skill.

## What you will produce

A screen that renders the onboarding form inside a `ScrollView`, obtains a short-lived onboarding token from the human's backend through `getHeaders`, sends the returned `customerId` and `phoneNumber` to the human's backend and links them to the sign-up session, verifies that phone with a second token minted for the `customerId`, handles success and the typed error kinds, and passes the sandbox verification on iOS and Android.

## Before you start: ask the human for these

The documentation does not contain them and you cannot derive them. Stop and ask, then continue. Never write a real value into a tracked file; keep each where the row says.

| Value | What it is | Where it goes |
| --- | --- | --- |
| `COINME_REGISTRY_TOKEN` | Read-only token for the private npm registry that serves @coinme-security/onboarding-sdk-react-native. | An environment variable that a gitignored `.npmrc` or `.yarnrc.yml` entry reads; CI reads it from a secret. |
| `API client ID and client secret` | The credentials the human's backend exchanges at `POST /services/authorize` for a partner access token, which mints the Transient Auth Token. The client ID is not the partner ID, and not the Risk SDK's `clientId`. | The backend's secret store or environment variables; never in client code or a committed file. |
| `production base URL` | The base URL for `/services/authorize` and `/services/browserAuth` in production; sandbox is `https://caas-staging.coinme.com`. Coinme provides it at onboarding. | Backend configuration, one value per environment. |

## Rules for this skill

- Follow the steps in order and keep the code as written; change only identifiers the human gives you and the places marked as yours.
- Step 4 replaces the `onSuccess` shown in step 1. Use step 4's `onSuccess`.
- Do not invent configuration fields, event names or API methods. What exists is what this skill shows plus what the installed package declares in its type definitions; check those before adding anything.
- Samples show the environment (such as `'sandbox'`, `'test'` or a staging base URL) as a literal so each stays self-contained. In the project, read it from the runtime configuration the human's build uses (for Vite, `VITE_*` variables in a gitignored `.env.local` with a committed `.env.example`), with a value per environment.
- This integration has no `rampId`, `partnerKey`, widget URL or embed allowlist. Do not ask for them or add them; they belong to the Widget skills.
- The Transient Auth Token is minted only in the human's backend, never in the browser or the app: write that backend route as the backend step below shows, reading the API client ID, client secret and base URL from the server's configuration. Never send the partner access token, the client ID or the client secret to the client.
- Never pass the partner access token to the SDK, not in sandbox, not in a prototype and not as a fallback when minting fails; the `Authorization` header carries only the Transient Auth Token from `POST /services/browserAuth`.
- When a step needs a value you do not have, ask; do not substitute a placeholder that could ship.
- Read the linked pages when a step is unclear; they are the source this skill was generated from.

## Read first

- The release on this site is `1.2.1`. Install it as the guide shows and do not pin another version.
- It has no native module of its own: no config plugin, prebuild, `pod install` or Gradle change. Do not add any for it.
- Until the vault receives it, the SSN is in the app's JavaScript runtime. If the app has a monitoring or APM SDK, a `fetch` interceptor or a network logger, exclude the onboarding vault host from request-body capture and keep network loggers out of release builds, as the Security section below says.

## 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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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.

## Procedure

### 1. Render the drop-in form

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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#style-the-whole-form) for a complete example.

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

`YOUR_BACKEND`, `getYourAppSessionToken`, `postToYourBackend`, `getTokenFromYourBackend` and the `/your-api/...` paths stand for the human's own server and code, not the SDK's: Coinme provides none of them, and the paths are the human's choice. The `onSuccess` here already sends the `customerId` and `phoneNumber` to the human's backend; step 4 says what that route must do, and step 5 covers the verification step it moves on to.

### 2. Mint the onboarding token in your backend

Add the backend route that the form's `getHeaders` calls (`/your-api/onboarding/token` in the guide's examples; the path is the human's choice), which returns `mintTransientAuthToken(signUpSessionId, 'onboarding')`: a Transient Auth Token with the `onboarding` scope, minted for the identifier of the customer's sign-up session, since the customer does not exist at Coinme yet. Step 4 shows where `signUpSessionId` comes from.

#### Get a partner access token

Call this from your backend only. It authenticates with HTTP Basic: your API client ID and client secret, joined by a colon and base64-encoded.

```bash
curl -X POST "https://caas-staging.coinme.com/services/authorize" \
  -H "Authorization: Basic $(printf '%s:%s' "$CLIENT_ID" "$CLIENT_SECRET" | base64)"
```

```json
{
  "access_token": "eyJ…",
  "token_type": "Bearer",
  "expires_in": "1800"
}
```

The lifetime differs by environment: 30 minutes (`1800`) in sandbox and 60 minutes (`3600`) in production. Read `expires_in` (seconds, sent as a string) rather than hard-coding it, keep the token in your backend and reuse it until shortly before it expires.

> **Never send the partner access token to a browser or an app.**
>
> It authorizes every CaaS endpoint on your behalf. Only the Transient Auth Token from the next step goes to the client.

#### Mint the Transient Auth Token

Also from your backend only, authenticated with the partner access token from step 1.

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

| Parameter | In | Required | Notes |
| --- | --- | --- | --- |
| `Authorization` | header | yes | `Bearer <partner access token>`. |
| `customerId` | query | yes | For card capture, the Coinme customer the card will belong to. For onboarding, your identifier for the customer's sign-up session. For phone verification, the Coinme `customerId` onboarding returned, read from your backend's own record, never from the client. For attestations, the Coinme `customerId` of the onboarded customer. The token is bound to this value. |
| `scope` | query | no | `payment-methods` (the default) for the Vault SDK's payment-method submit, `onboarding` for the Onboarding SDK's onboarding submit and phone verification calls (sandbox only for now: Coinme's production environment does not issue tokens with this scope yet), or `attestations` for the Compliance SDK's attestation store, which is not available in the beta at this time. |

For onboarding, pass `scope=onboarding` and the sign-up session's identifier:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${SIGNUP_SESSION_ID}&scope=onboarding" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

For phone verification, pass `scope=onboarding` and the `customerId` onboarding returned. Mint a fresh one for each verification call (sending the code, checking it), since a customer waiting for the text can easily pass the 10 minutes:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}&scope=onboarding" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

For the Compliance SDK's attestations, pass `scope=attestations` and the onboarded customer's `customerId`. Attestations are not available in the Compliance SDK beta at this time, and Coinme does not issue tokens with this scope:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}&scope=attestations" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

```json
{
  "access_token": "eyJ…",
  "token_type": "Bearer",
  "expires_in": "600"
}
```

Mint a fresh token each time the customer reaches the add-card, onboarding or consent screen. Tokens last 10 minutes and are cheap to mint; never cache one or reuse it across sessions or customers.

> **Check the body, not just the status.**
>
> A mint that reaches the service but fails validation returns HTTP `200` with an error envelope in the body (for example `{"status":400}`) and no `access_token`. Treat any response without an `access_token` as a failure.

#### In your backend

The two calls as a Node.js module. The route that hands the token to your page or app calls `mintTransientAuthToken`: for card capture, for a signed-in customer only; for onboarding, for the customer's sign-up session, because the customer is not signed in yet; for phone verification, for the `customerId` your backend saved against that customer's record when onboarding succeeded, read from your own record and never from the request; for attestations, for the signed-in customer only.

```typescript
const BASE_URL = process.env.COINME_BASE_URL!; // https://caas-staging.coinme.com in sandbox

let partnerToken: { value: string; expiresAt: number } | undefined;

const getPartnerAccessToken = async (): Promise<string> => {
  if (partnerToken && partnerToken.expiresAt > Date.now() + 60_000) {
    return partnerToken.value;
  }
  const credentials = Buffer.from(
    `${process.env.COINME_CLIENT_ID}:${process.env.COINME_CLIENT_SECRET}`
  ).toString('base64');
  const response = await fetch(`${BASE_URL}/services/authorize`, {
    method: 'POST',
    headers: { Authorization: `Basic ${credentials}` },
  });
  const body = await response.json();
  if (!response.ok || !body.access_token) {
    throw new Error(`Coinme authorize failed (${response.status})`);
  }
  partnerToken = {
    value: body.access_token,
    expiresAt: Date.now() + Number(body.expires_in) * 1000,
  };
  return partnerToken.value;
};

export const mintTransientAuthToken = async (
  customerId: string, // or, for onboarding, the sign-up session's identifier
  scope: 'payment-methods' | 'onboarding' | 'attestations' = 'payment-methods'
): Promise<{ token: string; expiresIn: number }> => {
  const url = new URL(`${BASE_URL}/services/browserAuth`);
  url.searchParams.set('customerId', customerId);
  url.searchParams.set('scope', scope);
  const response = await fetch(url, {
    method: 'POST',
    headers: { Authorization: `Bearer ${await getPartnerAccessToken()}` },
  });
  const body = await response.json();
  // A failed mint can arrive as HTTP 200 with an error envelope and no token.
  if (!response.ok || !body.access_token) {
    throw new Error(`Coinme browserAuth failed (${body.status ?? response.status})`);
  }
  return { token: body.access_token, expiresIn: Number(body.expires_in) };
};
```

The token lasts 10 minutes. When a submit fails because it expired, fetch a fresh one from the backend and retry once; [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) has the error tables.

### 3. Supply the onboarding token

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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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.

### 4. Link the `customerId` to the backend's sign-up session

The submit goes from the app to Coinme, so the human's backend does not see it. The new `customerId` reaches the backend only through `onSuccess`. Do this step whenever the human's backend needs to know which of its users was onboarded.

#### Who provides what

**Coinme provides**, and you use as documented:

- The form, the secure SSN field and the submit to Coinme.
- The new Coinme `customerId`, passed to `onSuccess`.
- `POST /services/authorize` and `POST /services/browserAuth`, which you call through `mintTransientAuthToken` (step 2).
- CaaS API calls, such as fetching a customer's wallets. See [Custody API client](https://platformdocs.coinme.com/docs/caas-custody-api-client.md).

**You build**, in the human's app:

- A sign-up session on the backend, with an ID, and a way for the app to carry it (for example a session token the app sends with each request).
- The token route from step 2, which reads the sign-up session ID from that session.
- A second backend route that receives the Coinme `customerId` and `phoneNumber` from `onSuccess`, checks the `customerId`, and links both to the sign-up session; phone verification needs them next.
- An `onSuccess` that calls that route, as the one in step 1 does (`postToYourBackend('/your-api/onboarding/complete', result)`). Keep it, pointed at the human's route.

Coinme does not create or manage sessions, and has no call that returns which sign-up session a `customerId` was onboarded from. Do not look for one.

If the human's app has no session mechanism or database yet, ask the human which to use.

#### Two identifiers

- **Sign-up session ID:** generated by the human's backend. Passed to Coinme as the `customerId` query parameter when minting the onboarding token, because the customer does not exist at Coinme yet.
- **Coinme `customerId`:** generated by Coinme. Returned by `onSuccess`. Stored by the backend against the sign-up session ID.

These are different values. Do not compare them to each other.

#### Rules from Coinme's documentation

- The SDK does not await `onSuccess`. Handle its promise, including failures, inside `onSuccess`.
- If the call from `onSuccess` to the backend fails, retry that call with the same `customerId`. Never resubmit the onboarding form: the customer is already onboarded, and a second submit returns `duplicate`.
- Never log customer details or the onboarding token.

#### Checks Coinme recommends before linking a `customerId`

The `customerId` the backend receives from `onSuccess` is reported by the app. Before linking it:

1. Accept it only on the sign-up session that minted the onboarding token. Identify that session from the session credential the backend issued (for example the session token), never from a value in the request body or query string.
2. Link one `customerId` per sign-up session, and each `customerId` to one sign-up session.
3. Confirm it with a CaaS API call made from the backend with partner credentials. Reject it if the call fails.

#### Implementation

Read [Example: linking onboarding to your backend session](https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md) before writing the backend routes, `getHeaders` or `onSuccess`. It is a complete hypothetical implementation (Express 5, `express-session`, PostgreSQL) that uses `mintTransientAuthToken` from step 2 and satisfies every rule and check above. It is written for the JavaScript & React SDK in a browser, with a session cookie: its backend routes, checks and database table are what the app's backend needs too, but carry the sign-up session the way the app already talks to its backend, and write `getHeaders` and `onSuccess` with this SDK as in step 1.

- Its endpoint paths, cookie name, schema and helper names are illustrative. Use the human's own conventions.
- If the human's app uses a different stack, implement the same behavior: two backend routes, the session carried between them, the checks in the order shown, one-to-one links enforced in the database.

### 5. Verify the phone

Onboarding is complete only once the customer's phone is verified. After the link in step 4, replace the form with `PhoneVerificationStep` (or build on `usePhoneVerification`), passing the `phoneNumber` from the onboarding result unchanged.

- **The rule:** every phone verification call (the send and the check) is authorized by a Transient Auth Token with `scope=onboarding` minted for the Coinme `customerId` onboarding returned. Never the partner access token, and never the sign-up session token. That token is the only thing that ties the calls to the customer: the send carries only the phone number and the check only the code, so there is no challenge ID, session or cookie to pass between them. Do not look for one.
- **You build** a backend route that the step's `getHeaders` calls (`POST /your-api/phone-verification/token` in the guide's examples; the path is the human's choice, and the SDK provides no such route or function) and that returns `mintTransientAuthToken(customerId, 'onboarding')` from step 2, where `customerId` is the Coinme `customerId` the backend linked to this sign-up session in step 4, read from the human's own record or session, **never from the request**: the route takes no `customerId` from the page or app (not in the body, the query string or a header), so a client can only get a token for its own customer.
- The routes in the Transient Auth Token page's [Example: both tokens, end to end](https://platformdocs.coinme.com/docs/transient-auth-token.md#example-both-tokens-end-to-end) (`/your-api/onboarding/token`, `/your-api/onboarding/complete`, `/your-api/phone-verification/token`, `/your-api/phone-verification/verified`) are example names for routes the human writes and owns; Coinme provides none of them. They are one way to do it, not the only way. Only the Coinme API calls (`POST /services/authorize`, `POST /services/browserAuth`) and the SDK's props are fixed. Name the human's routes however their backend names routes.
- Keep each token in memory: fetch a fresh one inside every `getHeaders` call, and never store it or log it.
- **How customer IDs stay unmixed:** each of the human's users has one saved `customerId`, written when onboarding succeeds, and the verification token route only ever mints for that one. Do not pass a `customerId` to the send or the check (neither takes one), do not use the partner access token for them, and do not reuse the onboarding token.
- Store `phoneNumber` with the `customerId` in step 4, and record on the backend when `onVerified` runs. Never offer a phone input at this step: Coinme texts whatever number it is sent and records it as the customer's verified phone without comparing it with the onboarded number, so passing the onboarded number is up to the integration.
- Treat the customer as onboarded only once the phone is verified. When a customer whose phone is not verified signs in again, show this step before anything else, with the stored `customerId` and `phoneNumber`.

> **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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#recommended-integration-flow)).

### 6. Handle the outcome

The example below calls the core API's `submitCustomerOnboarding` directly, so it catches the error itself. With the drop-in form the SDK makes that call for you and hands the same `CoinmeOnboardingError` to `onError`: put the `switch` there and branch on `error.kind`.

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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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.

## Going further

The form's props are in [Drop-in form](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#drop-in-form), your own layout in [Layout control](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#layout-control), the provider, field components and hook in [Headless React Native](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#headless-react-native), and the style split for the secure field and the state picker in [Styling](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#styling). Read the matching section before you go beyond the drop-in form.

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

## Verify

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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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.
8. Check that the `customerId` from step 3 is linked to the sign-up session in the human's backend, and run the checks in "Checking the example works" on the [example page](https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md) against the human's own routes.

For the sandbox test identity, use the [test identity for Coinme KYC](https://platformdocs.coinme.com/docs/widget-test-identities.md) marked **Yes** under **Verified**. The identities are fake and published for this; one marked **No** shows how a customer who cannot be verified fails.

### Reading the result

**Done when:** `onSuccess` returned a `customerId` your backend saved for the user, and phone verification reported the phone verified. A repeat submit of the same identity returns `duplicate`, not a second customer.

**Stop and ask the human when** onboarding returns `identityVerificationFailed` or another refusal, phone checks hit their limit, or a check fails with a code you cannot explain from the request body.

Judge every Coinme call by its body, not its HTTP status: a refused request usually comes back as HTTP 200 with the error in the body. [Reading results](https://platformdocs.coinme.com/agents/results.md) has the rule, what each common error code asks you to do, and what to send your Coinme integration contact when something fails.

## Troubleshooting

**`401` on install.** The registry token is missing or expired. Re-export `COINME_REGISTRY_TOKEN` and reinstall. See [Install](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#install).

**`Unable to resolve "@vgs/collect-react-native"`.** The peer dependency isn't installed. Install it alongside this package; see [Install](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md#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.

## Reference
- [Onboarding SDK overview](https://platformdocs.coinme.com/docs/coinme-onboarding-sdk.md)
- [Onboarding SDK for React Native](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md)
- [Example: linking onboarding to your backend session](https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md)
- [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)
