---
name: coinme-onboarding-react
description: "Add Coinme customer onboarding with non-documentary KYC to a React or JavaScript web app using @coinme-security/onboarding-sdk-react: install 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. Use when asked to onboard customers, collect KYC or SSN securely, verify a new customer's phone, or integrate the Coinme Onboarding SDK."
metadata:
  surface: "caas"
  package: "@coinme-security/onboarding-sdk-react"
  version: "1.7.1"
  peerDependencies: "react >=18, react-dom >=18"
---

# Customer onboarding in a web app with the Onboarding SDK

## When to use this skill

The human wants to onboard a new customer to Coinme from their web app. The SDK collects the details, takes the Social Security Number through a secure vault field so it never reaches the app's code, submits to Coinme and returns a `customerId`, then verifies the customer's phone with a texted code.

## 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 page that renders the onboarding form, 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.

## 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. | A gitignored `.npmrc` or `.yarnrc.yml` entry; 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 5 replaces the `onSuccess` shown in step 1. Use step 5'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.

## 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}
//npm.coinme.com/coinme-security-wrapper/:always-auth=true
```

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

```bash
export COINME_REGISTRY_TOKEN=<your-token>
npm install @coinme-security/onboarding-sdk-react
# or: yarn add @coinme-security/onboarding-sdk-react
```

`COINME_REGISTRY_TOKEN` is the registry access token. Request it from your Coinme integration contact.

`react` and `react-dom` 18 or later are peer dependencies of the React API (the package root). They're optional: an app without React imports from `@coinme-security/onboarding-sdk-react/core` and doesn't install them. The Coinme Vault SDK (`@coinme-security/vault-sdk-js`), which loads the secure field, is installed with the package.

## 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.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.md#recommended-integration-flow).

## 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.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 browser, so a page can only ever get a token for its own customer.
5. **Start phone verification with that same number.** Your page renders `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. Pass through your own class names for styling; the SDK bundles no CSS.

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

const FIELD_PROPS = {
  email: { className: 'input', placeholder: 'you@example.com' },
  firstName: { className: 'input' },
  middleName: { className: 'input' },
  lastName: { className: 'input' },
  addressLine1: { className: 'input' },
  addressLine2: { className: 'input' },
  city: { className: 'input' },
  state: { className: 'input' },
  postalCode: { className: 'input' },
  phoneNumber: { className: 'input' },
  dateOfBirth: { className: 'input' },
  ssn: {
    placeholder: '123-45-6789',
    css: { fontSize: '16px', fontFamily: 'Inter, sans-serif', color: '#0b1220' },
    containerProps: { className: 'input' },
  },
};

const CLASS_NAMES = {
  form: 'form',
  row: 'field',
  label: 'field-label',
  control: 'field-control',
  fieldError: 'field-error',
  alert: 'alert',
  submit: 'button',
};

export const Onboarding = () => (
  <CustomerOnboardingForm
    environment="sandbox"
    // YOUR backend route (the path is an example): mints a token for the sign-up session.
    // getTokenFromYourBackend is your own fetch helper, not part of the SDK.
    getHeaders={async () => ({
      Authorization: `Bearer ${await getTokenFromYourBackend('/your-api/onboarding/token')}`,
    })}
    // YOUR code: receives { customerId, phoneNumber }. Save both on your backend, then verify
    // that phone.
    onSuccess={startPhoneVerification}
    onError={(error) => reportOnboardingFailure(error.kind)}
    fieldProps={FIELD_PROPS}
    classNames={CLASS_NAMES}
    submitProps={{ children: 'Create my account' }}
  />
);
```

```css
.form {
  display: grid;
  gap: 14px;
}
.field {
  display: grid;
  gap: 6px;
}
.field-label {
  font-size: 13px;
  font-weight: 600;
  color: #475569;
}
.input {
  width: 100%;
  height: 44px;
  box-sizing: border-box;
  padding: 0 12px;
  border: 1px solid #e6edf7;
  border-radius: 8px;
  background: #fff;
  font: inherit;
  color: #0b1220;
}
.input:focus,
.input:focus-within,
.input.vgs-collect-container__focused {
  outline: 0;
  border-color: #1f63f5;
  box-shadow: 0 0 0 3px #eff5ff;
}
.input[aria-invalid='true'] {
  border-color: #5826c3;
}
/* The SSN container is an .input; the secure iframe fills it. */
.input iframe {
  display: block;
  width: 100%;
  height: 100%;
  border: 0;
}
.field-error {
  font-size: 12.5px;
  color: #5826c3;
}
.alert {
  padding: 12px 14px;
  border: 1px solid #e6edf7;
  border-left: 3px solid #5826c3;
  border-radius: 8px;
  background: #fff;
  font-size: 14px;
  color: #475569;
}
.button {
  justify-self: start;
  padding: 10px 18px;
  border: 0;
  border-radius: 999px;
  background: #5826c3;
  color: #fff;
  font: inherit;
  font-weight: 600;
  cursor: pointer;
}
.button:disabled {
  opacity: 0.5;
  cursor: default;
}
```

`getTokenFromYourBackend`, `startPhoneVerification` and `reportOnboardingFailure` stand for the human's own code, not the SDK's: `getTokenFromYourBackend` is a small `fetch` helper that calls the human's backend route (`/your-api/onboarding/token` here; the path is the human's choice) for a fresh onboarding token, and the other two are what the app does after a success or a failure. Write them for the human's app. The `onSuccess` here is a placeholder: step 5 replaces it with one that first sends the `customerId` and `phoneNumber` to the human's backend, and step 6 moves on to phone verification.

### 2. Allow the secure field in your Content-Security-Policy

If the human's site sends a Content-Security-Policy, add these entries before the first test; without them the SSN field does not render. With no CSP, skip this step.

If your site sets a CSP, allow our vault provider's domains and the two Coinme hosts for your environment. The secure SSN field is an iframe served by the vault provider, its script loads from the vault provider's CDN, the onboarding submit goes to the Coinme onboarding host, and the phone verification calls go to the Coinme API host.

| Environment | Coinme onboarding host | Coinme API host |
| --- | --- | --- |
| `live` | `https://secure.apis.coinme.com` | `https://caas.coinme.com` |
| `sandbox` | `https://secure.apis.coinme.org` | `https://caas-staging.coinme.com` |

With `<coinme-host>` and `<coinme-api-host>` replaced by the hosts above:

```
script-src  https://js.verygoodvault.com https://js3.verygoodvault.com
frame-src   https://js.verygoodvault.com https://js3.verygoodvault.com
connect-src https://js.verygoodvault.com https://js3.verygoodvault.com https://vgs-collect-keeper.apps.verygood.systems <coinme-host> <coinme-api-host>
```

`js3.verygoodvault.com` is the vault provider's fallback CDN, and `vgs-collect-keeper` receives its product-interaction analytics.

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

### 4. 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.7.0, which always sends one; see [Device fingerprint](https://platformdocs.coinme.com/docs/onboarding-sdk-react.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 put your Coinme credentials or your partner access token in the browser.** Only the Transient Auth Tokens reach the page, and only for the requests that need them. Never pass your partner access token (from `POST /services/authorize`) to this SDK.
- **Don't store the token.** Fetch it just in time and don't keep it in `localStorage`, `sessionStorage` or cookies.

**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 browser.

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

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.7.0, with Risk SDK for Web 1.2.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 browser with `getDeviceFingerprint()` 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 `getSessionTag()` right before adding a payment method or placing an order, and send the tag it returns as `webSessionId`.

The value is shared through `localStorage` under `coinme.deviceFingerprint`, so it survives page reloads. Like `localStorage`, it belongs to your site's origin, not to the device. If storage is blocked, it is shared for the current page only.

### 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 page. When onboarding succeeds, the page sends the result to your backend, which saves the `customerId` on the signed-in user. When the page 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 page 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 browser. 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, session handling, framework and 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 browser;
> - 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 page |
| **You build** | `POST /your-api/onboarding/token`, `/your-api/onboarding/complete`, `/your-api/phone-verification/token`, `/your-api/phone-verification/verified` (what each does: [You build](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#you-build)) | Your backend. These are examples: Coinme doesn't provide them, so name and shape them however you like. |

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` loads YOUR app's session for the person on the page, 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 browser never says which customer: the ID comes from your
// record, so a page 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 page 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 page** is the [Quickstart](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#quickstart) code: it calls these four routes through `getTokenFromYourBackend` and `postToYourBackend`.

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

The submit goes from the browser 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 3).
- 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 browser to carry it (for example a session cookie).
- The token route from step 3, 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. It replaces the `onSuccess` in step 1.

Coinme does not create or manage sessions or cookies, 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 browser. Before linking it:

1. Accept it only on the sign-up session that minted the onboarding token. Identify that session from what the backend issued (for example the session cookie), never from the request body, query string or a header the page sets.
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, React, same origin) that uses `mintTransientAuthToken` from step 3 and satisfies every rule and check above.

- 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.
- If the frontend and backend are on different origins, follow its "Different origins" section.

### 6. Verify the phone

Onboarding is complete only once the customer's phone is verified. After the link in step 5, 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 3, where `customerId` is the Coinme `customerId` the backend linked to this sign-up session in step 5, 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 5, 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 page never sends one. See [You build](https://platformdocs.coinme.com/docs/onboarding-sdk-react.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.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.

### `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.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)}
/>
```

It moves through three screens, shown as `data-screen` on its `<form>`:

- `'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 moves to the next box, Backspace on an empty box goes back, the arrow keys move between boxes, and non-digits are ignored. Pasting a code, or the phone's SMS autofill (the first box has `autocomplete="one-time-code"`), 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 typed or autofilled into a box already holding its first or last digit, because it can't be told apart from a partial entry 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.

| 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. |
| `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. `sendPrompt`, `codeSent` and `verified` are functions that get the masked number; `digit(position, length)` is each box's accessible name (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` | input props | — | Pass-through props spread onto every code box `<input>`, except `name`, `value`, `defaultValue` and `onChange`. `type`, `inputMode`, `pattern`, `autoComplete` and `aria-label` default to a numeric one-time code and can be replaced. Your `onKeyDown`, `onPaste` and `onFocus` run first; call `preventDefault()` to skip the step's handling. `testId` becomes each box's `data-testid` with `_<index>` appended, for example `code_0`. |
| `submitProps`, `resendProps` | button props | — | Pass-through props for the send/verify button and the resend button. The step owns `type`, the text and (for resend) `onClick`, and keeps them disabled while a call is in flight. |
| `className`, `classNames` | `string`, `PhoneVerificationStepClassNames` | — | Class names added to the step's built-in `coinme-phone-verification*` classes: `form`, `row`, `label`, `control`, `codeGroup` (the boxes' container), `codeBox` (each box), `message`, `hint` (the countdown), `alert`, `submit`, `resend`. The step ships no CSS, so lay the boxes out yourself, for example `.code-boxes { display: flex; gap: 8px }`. |
| `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` and `retryInSeconds`. The `<form>` and its submit handling stay with the SDK. |
| `testId` | `string` | — | Rendered as `data-testid` on the `<form>`. |

### `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 <p>Your phone is verified.</p>;
  if (codeSentAt === null) {
    return (
      <>
        {error && <p role="alert">{error.message}</p>}
        <button disabled={status === 'sending'} onClick={() => sendCode().catch(ignoreSdkError)}>
          Text me a code
        </button>
      </>
    );
  }
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        verifyCode(code).catch(ignoreSdkError);
      }}
    >
      <input
        autoComplete="one-time-code"
        inputMode="numeric"
        value={code}
        onChange={(event) => setCode(event.target.value)}
      />
      {error && <p role="alert">{error.message}</p>}
      <button disabled={status === 'verifying'}>Verify</button>
      <button type="button" onClick={() => sendCode().catch(ignoreSdkError)}>
        Send a new code
      </button>
    </form>
  );
};
```

### When verification fails

The failures specific to this step (see [Error handling](https://platformdocs.coinme.com/docs/onboarding-sdk-react.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.md#recommended-integration-flow)).

### 7. 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;
    case 'configuration':
      // Refused before sending, or the package isn't configured. Fix the integration.
      reportIntegrationError(error.message);
      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 customer 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 finished loading. Wait for `vaultStatus` to be `'ready'`, or enable your submit button only when `isValid` is `true`. | yes |
| `configuration` | Refused before sending: the `Authorization` header carries a partner access token instead of a Transient Auth Token (see [Authentication and headers](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#authentication-and-headers)). Or the package has no onboarding configuration for the selected environment; published packages always include it, so contact Coinme if you see this. | 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

Layout control, the headless provider and hook, styling and the core API are in the guide and shown live, with code, on the [examples page](https://platformdocs.coinme.com/docs/onboarding-sdk-examples.md).

## 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. Reload the page, submit the same identity again, and check that `onError` receives a `duplicate` error.
5. In the browser's network tab, check that the submit goes to the sandbox host listed under [Content-Security-Policy](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#content-security-policy).
6. 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`, then enter the right one and check that `onVerified` is called.
7. 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.md#install).

**`vaultStatus` is `'error'` with `kind: 'network'`.** The secure field script didn't load. Check the network and your [CSP](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#content-security-policy). Ad blockers can also block `js.verygoodvault.com`.

**Submits fail with `notReady`.** The submit ran before the secure SSN field finished loading, 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'`.

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

**The SSN field doesn't appear.** The vault is still loading or failed to load (check `vaultStatus`), or the vault's iframe is blocked by your CSP (`frame-src`) or an ad blocker.

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

**Submits or phone verification fail with `configuration` and nothing is sent.** The `Authorization` header carries a partner access token. Your backend is returning the partner access token to the browser; mint a Transient Auth Token from `POST /services/browserAuth` (with `scope=onboarding`) instead and return only its `access_token`. See [Authentication and headers](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md#authentication-and-headers).

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

**Doubled SSN fields in development.** If you create the SSN field yourself with the core API in React, create it in an effect and delete it in the effect's cleanup, so StrictMode's double run doesn't mount two iframes. The SDK's components already do this.

## Reference
- [Onboarding SDK overview](https://platformdocs.coinme.com/docs/coinme-onboarding-sdk.md)
- [Onboarding SDK for JavaScript & React](https://platformdocs.coinme.com/docs/onboarding-sdk-react.md)
- [Form examples](https://platformdocs.coinme.com/docs/onboarding-sdk-examples.md)
- [Example: linking onboarding to your backend session](https://platformdocs.coinme.com/docs/onboarding-sdk-session-example.md)
