---
name: coinme-vault-react-native
description: "Add card capture to a React Native or Expo app with the Coinme Vault SDK: install the packages, wrap the app in the provider, use the secure field components and hooks, and submit the payment method to Coinme with the transient auth token. Use when asked to collect card details, add a payment method or integrate Coinme's vault in a React Native or Expo app."
metadata:
  surface: "caas"
  package: "@coinme-security/vault-sdk-react-native"
  version: "1.3.0"
  peerDependencies: "@vgs/collect-react-native ^1.1.6, react >=18, react-native >=0.76"
---

# Coinme Vault SDK in React Native

## When to use this skill

The human wants a React Native or Expo app to collect a customer's card details and add them as a payment method at Coinme without the card data touching the app's code or servers. It is not for the Coinme Widget, which handles payment inside its own frame.

## 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 React Native or Expo app with the vault's secure fields in the payment form, validation wired to the submit control, and a submit that sends the payment method to Coinme with a fresh transient auth token in the Authorization header, a Risk SDK session id fetched right before the submit, and the device fingerprint the Coinme SDKs share, which the SDK adds.

## 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 |
| --- | --- | --- |
| `registry token` | Read-only token for the private registry that serves the Coinme SDKs. The install steps below read it from an environment variable they name; set that variable. | An environment variable or a gitignored registry config read at install time; CI reads it from a secret. Never in a committed file. |
| `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. |
| `customerId, paymentProviderId and the Risk SDK webSessionId` | The customer the payment method belongs to, the payment provider, and the Risk SDK session the submit is tied to. | Values from the human's app state at submit time; the Risk SDK must already be integrated to supply the session id, fetched right before the submit. On the web and React Native the Coinme SDKs share the device fingerprint; on iOS and Android the app passes the same value it gives the Risk SDK. |

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

Every payment-method submit carries a Transient Auth Token as `Authorization: Bearer <token>`, minted by the human's backend for the customer (the backend step below). The client fetches one when the add-card screen opens, keeps it in memory, and on a `server` error with status 401 or 403 fetches a fresh one and retries once. Never store it on the device or in the browser, and never put the backend's credentials in the client. Never pass the partner access token to the SDK; the `Authorization` header carries only the Transient Auth Token from `POST /services/browserAuth`.

From 1.2.3 a submit whose `Authorization` header carries a partner access token is refused before sending with a `configuration` `CoinmeVaultError`: fix the backend route that returned it, never retry. From 1.2.2, a `network` error with `timedOut: true` means the outcome is unknown, since the request may still have completed: re-list the customer's payment methods before offering a retry, or the same card can be added twice.

The submit also needs a Risk SDK session id, fetched right before the submit because a session tag lives 30 minutes. From Vault SDK 1.3.0, with Risk SDK for Web 1.2.0 or React Native 1.1.0 or later, the SDK adds the device fingerprint the Coinme SDKs share; otherwise pass `X-Device-Fingerprint` with the same value the Risk SDK gets. If the Risk SDK is not integrated yet, say so and offer the Risk skill first.

## Backend: mint the Transient Auth Token

Before the client can submit a card, the human's backend needs a route that returns `mintTransientAuthToken(customerId)` for the signed-in customer: a Transient Auth Token with the default `payment-methods` scope, bound to the customer the card will belong to. The client calls it when the add-card screen opens.

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

## Procedure

Follow the guide below in order. It is the integration guide for this platform as published, so the section names are the guide's own.

# Coinme Vault SDK for React Native

## Coinme Vault SDK for React Native

`@coinme-security/vault-sdk-react-native` is a typed JavaScript wrapper that lets your React

Native app capture debit card data - card number, expiry, CVC, cardholder name, and billing

address - without any of those values ever touching your JavaScript, your component state, your

logs, or your backend. You collect the data through secure fields provided by the SDK; it

travels directly to Coinme's PCI-compliant vault; your app receives only a confirmation

response.

### How it works

The SDK is a thin wrapper around VGS Collect for React Native ([`@vgs/collect-react-native`](https://www.npmjs.com/package/@vgs/collect-react-native)). VGS

("Very Good Security") is a data-security platform that acts as a secure proxy between your

app and sensitive payment data. The SDK pre-binds Coinme's VGS vault configuration for ease of use, and it exposes convenience methods for high profile operations like adding payment cards to a customer account.

From your app's perspective, the flow is:

1. You wrap your card form in a `CoinmeVaultProvider`.
2. You render secure field components (`CoinmeCardNumberField`, `CoinmeExpiryField`, `CoinmeCvcField`, and others) that look and behave like ordinary React Native text inputs.
3. Internally, each field holds its value inside the VGS collector - your application code

has no access to the raw PAN, CVC, or expiry, even through refs.
4. When the user submits, you call `vault.submit()`. The SDK routes the payload through VGS's secure proxy to Coinme's ingress, and returns a response object (status and parsed body). No raw card value ever passes through your code.

#### Pure JS - no native build step

Both this SDK and its `@vgs/collect-react-native` peer are **pure JavaScript/TypeScript**. They use React Native's built-in `TextInput` under the hood and submit over `fetch` - there is no

native iOS/Android module. This means:

- **Expo Go works out of the box.** No prebuild, no config plugin, no `pod install` or Gradle edits are needed for either package.
- **Neither React Native architecture** (Bridge or new JSI/Fabric) requires any extra configuration.
- The only native toolchain work required to build your app is whatever your own code already

needs - the SDK adds nothing on top.

> If a future VGS release ships native code, an Expo development build would be requiredinstead of Expo Go. The SDK README will note this if it ever applies.

### Prerequisites

Before you install the SDK, confirm you have the following:

| Requirement | Minimum |
| --- | --- |
| Node | 20+ (see `.nvmrc` in the SDK repo for the tested version) |
| React | 18 or 19 |
| React Native | 0.76 or later |
| `CLOUDSMITH_TEAM_TOKEN` | Coinme Cloudsmith entitlement token - see below |

**For Expo projects**, nothing beyond the above is needed. The app runs in Expo Go.

**For bare React Native projects**, you need the standard native toolchain for your target

platform (Xcode and CocoaPods for iOS; JDK 17 and the Android SDK for Android). The SDK adds

nothing to this - it is the same toolchain your app already requires.

#### Obtaining the `CLOUDSMITH_TEAM_TOKEN`

The SDK is published to Coinme's private npm registry. Access is authenticated by a Cloudsmith entitlement token. This token is used **only** at npm install time - it does not

apply to `pod install`, Gradle, or any runtime requests. To obtain one, ask your Coinme integration contact.

### Installation

The SDK is scoped under `@coinme-security`, which is hosted on Coinme's private registry. You configure that scope in your project's package manager config, then install both the SDK and its required peer dependency.

#### Step 1 - Configure the private registry

`.npmrc` (npm or Yarn Classic):

```
@coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/
//npm.coinme.com/coinme-security-wrapper/:_authToken=${CLOUDSMITH_TEAM_TOKEN}
always-auth=true
```

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

```yaml
nodeLinker: node-modules

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

Commit the config file to your repo. The `CLOUDSMITH_TEAM_TOKEN` value itself should be supplied as an environment variable and never committed to source control.

#### Step 2 - Install the packages

```bash
export CLOUDSMITH_TEAM_TOKEN=<your-token>
yarn add @coinme-security/vault-sdk-react-native @vgs/collect-react-native
```

`@coinme-security/vault-sdk-react-native` resolves from Coinme's private registry. Its peer `@vgs/collect-react-native` resolves from the public npm registry. Both must be installed -

the SDK will not work without the peer.

### Running your app

Because there is no native code in either package, there is no extra step to integrate them into your native build.

#### Expo

Run in Expo Go - no prebuild required:

```bash
npx expo start
# then press `i` for iOS Simulator, `a` for Android emulator,
# or scan the QR code with Expo Go on a physical device
```

If your own app already requires native modules that need a development build, continue to use

your development build workflow - the SDK will work the same way there. You only need a

development build (`npx expo prebuild`) for reasons unrelated to this SDK.

#### Bare React Native

Run the standard native build for your platform:

```bash
# iOS
cd ios && pod install && cd ..
npx react-native run-ios

# Android
npx react-native run-android
```

The `pod install` step here installs React Native's own pods - not VGS or this SDK. Neither

package adds anything to your Podfile or Gradle configuration.

#### iOS privacy manifest (optional)

VGS provides an optional privacy manifest for `@vgs/collect-react-native` as a transparency

measure. It declares product-interaction analytics only - no personally identifiable information

and no user tracking are involved. Apple does not currently require this manifest for this SDK.

If your release process merges third-party privacy manifests into your app's

`PrivacyInfo.xcprivacy`, see [VGS privacy details](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/react-native-sdk/privacy-details) for the entries to add.

### Quickstart

Here is the minimum integration - a card number, expiry, and CVC field, gated submit, and

error handling. If all you need is to capture a basic card form and submit it, this is it.

```tsx
import {
  CoinmeCardNumberField,
  CoinmeExpiryField,
  CoinmeCvcField,
  CoinmeVaultError,
  CoinmeVaultProvider,
  useCoinmeVault,
  useVaultFormValidity,
  VAULT_FIELD_NAMES,
} from '@coinme-security/vault-sdk-react-native';
import { useState } from 'react';
import { Button, Text, View } from 'react-native';

const CardForm = () => {
  const vault = useCoinmeVault();
  const { isValid } = useVaultFormValidity();
  const [status, setStatus] = useState('');

  const onSubmit = async () => {
    try {
      const result = await vault.submit();
      // result.status is the HTTP status code; result.data is the parsed response body.
      // Raw card values are never available here.
      setStatus(`OK ${result.status}`);
    } catch (error) {
      if (error instanceof CoinmeVaultError) {
        setStatus(`${error.kind}: ${error.message}`);
      }
    }
  };

  return (
    <View>
      <CoinmeCardNumberField
        fieldName={VAULT_FIELD_NAMES.pan}
        placeholder="Card number"
      />
      <CoinmeExpiryField
        fieldName={VAULT_FIELD_NAMES.expiry}
        placeholder="MM/YY"
      />
      <CoinmeCvcField fieldName={VAULT_FIELD_NAMES.cvc} placeholder="CVC" />
      <Button title="Submit" onPress={onSubmit} disabled={!isValid} />
      <Text>{status}</Text>
    </View>
  );
};

// Wrap your form - or your entire screen — in CoinmeVaultProvider.
// Pass 'sandbox' while developing; switch to 'live' for production.
export const App = () => (
  <CoinmeVaultProvider environment="sandbox">
    <CardForm />
  </CoinmeVaultProvider>
);
```

The three things to notice:

- `CoinmeVaultProvider` is the entry point. It creates one vault on mount and makes it available to everything inside it. Set `environment` to `'sandbox'` for development and `'live'` for production - no other configuration is required to get started.
- `useVaultFormValidity()` aggregates the validity of every registered field. Disabling the submit button until `isValid` is `true` prevents an invalid card from ever reaching the server.
- `vault.submit()` routes the collected values through VGS to Coinme's ingress and returns a result object. On failure it throws a `CoinmeVaultError` - see

[Error handling](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-react-native.md#error-handling) below.

> **It's Easy!**
>
> For the vast majority of deployments, all you need to pass is `environment`; you would pass `live` as the environment for production and `sandbox` for stage (testing). **The SDK does the rest**; you don't need to provide any other configuration.

### Core concepts

#### The provider

`CoinmeVaultProvider` creates and owns one VGS vault instance for its subtree. All field

components and hooks in the tree share that vault through React context. You configure it once

at the top of the tree - you do not pass vault credentials or ingress URLs to individual fields.

```tsx
<CoinmeVaultProvider environment="sandbox">
  {/* your form */}
</CoinmeVaultProvider>
```

`environment` and the optional `config` prop are read **once on mount**. To change either, unmount and remount the provider. The vault is disposed automatically on unmount.

> **You should never pass in a custom config unless you have been explicitly directed to do so by your Coinme integration contact.**Doing so can break your integration and can result in PCI compliance issues that would cripple your card processing efforts.
>
> **When in doubt:** pass only environment; let the SDK do the work for you.

| Prop | Type | Notes |
| --- | --- | --- |
| `environment` | `'sandbox' \| 'live'` | Required. Selects the vault, ingress host, and submit path. |
| `config` | `RuntimeVaultConfig?` | Optional. Overrides the ingress host and/or submit path. Both sandbox and live entries must be provided; `environment` selects which is active. |
| `onError` | `(error: unknown) => void` | Optional observe-only callback for vault initialization errors - use it for logging. Wrap the subtree in a React error boundary to recover from initialization failures. |

#### Secure field components

Each `Coinme*Field` component wraps a VGS secure input and binds it to the provider's vault

collector. You style and use them like ordinary React Native text inputs. The raw value typed

by the user stays inside VGS - it is not exposed through the component's ref, `onStateChange` callback, or any other prop.

| Component | Purpose |
| --- | --- |
| `CoinmeCardNumberField` | Card number with Luhn validation, brand detection, and masking. |
| `CoinmeExpiryField` | Expiry date in `MM/YY` format; validates that the date is in the future. On submit, splits into separate `exp_month` and `exp_year` values. |
| `CoinmeCvcField` | Security code; adapts to the detected card brand (3 or 4 digits). |
| `CoinmeCardHolderField` | Cardholder name. |
| `CoinmeTextField` | Generic secure field for other sensitive values (billing address lines, ZIP code, SSN, etc.). Use the `type` prop to select behaviour. |

Every field accepts all of the underlying VGS input's props - `placeholder`, `onStateChange`, `validationRules`, `maxLength`, `containerStyle`, `textStyle`, and so on - except `collector` (the SDK supplies this from the vault) and `type` (fixed on the dedicated card/CVC/expiry fields).

Fields expose a `ref` with `focus()` and `blur()` for programmatic focus management.

#### Field names

Wire each field's `fieldName` prop to the corresponding constant from `VAULT_FIELD_NAMES`. This keeps collected data aligned with the request body template used by `submitPaymentMethod`:

```typescript
import { VAULT_FIELD_NAMES } from '@coinme-security/vault-sdk-react-native';

// Available names: pan, cvc, expiry, address1, address2, city, zipcode
<CoinmeCardNumberField fieldName={VAULT_FIELD_NAMES.pan} />
```

#### Hooks

`useCoinmeVault()` - returns the vault from the nearest `CoinmeVaultProvider`, with a `submit()` method and the underlying VGS `collector` for advanced use. Throws if called outside a provider.

`useVaultFormValidity()` - aggregates validity across every field registered with the

provider. `isValid` is `true` only when at least one field is registered and every registered field is valid. `fields` is a map of all field states keyed by `fieldName`.

```tsx
const { isValid, fields } = useVaultFormValidity();
<Button title="Submit" onPress={onSubmit} disabled={!isValid} />
```

> Plain (non-PCI) inputs collected with a regular React Native `TextInput` - such as a billing
>
> `state` dropdown - are not tracked by `useVaultFormValidity`. Gate your submit button on `isValid` **and** your own checks for any plain inputs.

`useVaultFieldState(fieldName)` - returns the current `VGSTextInputState` for one named field, or `undefined` until the field first reports. Once the last field with that name unmounts, its state is cleared and this returns `undefined` again, so read values such as `last4` while the field is mounted. Use it to show per-field validation feedback. The state object contains non-sensitive metadata only: `isValid`, `isDirty`, `isEmpty`, `isFocused`, and for card fields, `last4`, `bin`, and `cardBrand`. Raw field values are never included.

```tsx
const pan = useVaultFieldState(VAULT_FIELD_NAMES.pan);

{pan?.isDirty && !pan.isValid && (
  <Text>Please enter a valid card number.</Text>
)}
```

### Submitting a payment method

> **Never use your partner access token with the Vault SDK.**
>
> The `Authorization` header must be `Bearer <transient-auth-token>` with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend mints from `POST /services/browserAuth`. Never pass your partner access token (from `POST /services/authorize`) to the SDK.

From 1.2.3 the SDK refuses a submit whose `Authorization` header carries a partner access token and throws a `configuration` `CoinmeVaultError` 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` and return only its `access_token`. The partner access token is a long-lived credential that must stay on your backend.

For Coinme's payment-method endpoint specifically, the SDK ships a `submitPaymentMethod` helper that assembles the nested request body for you. The card number, expiry, CVC, and billing address fields are wired in securely by their `VAULT_FIELD_NAMES`; the remaining values (`customerId`, `paymentProcessAssociation`, billing first/last name, etc.) are plain literals you supply.

```tsx
import {
  CoinmeCardNumberField,
  CoinmeExpiryField,
  CoinmeCvcField,
  CoinmeTextField,
  CoinmeVaultError,
  NotEmptyRule,
  submitPaymentMethod,
  useCoinmeVault,
  useVaultFormValidity,
  VAULT_FIELD_NAMES,
} from '@coinme-security/vault-sdk-react-native';
import { useState } from 'react';
import { Button, Text, TextInput, View } from 'react-native';

// Define validation rules outside the component so fields don't re-register on every render.
const streetRules = [new NotEmptyRule('Street address is required')];
const cityRules   = [new NotEmptyRule('City is required')];
const zipRules    = [new NotEmptyRule('ZIP code is required')];

const PaymentMethodForm = () => {
  const vault = useCoinmeVault();
  const { isValid } = useVaultFormValidity();
  const [state, setState] = useState('');
  const [status, setStatus] = useState('');

  const onSubmit = async () => {
    try {
      const result = await submitPaymentMethod(vault, {
        customerId: 'customer_123',
        paymentProcessAssociation: 'BUY',     // 'BUY' | 'SELL'
        paymentProviderId: 'provider_123',
        webSessionId: 'session_123',           // Risk SDK session tag, fetched right before this call
        billingAddress: {
          firstName: 'Jane',
          lastName: 'Doe',
          state,                               // collected via plain TextInput below
          country: 'US',                       // optional; defaults to 'US'
        },
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Bearer <transient-auth-token>',
          // From 1.3.0, with Risk SDK for React Native 1.1.0 or later, X-Device-Fingerprint
          // is added for you. Otherwise pass the same value you gave the Risk SDK.
        },
      });
      setStatus(`OK ${result.status}`);
    } catch (error) {
      if (error instanceof CoinmeVaultError) {
        setStatus(`${error.kind}: ${error.message}`);
      }
    }
  };

  return (
    <View>
      <CoinmeCardNumberField fieldName={VAULT_FIELD_NAMES.pan} placeholder="Card number" />
      <CoinmeExpiryField     fieldName={VAULT_FIELD_NAMES.expiry} placeholder="MM/YY" />
      <CoinmeCvcField        fieldName={VAULT_FIELD_NAMES.cvc} placeholder="CVC" />
      <CoinmeTextField fieldName={VAULT_FIELD_NAMES.address1} placeholder="Street address"
        validationRules={streetRules} />
      <CoinmeTextField fieldName={VAULT_FIELD_NAMES.address2} placeholder="Apt / Suite (optional)" />
      <CoinmeTextField fieldName={VAULT_FIELD_NAMES.city} placeholder="City"
        validationRules={cityRules} />
      <CoinmeTextField fieldName={VAULT_FIELD_NAMES.zipcode} placeholder="ZIP code"
        validationRules={zipRules} />

      {/* Billing state is not PCI-sensitive - collect it with a plain TextInput. */}
      <TextInput value={state} onChangeText={setState} placeholder="State (e.g. WA)" />

      <Button
        title="Submit"
        onPress={onSubmit}
        disabled={!isValid || state.trim() === ''}
      />
      <Text>{status}</Text>
    </View>
  );
};
```

#### `submitPaymentMethod` input fields

| Field | Type | Notes |
| --- | --- | --- |
| `customerId` | `string` | The signed-in Coinme customer the payment method belongs to. |
| `paymentProcessAssociation` | `'BUY' \| 'SELL'` | Whether the card is being added for a buy or sell ramp. |
| `paymentProviderId` | `string` | Payment provider identifier; sent as `providerId` in the request body. |
| `webSessionId` | `string` | Risk SDK web session identifier (from the Coinme Risk SDK). Always required. Fetch it from the Risk SDK right before each submit: a session tag lives 30 minutes. |
| `billingAddress` | object | `{ firstName, lastName, state, country? }` - plain literals. `country` defaults to `'US'`. |
| `headers` | `Record<string, string>?` | Optional request headers, e.g. `Authorization`. From 1.3.0, with Risk SDK for React Native 1.1.0 or later, `X-Device-Fingerprint` is optional; see [Device fingerprint](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-react-native.md#device-fingerprint). |
| `timeoutMs` | `number?` | From 1.2.2. Per-call submit timeout (default 60 000 ms). On expiry the submit fails as a `network` error with `timedOut: true`, but the request may still have completed, so the outcome is unknown: check the user's payment methods before retrying, or you may add the same one twice. |

The card fields (`pan`, `cvc`, `expiry`) and billing fields (`address1`, `address2`, `city`, `zipcode`) are assembled into the request body using their `VAULT_FIELD_NAMES` constants. Every submit auto-attaches Coinme distributed-tracing headers (`X-B3-TraceId`, `X-B3-SpanId`); pass your own values in `headers` to override them. Headers apply to one submit, so pass the full set you need (including `Authorization`) on every call. From 1.2.2, submits on one vault run one at a time, in call order, and each is bounded by `timeoutMs` (timed from when it starts running), so a hung request times out and the next queued submit proceeds.

### Error handling

Every failure during submit - VGS field validation, network error, HTTP error, or a Coinme

application-level error - is normalized to a `CoinmeVaultError`. Catch it and branch on `error.kind`:

```typescript
try {
  await vault.submit();
} catch (error) {
  if (error instanceof CoinmeVaultError) {
    switch (error.kind) {
      case 'validation':
        // One or more fields failed VGS validation before the request was sent.
        showFieldErrors(error.fields); // Record<string, string[]>
        break;
      case 'server':
        // The request completed with a non-2xx HTTP status.
        reportStatus(error.status);
        break;
      case 'caas':
        // 2xx response, but Coinme's backend returned an application error envelope.
        reportCaas(error.errorResponse);
        break;
      case 'network':
        if (error.timedOut) {
          // From 1.2.2: the submit hit timeoutMs. The request may still have
          // completed, so check the user's payment methods before a retry.
          await refreshPaymentMethods();
        } else {
          // Not sent (offline, DNS failure, TLS error).
          showRetry();
        }
        break;
      case 'configuration':
        // From 1.2.3: refused before sending, because Authorization carries a
        // partner access token. Fix the integration; a retry won't help.
        reportIntegrationError(error.message);
        break;
      default:
        // 'unknown' - any other failure, including VGS misconfiguration.
        showRetry();
    }
  }
}
```

| `kind` | Meaning | Extra fields |
| --- | --- | --- |
| `validation` | A field failed VGS validation before the request was sent. | `fields` - `Record<string, string[]>` of VGS messages |
| `server` | The request completed with a non-2xx status. | `status` |
| `caas` | 2xx response carrying a Coinme application-level error envelope. | `status`, `errorResponse` |
| `network` | No response was received. Either the request was not sent (offline, DNS/TLS failure), or, from 1.2.2, the submit hit `timeoutMs`, in which case the request may still have completed and the outcome is unknown. | `timedOut: true` on a timeout, from 1.2.2 |
| `configuration` | From 1.2.3. Refused before sending: the `Authorization` header carries a partner access token instead of a Transient Auth Token. Retrying will not help. | - |
| `unknown` | Any other failure, including VGS misconfiguration. | - |

`CoinmeVaultError` never contains raw card data. Where a failure wraps an underlying error, the original is on `error.cause`. A `caas` failure carries the backend envelope on `error.errorResponse` instead, and a request that times out has no `cause`.

A timeout is not proof that nothing happened: the request may still be delivered after the SDK stops waiting. Never retry a timed-out submit blindly, or you may add the same payment method twice. Check the current state first (for example, re-list the user's payment methods) and retry only if the item is missing.

### Advanced topics

These sections cover less common integration scenarios. Most integrations won't need them.

#### Custom ingress or submit path

By default the SDK submits to the ingress host and path baked into the selected environment. To override either for a given environment, pass a `config` prop to `CoinmeVaultProvider`. You must supply entries for both `sandbox` and `live`; `environment` decides which is active. The vault ID itself is never configurable at runtime.

> **You should never pass in a custom ingress unless you have been explicitly directed to do so by your Coinme integration contact.**Doing so can break your integration and can result in PCI compliance issues that would cripple your card processing efforts.
>
> **When in doubt:** pass only environment; let the SDK do the work for you.

```tsx
<CoinmeVaultProvider
  environment="sandbox"
  config={{
    sandbox: {
      ingress: 'https://secure.sandbox.example.com',
      path: '/your/submit/path',
    },
    live: {
      ingress: 'https://secure.example.com',
      path: '/your/submit/path',
    },
  }}
>
  <CardForm />
</CoinmeVaultProvider>
```

#### Custom request body

When your ingress expects a body shape other than the built-in payment-method one, call `vault.submit()` directly. Provide plain values in `extraData` and reference collected fields via `{{ fieldName }}` placeholders in `customRequestStructure` - VGS resolves them securely at

submit time.

```typescript
await vault.submit({
  extraData: { customerId: 'cust_123' },
  customRequestStructure: {
    card: {
      number: `{{ ${VAULT_FIELD_NAMES.pan} }}`,
      cvv:    `{{ ${VAULT_FIELD_NAMES.cvc} }}`,
    },
  },
  headers: { Authorization: `Bearer ${transientAuthToken}` },
});
```

#### Using a vault without the provider

If wrapping your form in `CoinmeVaultProvider` is not practical, you can construct the vault directly with `createCoinmeVault` and pass it to each field and to `submitPaymentMethod` via the `vault` prop or argument. You are responsible for calling `vault.dispose()` on unmount.

```tsx
import { createCoinmeVault } from '@coinme-security/vault-sdk-react-native';
import { useMemo, useEffect } from 'react';

const PaymentForm = () => {
  const vault = useMemo(() => createCoinmeVault({ environment: 'sandbox' }), []);
  useEffect(() => () => vault.dispose(), [vault]);

  return (
    <>
      <CoinmeCardNumberField vault={vault} fieldName={VAULT_FIELD_NAMES.pan} />
      <CoinmeExpiryField vault={vault} fieldName={VAULT_FIELD_NAMES.expiry} />
      <CoinmeCvcField vault={vault} fieldName={VAULT_FIELD_NAMES.cvc} />
      <Button onPress={() => submitPaymentMethod(vault, input)} title="Submit" />
    </>
  );
};
```

Note that `useVaultFormValidity()` and `useVaultFieldState()` depend on the provider's field registry. Without a provider, track validity yourself using each field's `onStateChange` prop.

#### Raw VGS access

The SDK re-exports the entire `@vgs/collect-react-native` public API, so VGS primitives -

validation rules like `NotEmptyRule`, `VGSError`, `VGSErrorCode`, `VGSTextInputState`, and

serializers - are importable directly from this package:

```typescript
import { NotEmptyRule, VGSError } from '@coinme-security/vault-sdk-react-native';
```

For their full API, see the [VGS Collect React Native documentation](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/react-native-sdk).

### Security rules

These rules apply to your integration. They carry through directly from VGS:

- **Never log or persist raw card values.** Use only the state metadata surfaced by `VGSTextInputState` (e.g. `isValid`, `isDirty`, `last4`, `cardBrand`) and the parsed

response body. The raw PAN, CVC, and expiry are never accessible to your code - keep it

that way.
- **Always gate submit on validity.** Use `useVaultFormValidity()` to disable your submit button until `isValid` is `true`. This prevents a malformed card from ever being sent.
- **Import only from the package root.** Never reach into `@vgs/collect-react-native` subpaths directly.

### Example apps

Runnable reference implementations are included in the SDK repository:

- `examples/bare` - bare React Native app with the full payment-method form.
- `examples/expo` - Expo equivalent.

Both examples render a complete card + billing address form, gate submit on validity, and branch `CoinmeVaultError` by kind.

### Troubleshooting

`401`**/ authentication error during install** - `CLOUDSMITH_TEAM_TOKEN` is missing or expired. Re-export it and reinstall:

```bash
export CLOUDSMITH_TEAM_TOKEN=<your-token>
yarn install
```

`Unable to resolve "@vgs/collect-react-native"` - the peer dependency is not installed.

Add it explicitly:

```bash
yarn add @vgs/collect-react-native
```

`CoinmeCardNumberField needs a vault`**/**`useCoinmeVault must be used within a CoinmeVaultProvider`

- a field or hook is being rendered outside the provider. Wrap the relevant subtree in

`<CoinmeVaultProvider environment="…">`, or pass an explicit `vault` prop to the field.

**Submit button never enables** - `useVaultFormValidity()` requires every registered field to be valid. Check that each field has a `fieldName`, that fields with required input have `validationRules` set, and that any plain `TextInput` values are validated separately (they do not register with the vault and are not counted by `isValid`).

**Metro can't resolve the SDK after install** - clear Metro's cache:

```bash
# bare React Native
npx react-native start --reset-cache

# Expo
npx expo start --clear
```

**Expo: secure fields don't render, or submit fails** - confirm `@vgs/collect-react-native` is on a `1.x` release (pure JS). If your app requires native modules outside this SDK, you may need a development build (`npx expo prebuild`) for those modules; the SDK itself runs identically in Expo Go or a development build.

## Device fingerprint

Coinme ties risk checks to a device ID sent as the `X-Device-Fingerprint` header. On the web and React Native you don't have to supply one.

- If you pass a fingerprint, 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`.
- Leaving the header out needs these releases or later: Risk SDK for Web 1.2.0, Risk SDK for React Native 1.1.0, Vault SDK for JavaScript 1.3.0, Vault SDK for React Native 1.3.0, Onboarding SDK for JavaScript & React 1.7.0, Onboarding SDK for React Native 1.2.0. With an older release, pass every Coinme SDK the same `X-Device-Fingerprint` you give the Risk SDK.
- Calls your server makes to Coinme for this user (for example orders) must send the same value. Read it in your web page or app with the SDK's `getDeviceFingerprint()` (on React Native it returns a Promise) and send it to your server with the request. Never call `getDeviceFingerprint()` on your server.
- On the web the value belongs to the browser and the site's origin, not the device: a page on another origin gets a different one.
- A `:` in the value is replaced with `-`.
- A risk session tag lives 30 minutes from when it was first issued. Fetch it right before adding a payment method or placing an order, and send the tag it returns as `webSessionId`.

The Risk SDK for React Native keeps the shared value in your app's native storage, so it survives relaunches. Import it at the top of your app's entry file (for example `index.js`), before anything else that uses a Coinme SDK, so the stored value is loaded before this SDK sends a request:

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

## Verify

Build and run the app. Confirm the secure fields render and validate, that the submit control stays disabled until the form is valid, that the client gets a Transient Auth Token from the human's backend route and sends it as `Authorization: Bearer <token>` together with a Risk SDK session id fetched right before the submit and the device fingerprint the Risk SDK uses, that the `Authorization` header never carries the partner access token, and that no token or backend credential is in the client or a committed file.

### Reading the result

**Done when:** Invalid input keeps the form invalid, the submit succeeds, and listing the customer's payment methods from your backend shows the card `CREATED`.

**Stop and ask the human when** the card is refused as in use and you cannot find the earlier test that holds it, or the session tag keeps failing to match after you minted it on the same device.

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.

## Reference
- [Coinme Vault SDK](https://platformdocs.coinme.com/docs/coinme-vault-sdk.md)
- [Coinme Vault SDK for React Native](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-react-native.md)
- [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)
