# Vault SDK: Coinme App Platform > Every page and skill for the Vault SDK, in one file: the SDK documents and guides, and the Agent Skills that integrate it. The Vault SDK belongs to the Coinme-as-a-Service (CaaS) integration; https://platformdocs.coinme.com/agents/surfaces.md explains the two surfaces. The index of the whole site is https://platformdocs.coinme.com/llms.txt. --- --- title: "Coinme Vault SDK" url: "https://platformdocs.coinme.com/#/docs/coinme-vault-sdk" markdown: "https://platformdocs.coinme.com/docs/coinme-vault-sdk.md" summary: "The Coinme Vault SDK lets your application collect sensitive information like payment card data - card number, expiry, CVC, cardholder name, and billing address - without any of those values ever touching your code, your logs, or your servers. Data is entered into secure input fields managed by the SDK and travels directly to Coinme's PCI-compliant vault; your application receives only a confirmation response and non-sensitive metadata (such as a payment card's last four digits and brand)." surface: "caas" source: "https://docs.coinme.com/docs/coinme-vault-sdk" updated: "2026-10-28" --- # Coinme Vault SDK The Coinme Vault SDK lets your application collect sensitive information like payment card data - card number, expiry, CVC, cardholder name, and billing address - without any of those values ever touching your code, your logs, or your servers. Data is entered into secure input fields managed by the SDK and travels directly to Coinme's PCI-compliant vault; your application receives only a confirmation response and non-sensitive metadata (such as a payment card's last four digits and brand). **What the SDK provides:** - **Secure capture**: Data is collected in secure fields that look and behave like your platform's native inputs, but whose raw values are never accessible to your application code. - **Direct-to-vault transport**: collected values are routed through a secure proxy straight to Coinme's vault, bypassing your backend entirely and keeping raw data out of your PCI scope. - **Built-in validation**: card number (Luhn and brand detection), expiry, and CVC are validated before anything is submitted, so malformed card data never reaches the server. - **Coinme-ready configuration**: the SDK is pre-configured for Coinme's `sandbox` and `live` environments and ships a helper for submitting payment methods to Coinme's payment endpoints. No vault credentials or routing configuration are required. - **What's Next?**: the SDK will be extended to collect other forms of sensitive data such as SSN, and more platform coverage will be provided. ## Authentication for Coinme endpoints > **Never use your partner access token with the Vault SDK.** > > The payment-method submit's `Authorization` header must be `Bearer ` with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend mints from `POST /services/browserAuth`, for the customer adding the card. Never pass your partner access token (from `POST /services/authorize`) to the SDK. --- --- title: "Coinme Vault SDK for Javascript" url: "https://platformdocs.coinme.com/#/docs/coinme-vault-sdk-for-javascript" markdown: "https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md" summary: "`@coinme-security/vault-sdk-js` is a typed, framework-agnostic JavaScript wrapper that lets any web app capture debit card data - card number, expiry, CVC, billing address, and other sensitive values - without those values ever touching your JavaScript, your DOM, your logs, or your backend. You render containers for the secure fields; the SDK mounts VGS-hosted inputs into them; your code receives only a confirmation response." surface: "caas" platform: "web" package: "@coinme-security/vault-sdk-js" version: "1.3.0" source: "https://docs.coinme.com/docs/coinme-vault-sdk-for-javascript" updated: "2026-10-28" --- # Coinme Vault SDK for Javascript `@coinme-security/vault-sdk-js` is a typed, framework-agnostic JavaScript wrapper that lets any web app capture debit card data - card number, expiry, CVC, billing address, and other sensitive values - without those values ever touching your JavaScript, your DOM, your logs, or your backend. You render containers for the secure fields; the SDK mounts VGS-hosted inputs into them; your code receives only a confirmation response. The SDK works with any web stack - vanilla JS, React, Vue, Angular, Svelte, or any SSR framework - because the secure fields are cross-origin iframes, not framework components. You wire them up in a handful of calls. ## How it works The SDK wraps [VGS Collect.js](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/index), a browser library from Very Good Security that handles the mechanics of secure card capture. VGS acts as a secure proxy: each field the SDK creates is a cross-origin iframe served by VGS, not an input element in your page. Values typed by the user are captured inside those iframes and submitted directly to Coinme's vault - they never enter your JavaScript, your DOM tree, or any network request your code can inspect. The SDK pre-binds Coinme's VGS vault configuration. You never supply a vault ID, ingress route, or submit path - just pick an `environment` (`sandbox` or `live`) and the SDK resolves everything else. ### The iframe model - what it means for your integration Because each secure field is an iframe served from VGS's domain, a few things work differently from a regular ``: - **Your page CSS cannot reach inside the fields.** Styling is applied through a `css` option you pass at field creation time - see [Styling](#styling). - **You can't read the field values back.** The fields are intentionally opaque. You get state metadata - `isValid`, `isDirty`, `last4`, `cardBrand` - but never the raw value. - **Field containers must exist in the DOM before you create fields.** The factory calls (`vault.createCardNumberField`, etc.) mount iframes into the container elements you pass. If a container doesn't exist yet, the field won't render. - **Vault creation is browser-only.** `createCoinmeVault` loads VGS Collect.js from the VGS CDN and needs a `window`. Calling it during server-side rendering will reject - see [SSR frameworks](#ssr-frameworks-next-js-nuxt-sveltekit). ### What VGS Collect.js version is used? VGS Collect.js is loaded at runtime from the VGS CDN (for PCI script attestation). The SDK pins to version **4.0.1** - exposed as the `VGS_COLLECT_VERSION` export if you need to reference it. The SDK also ships full TypeScript typings for the VGS Collect surface, which VGS itself does not provide. ## Prerequisites Before you install the SDK: | Requirement | Details | | --- | --- | | Browser target | Evergreen Chrome, Firefox, Edge; Safari 10+. Vault creation is browser-only. | | Node (build-time) | Any version that supports your build tool. Importing the package in Node is side-effect safe; creating a vault there is not. | | `CLOUDSMITH_TEAM_TOKEN` | Coinme Cloudsmith entitlement token - see below. | | Content-Security-Policy | If your site sets a CSP, you must add VGS domains before the SDK will work - see [CSP](#content-security-policy). | ### 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. To obtain one, ask your Coinme integration contact. ### Content-Security-Policy If your site sets a `Content-Security-Policy`, the secure fields (iframes) and the VGS Collect.js script load from VGS's domains. Add these entries before you begin: ``` 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 ``` Also add your Coinme ingress host under `connect-src`. (`js3.verygoodvault.com` is VGS's fallback CDN; `vgs-collect-keeper` receives VGS product-interaction analytics.) If either domain is missing, the fields will fail to render or `createCoinmeVault` will reject with a network error. ## Installation ### 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. Keep the token itself out of source control - supply it as an environment variable. ### Step 2 - Install ```bash export CLOUDSMITH_TEAM_TOKEN= yarn add @coinme-security/vault-sdk-js ``` There is no peer dependency to install separately. The `@vgs/collect-js` loader ships as a regular dependency of the SDK. ## Quickstart Here is the minimum integration for vanilla JS - container elements, vault creation, field mounting, gated submit, and error handling. If you're using React, Vue, or an SSR framework, see [Framework setup](#framework-setup) below. ```markup
``` ```typescript import { CoinmeVaultError, createCoinmeVault, } from '@coinme-security/vault-sdk-js'; // createCoinmeVault is async - it loads VGS Collect.js from the VGS CDN. const vault = await createCoinmeVault({ environment: 'sandbox' }); // Mount secure fields into the container elements. // These calls return raw VGS field instances. vault.createCardNumberField('#pan', { placeholder: 'Card number' }); vault.createExpiryField('#expiry', { placeholder: 'MM / YYYY' }); vault.createCvcField('#cvc', { placeholder: 'CVC' }); // Subscribe to form state changes to gate the submit button. const button = document.querySelector('#submit')!; vault.subscribe(() => { button.disabled = !vault.getFormState().isValid; }); button.addEventListener('click', async () => { try { const result = await vault.submit(); // result.status is the HTTP status; result.data is the parsed response body. // Raw field values are never available here. console.log('OK', result.status); } catch (error) { if (error instanceof CoinmeVaultError) { console.log(`${error.kind}: ${error.message}`); } } }); // Call when the hosting view is removed. // vault.dispose(); ``` Three things to notice: - `createCoinmeVault`**is async.** It loads VGS Collect.js from the CDN before resolving. Wait for it before calling any field factories. - **Field containers must exist first.** The factory calls (`createCardNumberField`, etc.) mount iframes into DOM elements. Create the vault and call the factories only after your containers are in the DOM. - `vault.subscribe` notifies on every field-state change and returns an unsubscribe function. Poll `vault.getFormState().isValid` inside it to keep your submit button in sync. > **It's Easy!** > > For the vast majority of deployments, all you need to pass to `createCoinmeVault` 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. ## Framework setup The SDK is framework-agnostic, but a few integration patterns are worth following per framework to get lifecycle and cleanup right. ### React Vault creation is async and browser-only, so it belongs in a `useEffect`. Secure fields must be created after their container `
`s mount, and deleted in cleanup to prevent React 18 StrictMode's double-invocation from stacking duplicate iframes: ```tsx import { createCoinmeVault, type CoinmeVault, } from '@coinme-security/vault-sdk-js'; import { useEffect, useState, useSyncExternalStore } from 'react'; /** Creates the vault on mount (browser-only), disposes on unmount. */ const useCoinmeVault = () => { const [vault, setVault] = useState(); useEffect(() => { let disposed = false; let created: CoinmeVault | undefined; createCoinmeVault({ environment: 'sandbox' }).then((v) => { if (disposed) return v.dispose(); created = v; setVault(v); }); return () => { disposed = true; created?.dispose(); }; }, []); return vault; }; /** Reactive form state - snapshot is referentially stable, no memo needed. */ const useVaultFormState = (vault: CoinmeVault) => useSyncExternalStore(vault.subscribe, vault.getFormState); ``` Create fields in a separate effect, with cleanup: ```tsx useEffect(() => { if (!vault) return; const fields = [ vault.createCardNumberField('#pan'), vault.createExpiryField('#expiry'), vault.createCvcField('#cvc'), ]; // Delete fields in cleanup so React StrictMode's double-run doesn't stack iframes. return () => fields.forEach((field) => field.delete()); }, [vault]); ``` A full working example is in `examples/react` in the SDK repository. ### Vue 3 Same lifecycle, Vue idioms - create the vault in `onMounted`, dispose in `onUnmounted`, mirror form state into a `ref`: ```markup ``` ### SSR frameworks (Next.js, Nuxt, SvelteKit, …) Importing the package on the server is safe - the module has no load-time browser side effects. **Creating a vault is browser-only** - `createCoinmeVault` rejects if there is no `window`. Keep these points in mind: - Create the vault inside client-side lifecycle code: `useEffect` (Next.js), `onMounted` (Nuxt), `onMount` (SvelteKit). The React and Vue examples above already do this. - In Next.js App Router, add the `'use client'` directive to your form component. - Don't render secure-field containers on the server expecting them to be filled - fields mount only after the client-side vault exists. - Add CSP headers in your framework's config (e.g. `next.config.js` headers) - see [CSP](#content-security-policy). ## Secure fields Five factory methods are available on the vault instance. Each one mounts a cross-origin iframe into the container matched by the CSS selector you pass, and returns the raw VGS field instance. All VGS field methods - `mask()`, `replacePattern()`, `update()`, `reset()`, `delete()`, `focus()`, `on()`/`off()`, and the `promise` readiness signal - work exactly as [VGS documents them](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/reference-documentation). | Factory | Purpose | | --- | --- | | `createCardNumberField` | Card number with Luhn validation, brand detection, and masking. Defaults to name `pan`. Add `showCardIcon: true` for a brand icon inside the field. | | `createExpiryField` | Expiry date in `MM / YYYY` format, with a built-in not-in-the-past check. On submit, a serializer splits it into `exp_month` and a 4-digit `exp_year`. Defaults to name `expiry`. | | `createCvcField` | Security code; adapts to the detected card brand (3 or 4 digits). Defaults to name `cvc`. | | `createCardHolderField` | Cardholder name - for flows that need it collected securely. (The payment-method helper accepts name literals instead.) Defaults to name `cardholder`. | | `createTextField` | Generic secure field for other sensitive values: billing address lines, city, ZIP, SSN, etc. `name` is required. Choose field behaviour with `type` (`'text'`, `'ssn'`, `'zip-code'`, `'password'`, `'textarea'`, and others). | Every factory passes all options through to VGS unfiltered, so new VGS options work without an SDK update. > **Expiry year width.** > > The payment-method endpoint requires a 4-digit year. The expiry factory defaults to `MM / YYYY` accordingly. Override `yearLength: 2` only if your endpoint accepts 2-digit years. ### Field names `VAULT_FIELD_NAMES` provides the conventional field-name constants - `pan`, `cvc`, `expiry`, `address1`, `address2`, `city`, `zipcode`. The card factories default to them. Pass them explicitly on `createTextField` so collected values line up with the payment-method request template: ```typescript import { VAULT_FIELD_NAMES } from '@coinme-security/vault-sdk-js'; vault.createTextField('#address1', { name: VAULT_FIELD_NAMES.address1, validations: ['required'], }); ``` ## Styling Because secure fields render inside VGS iframes, ordinary page CSS cannot reach inside them. There are two complementary approaches. ### Inside the field: the `css` option Style the field's text input with the `css` option. It supports regular CSS properties, pseudo-classes and pseudo-elements, nested `&` selectors, the VGS field state classes, web fonts via `@font-face`, and media queries: ```typescript vault.createCardNumberField('#pan', { css: { 'font-family': '"Inter", system-ui, sans-serif', 'font-size': '16px', color: '#1b1d1f', '&::placeholder': { color: '#9aa0a6' }, '&:focus': { color: '#000' }, // VGS state classes: valid, invalid, empty, dirty, touched '&.invalid.touched': { color: '#c5221f' }, '@font-face': { 'font-family': 'Inter', src: 'url("https://example.com/inter.woff2")', }, }, }); ``` > Media queries inside `css` are computed against the **iframe's** width, not the page's. ### Around the field: the `classes` option Your host container `
` receives state classes from VGS that you can target with regular page CSS. Map them to your own class names with the `classes` option: ```typescript vault.createCvcField('#cvc', { classes: { invalid: 'field-invalid', focused: 'field-focused' }, }); ``` ```css .field-focused { border-color: #1a73e8; } .field-invalid { border-color: #c5221f; } ``` VGS's default class names (if you don't override them) are `vgs-collect-container__invalid`, `__focused`, `__empty`, `__dirty`, and `__touched`. ### Masks and input shaping Text-like fields expose VGS's chainable formatting API on the returned instance: ```typescript const ssn = vault.createTextField('#ssn', { name: 'ssn', type: 'ssn' }); ssn.mask('999-99-9999', '*'); // 9: digit, a: letter, *: alphanumeric ssn.replacePattern('/[^0-9-]+/g'); // strip anything else as the user types ``` For the full option-by-option reference, see the VGS [customization](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/customization) and [formatting](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/formatting) pages - everything there is reachable through the factories' options and returned instances. ## Form state and validity `vault.getFormState()` returns `{ isValid, fields }`. `vault.subscribe(listener)` fires on every field-state change and returns an unsubscribe function. ```typescript const unsubscribe = vault.subscribe(() => { const { isValid, fields } = vault.getFormState(); submitButton.disabled = !isValid; panHint.hidden = !(fields.pan?.isDirty && !fields.pan?.isValid); }); ``` `isValid` is `true` only when at least one field exists and every field reports valid. A validation-free `createTextField` (e.g. an optional apartment line) counts as valid while empty and won't block submission; fields with `validations` stay invalid until they pass. Each entry in `fields` carries non-sensitive state and metadata: `isValid`, `isDirty`, `isEmpty`, `isFocused`, `isTouched`, `errorMessages`, and for card fields `last4`, `bin`, and `cardType`. Raw field values are never included. The form state snapshot is referentially stable between changes, so it plugs directly into React's `useSyncExternalStore`: ```typescript useSyncExternalStore(vault.subscribe, () => vault.getFormState()) ``` > Plain (non-PCI) inputs collected with a regular `` - such as a billing `state` > > dropdown - are not part of the vault. Gate your submit on `isValid` **and** your own checks for any plain inputs. ## Submitting a payment method > **Never use your partner access token with the Vault SDK.** > > The `Authorization` header must be `Bearer ` 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 browser. 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 by their `VAULT_FIELD_NAMES`; the remaining values (`customerId`, billing first/last name, etc.) are plain literals you supply. ```typescript import { submitPaymentMethod, VAULT_FIELD_NAMES, } from '@coinme-security/vault-sdk-js'; // Mount secure fields using VAULT_FIELD_NAMES so values line up with the request template. vault.createCardNumberField('#pan'); vault.createExpiryField('#expiry'); vault.createCvcField('#cvc'); vault.createTextField('#address1', { name: VAULT_FIELD_NAMES.address1, validations: ['required'] }); vault.createTextField('#address2', { name: VAULT_FIELD_NAMES.address2 }); vault.createTextField('#city', { name: VAULT_FIELD_NAMES.city, validations: ['required'] }); vault.createTextField('#zipcode', { name: VAULT_FIELD_NAMES.zipcode, validations: ['required', 'postal_code/us'] }); 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: 'WA', // plain literal, e.g. from a regular ` values are validated separately - they don't register with the vault and don't count toward `isValid`. **Submits succeed but hit the wrong host** - an unregistered ingress CNAME silently falls back to the default vault URL rather than failing. Verify the ingress value in sandbox before using it in production - see the [ingress caveat](#custom-ingress-or-submit-path). **React StrictMode shows doubled fields in development** - create fields in a `useEffect` and delete them in its cleanup function. See the [React setup](#react) section and `examples/react` in the SDK repository. ## 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`. --- --- title: "Coinme Vault SDK for iOS Native" url: "https://platformdocs.coinme.com/#/docs/coinme-vault-sdk-for-ios-native" markdown: "https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-ios-native.md" summary: "The Coinme Vault SDK for iOS is a Swift SDK that wraps the VGS Collect iOS SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process." surface: "caas" platform: "ios" package: "CoinmeVault · Swift" version: "1.0.1" source: "https://docs.coinme.com/docs/coinme-vault-sdk-for-ios-native" updated: "2026-10-28" --- # Coinme Vault SDK for iOS Native ## Introduction The Coinme Vault SDK for iOS is a Swift SDK that wraps the VGS Collect iOS SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process. It is the iOS counterpart to the Coinme Vault SDK for Android, and the public API mirrors the Android SDK for cross-platform parity. **Security model:** Secure field values (card number, CVV, …) never leave the VGS field views and never enter your application process. The SDK exposes only validity and non-sensitive metadata (`isValid`, `isEmpty`, `cardBrand`, `last4`, …). Submission goes directly from the VGS views to the vault. **Error messages never contain field values (PII).** ### What Does It Collect? The SDK collects only the payment data you explicitly bind into its fields, and submits it directly to the Coinme vault. The supported fields are: - **Card data** — card number, expiry month/year, CVV - **Cardholder name** - **Billing address** — address lines, city, ZIP code Your application never receives the raw field values — it sees only validity state and non-sensitive metadata such as the detected card brand and the last four digits. ## SDK Requirements | Requirement | Value | | --- | --- | | Minimum iOS | 15.0 | | Swift | 5.9 | | VGS Collect | `~> 1.18` (resolves transitively) | VGS Collect is resolved as a normal dependency, so the VGS field-view classes (`VGSCardTextField`, …) are available on your compile classpath without an extra dependency. ## Installation **IMPORTANT:** Ask your Coinme integration contact to obtain your Cloudsmith **entitlement token**. The library publishes to Cloudsmith (`coinme/coinme-sdk-mobile`) for both Swift Package Manager and CocoaPods. ### Swift Package Manager One-time registry login (uses your Cloudsmith entitlement token): ``` swift package-registry set https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/swift package-registry login https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ \ --username YOUR_USERNAME --password YOUR_ENTITLEMENT_TOKEN ``` Then add the dependency: `Package.swift` ```swift // Package.swift .package(id: "coinme.CoinmeVaultSDK", from: "1.0.0") ``` The SDK pulls VGSCollectSDK via SCM. To resolve it through the registry instead, run: ``` swift package --replace-scm-with-registry resolve ``` To add the package in Xcode: **File → Add Package Dependencies**, add the registry URL above, then search for `coinme.CoinmeVaultSDK`. ### CocoaPods `Podfile` ```swift # Podfile — supplied by Coinme source 'https://dl.cloudsmith.io//coinme/coinme-sdk-mobile/cocoapods/index.git' source 'https://cdn.cocoapods.org/' target 'YourApp' do use_frameworks! pod 'CoinmeVaultSDK', '~> 1.0' # pulls VGSCollectSDK transitively end ``` ## Configuration The account-scoped **vault ID** is baked into the library per environment at publish time and is never passed by callers. For local development, copy `local.properties.example` to `local.properties` and fill in: ``` COINME_VAULT_ID_SANDBOX=your_sandbox_vault_id COINME_VAULT_ID_LIVE=your_live_vault_id ``` **Ingress hostnames and the submit path are not configured here** — they are public, stable values baked into the SDK per environment (`config/VaultDefaults.swift`): sandbox → `secure.payments-stage.coinme.com`, live → `secure.payments.coinme.com`, path → `/caas/v2/paymentmethods`. They can be overridden per-runtime (but never the vault ID) via `RuntimeVaultConfig` — see Runtime configuration overrides below. ## Quick Start ```swift import CoinmeVaultSDK // 1. Create the vault for an environment. let vault = try CoinmeVault.create(environment: .sandbox) // 2. Build pre-named VGS fields against the vault's collector and bind them. let cardNumber = CoinmeFields.cardNumber(collector: vault.collector) let expiry = CoinmeFields.expiry(collector: vault.collector) let cvc = CoinmeFields.cvc(collector: vault.collector) let holder = CoinmeFields.cardHolder(collector: vault.collector) vault.bind(cardNumber, expiry, cvc, holder) // add the views to your view hierarchy too // 3. Observe form validity (drive your submit button's enabled state). vault.onFormStateChange = { state in submitButton.isEnabled = state.isValid } // 4. Submit. Throws CoinmeVaultError on failure. let result = try await vault.submit( VaultSubmitOptions( extraData: ["accountId": "abc", "country": "US"], headers: ["X-Request-Source": "ios"] ) ) print("status=\(result.status) body=\(result.body ?? "")") // 5. Release VGS resources when done (e.g. on screen teardown). vault.dispose() ``` `CoinmeVault` is `@MainActor` — create it, build fields, bind, and observe state on the main actor. ## Core Concepts | Type | Role | | --- | --- | | `CoinmeVault` | Entry point. Wraps a `VGSCollect` collector, tracks form validity, performs submits. `@MainActor`. | | `CoinmeVaultEnvironment` | `.sandbox` or `.live`. Selects the baked-in vault ID / ingress / path. | | `CoinmeFields` | Factory that builds VGS text fields with the correct Coinme field name and VGS type pre-set. | | `VaultFieldNames` | The dot-notation field-name constants VGS deep-merges into nested submit JSON. | | `VaultSubmitOptions` | Per-submit `extraData` (non-secure JSON) and `headers`. | | `VaultSubmitResult` | `status: Int`, `body: String?`, `data: Any?` on success. | | `CoinmeVaultError` | Error enum thrown by `submit`. | The collector is exposed as `vault.collector: VGSCollect` — both the input to the `CoinmeFields` factories and the documented escape hatch for advanced VGS usage not covered by the wrapper. ### Creating a vault ```swift let vault = try CoinmeVault.create( environment: .sandbox, config: nil // optional RuntimeVaultConfig; see "Runtime configuration overrides" ) ``` `create()` resolves the vault configuration, builds the underlying `VGSCollect`, and registers a single form-state listener. It throws `CoinmeVaultError.invalidConfiguration` if the vault ID is not baked in or an override is incomplete. Create **one** `CoinmeVault` per form/screen and `dispose()` it when the screen goes away. ### Field names Field names are **dot-notation keys** that VGS deep-merges into nested submit JSON (`card.cardNumber` → `{"card":{"cardNumber":...}}`). They are defined in `VaultFieldNames`: | Constant | Value | Notes | | --- | --- | --- | | `cardNumber` | `card.cardNumber` | | | `expMonth` | `card.month` | child of the expiry serializer | | `expYear` | `card.year` | child of the expiry serializer | | `cvc` | `card.cvv` | | | `cardHolder` | `cardHolderName` | | | `address1` | `billingAddress.addressLine1` | | | `address2` | `billingAddress.addressLine2` | | | `city` | `billingAddress.city` | | | `zipCode` | `billingAddress.zipCode` | | | `expiry` | `card` | parent field name for the expiry field | **The SDK submits every bound field.** Bind only the fields you intend to send. The expiry field is the special case: its own field name is `card` and it uses a `VGSExpDateSeparateSerializer(monthFieldName: "card.month", yearFieldName: "card.year")` so a single input writes two JSON keys. The year is forced to 4 digits on output. `CoinmeFields.expiry()` configures all of this for you. ## Building Fields VGS field views subscribe to their collector the moment their `configuration` is set, so each `CoinmeFields` factory takes the owning vault's collector: ```swift import CoinmeVaultSDK let cardNumber = CoinmeFields.cardNumber(collector: vault.collector) // VGSCardTextField, "card.cardNumber" let expiry = CoinmeFields.expiry(collector: vault.collector) // VGSExpDateTextField, separate-date serializer let cvc = CoinmeFields.cvc(collector: vault.collector) // VGSCVCTextField, "card.cvv" let holder = CoinmeFields.cardHolder(collector: vault.collector) // VGSTextField, "cardHolderName" let custom = CoinmeFields.text(collector: vault.collector, fieldName: "billingAddress.city") ``` `cardNumber`, `cvc`, and `cardHolder` accept an optional `fieldName` override; `expiry` does not (its serializer is fixed); `text` requires the field name. Returned views are ordinary `VGSTextField` subclasses — style them, add them to your view hierarchy, and `vault.bind(...)` them. ### Rendering VGS fields VGS fields are UIKit `UIView`s. In UIKit, add them to your view hierarchy directly. In SwiftUI, wrap each field in a `UIViewRepresentable` (the demo's `VGSFieldView` is the canonical reference): ```swift struct VGSFieldView: UIViewRepresentable { let field: VGSTextField func makeUIView(context: Context) -> VGSTextField { field } func updateUIView(_ uiView: VGSTextField, context: Context) {} } ``` Build the fields once (e.g. in your view model) so they aren't recreated on every SwiftUI render, then render each with `VGSFieldView(field: cardNumber)`. See the `Example/` app for a full working form. ### Binding fields ```swift func bind(_ fields: VGSTextField...) // required fields func bindOptional(_ fields: VGSTextField...) // optional fields ``` `bind` registers each field name with the form-validity tracker. **Registration seeds the field as invalid** — a freshly bound form reports `isValid == false` until VGS emits its first state change. Bind a field once. VGS emits no initial state, so an untouched field's validity is unknown until the user edits it. Use `bindOptional` for fields that may be left empty (e.g. `billingAddress.addressLine2`): they seed as **valid**, so an untouched form can still reach `isValid == true`. Fields with no configured `fieldName` are skipped by `bind`/`bindOptional` — always build them via `CoinmeFields` first. ## Observing Form State ```swift var formState: VaultFormState // current snapshot var formStatePublisher: AnyPublisher // Combine stream var onFormStateChange: ((VaultFormState) -> Void)? // non-Combine callback func fieldState(_ fieldName: String) -> VaultFieldState? // one field public struct VaultFormState: Equatable { public let fields: [String: VaultFieldState] public let isValid: Bool // true only when every bound field is valid } public struct VaultFieldState: Equatable { public let fieldName: String public let isValid: Bool public let isEmpty: Bool public let isFocused: Bool public let contentLength: Int public let cardBrand: String? // card-number field only public let last4: String? // card-number field only } ``` Typical use — drive the submit button: ```swift // Callback style: vault.onFormStateChange = { state in submitButton.isEnabled = state.isValid } // Combine style: vault.formStatePublisher .map(\.isValid) .receive(on: RunLoop.main) .assign(to: \.isEnabled, on: submitButton) .store(in: &cancellables) // React to a single field, e.g. show the detected card brand: let brand = vault.fieldState(VaultFieldNames.cardNumber)?.cardBrand ``` **No secure values are ever present in these snapshots** — only validity and the non-sensitive metadata shown above. ## Submitting the Data > **Never use your partner access token with the Vault SDK.** > > The `Authorization` header must be `Bearer ` 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. ```swift @discardableResult func submit(_ options: VaultSubmitOptions = VaultSubmitOptions()) async throws -> VaultSubmitResult public struct VaultSubmitOptions { public let extraData: [String: Any] // deep-merged into the submit JSON alongside fields public let headers: [String: String] // merged with trace headers; caller wins on conflict } ``` What `submit` does, in order: 1. **Pre-validates** from the tracker; if the form is invalid it throws `CoinmeVaultError.validation(fields:)` **before any network call**. 2. Generates per-request `X-B3-TraceId` / `X-B3-SpanId` and merges your `headers` on top (your headers win on conflict). 3. POSTs to the configured submit path with `extraData` as custom data via VGS. 4. Maps the response — including the **CAAS envelope** case where VGS returns HTTP 200 with a nested `errorResponse` payload (thrown as `CoinmeVaultError.caas`, not returned as success). **Only one submit may be in flight at a time** — a concurrent call throws `CoinmeVaultError.submitInProgress`. ### Completion-handler variant ```swift vault.submit(VaultSubmitOptions()) { (result: Result) in switch result { case .success(let r): // ... case .failure(let e): // ... } } ``` ### Payment-method convenience A higher-level helper for the CAAS payment-method endpoint: ```swift let result = try await vault.submitPaymentMethod( PaymentMethodInput( accountId: "abc", providerId: "prov-1", webSessionId: "sess-1", paymentProcessAssociation: .buy, // optional billingAddress* fields default to ""/omitted; country defaults to "US" billingAddressFirstName: "Jane", billingAddressLastName: "Doe", billingAddressState: "WA" ), headers: ["Authorization": "Bearer \(transientAuthToken)"] ) ``` It builds the CAAS `extraData` shape (`accountId`, `stagingProviderId`, `webSessionId`, `paymentProcessAssociation`, `billingAddress`) and delegates to `submit`. The card fields themselves are supplied securely by the bound VGS fields. ## Error Handling `submit` only ever throws `CoinmeVaultError` ```swift do { try await vault.submit(options) } catch let error as CoinmeVaultError { switch error { case .validation(let fields): fields.forEach { name, reasons in showFieldError(name, reasons) } case .caas: switch error.submitCardError { case .cardInUseByAnotherUser: showCardInUse() case .maxNumberOfCardsReached: showTooManyCards() default: showGenericError() } case .server(let status, _): showServerError(status) default: showGenericError() } } ``` | Case | Meaning | Associated values | | --- | --- | --- | | `.validation(fields:)` | Form invalid; thrown before any network call. | `[String: [String]]` — `["required"]` / `["invalid"]` per field | | `.network(underlying:)` | Connectivity / transport failure. | `Error?` | | `.server(status:body:)` | HTTP 4xx/5xx with no recognizable CAAS envelope. | `Int`, `String?` | | `.caas(status:errorResponse:)` | CAAS error envelope (4xx/5xx, or nested in an HTTP 200). | `Int`, `CaasErrorResponse` | | `.submitInProgress` | A submit is already in flight. | — | | `.invalidConfiguration(_:)` | Missing/invalid configuration (e.g. an unbaked vault ID). | `String` | | `.unknown(underlying:)` | Anything else. | `Error?` | `error.submitCardError` is a convenience on `CoinmeVaultError` that resolves the first known CAAS error code to a `SubmitCardError` (or `nil` if unrecognized). The raw code remains available via the associated `CaasErrorResponse` (`errorResponse.firstKnownError()?.errorCode`). `SubmitCardError` maps known CAAS card-submit codes to enum constants and is ported from the Coinme app to ease migration. **Error cases never carry a field value (PCI).** Log them freely. ## Runtime Configuration Overrides The vault ID is **always** baked in at publish time and cannot be overridden. The ingress host and submit path **can** be overridden at runtime by passing a `RuntimeVaultConfig` to `create`: ```swift let runtime = RuntimeVaultConfig( sandbox: EnvironmentOverride(ingress: "tnt-xyz.sandbox.verygoodproxy.com", path: "/caas/v2/paymentmethods"), live: EnvironmentOverride(ingress: "tnt-xyz.live.verygoodproxy.com", path: "/caas/v2/paymentmethods") ) let vault = try CoinmeVault.create(environment: .sandbox, config: runtime) ``` When `config` is `nil`, the baked-in defaults are used: a blank ingress means the VGS default host, and the path defaults to `/caas/v2/paymentmethods`. ## Lifecycle Call `vault.dispose()` when the form is gone. It stops state observation and unsubscribes all VGS text fields to release resources. After disposal the instance must not be reused — create a new one. In SwiftUI, tie disposal to the view's lifetime (e.g. call `dispose()` from `.onDisappear` on the view model that owns the vault). --- --- title: "Coinme Vault SDK for Android Native" url: "https://platformdocs.coinme.com/#/docs/coinme-vault-sdk-for-android-native" markdown: "https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-android-native.md" summary: "The Coinme Vault SDK is a Kotlin library for Android that wraps the VGS Collect Android SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process." surface: "caas" platform: "android" package: "CoinmeVault · Kotlin" version: "1.0.0" source: "https://docs.coinme.com/docs/coinme-vault-sdk-for-android-native" updated: "2026-10-28" --- # Coinme Vault SDK for Android Native ## Introduction The Coinme Vault SDK is a Kotlin library for Android that wraps the VGS Collect Android SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process. It is the Android counterpart to the `vault-sdk-react-native` SDK, and the public API mirrors the React Native SDK for cross-platform parity. **Security model:** Secure field values (card number, CVV, …) never leave the VGS field views and never enter your application process. The SDK exposes only validity and non-sensitive metadata (`isValid`, `isEmpty`, `cardBrand`, `last4`, …). Submission goes directly from the VGS views to the vault. **Error messages never contain field values (PII).** ### What Does It Collect? The SDK collects only the payment data you explicitly bind into its fields, and submits it directly to the Coinme vault. The supported fields are: - **Card data** — card number, expiry month/year, CVV - **Cardholder name** - **Billing address** — address lines, city, ZIP code Your application never receives the raw field values — it sees only validity state and non-sensitive metadata such as the detected card brand and the last four digits. ## SDK Requirements | Requirement | Value | | --- | --- | | Minimum Android version | Android 7.0 (Nougat) — API Level 24 | | Compile SDK | 37 | | JVM target | 17 | | VGS Collect | 1.11.0 (re-exported as `api`) | The SDK ships **no Compose dependency** — VGS fields are Android Views, so "Compose support" is just `AndroidView` interop (see Integration path 3 below). ## Installation **IMPORTANT:** Ask your Coinme integration contact to obtain your Cloudsmith entitlement token. The library publishes to Cloudsmith (`coinme/coinme-sdk-mobile`) as `com.coinme:vault-sdk-android`. ### Step 1: Add the Repository In `settings.gradle.kts`: `settings.gradle.kts` ```kotlin dependencyResolutionManagement { repositories { google() mavenCentral() maven { url = uri("https://maven.cloudsmith.io/coinme/coinme-sdk-mobile/") // Cloudsmith entitlement token, supplied by Coinme. credentials(HttpHeaderCredentials::class) { name = "Authorization" value = "Bearer ${providers.gradleProperty("CLOUDSMITH_ENTITLEMENT_TOKEN").get()}" } authentication { create("header") } } } } ``` ### Step 2: Add the Dependency In `app/build.gradle.kts`: `app/build.grqadle.kts` ```kotlin dependencies { implementation("com.coinme:vault-sdk-android:1.0.0") } ``` Because the SDK declares `api(vgscollect)`, the VGS field-view classes (`VGSCardNumberEditText`, …) are available on your compile classpath without an extra dependency. ## Configuration The account-scoped **vault ID** is baked into the library as a `BuildConfig` field, read from an **environment variable with a** `local.properties` **fallback**. Copy `local.properties.example` to `local.properties` and fill in the values, or set the env vars in CI: ``` COINME_VAULT_ID_SANDBOX=your_sandbox_vault_id COINME_VAULT_ID_LIVE=your_live_vault_id ``` The env var names match the React Native SDK's `gen-vault-config`, so one `.env` serves both repos. **Ingress hostnames and the submit path are not configured here** — they are public, stable values baked into the SDK per environment: sandbox → `secure.payments-stage.coinme.com`, live → `secure.payments.coinme.com`, path → `/caas/v2/paymentmethods`. They can be overridden per-runtime (but never the vault ID) via `RuntimeVaultConfig` — see Runtime configuration overrides below. ## Quick Start ```kotlin import com.coinme.vaultsdk.CoinmeVault import com.coinme.vaultsdk.CoinmeVaultEnvironment import com.coinme.vaultsdk.core.VaultSubmitOptions import com.coinme.vaultsdk.widget.CoinmeFields // 1. Create the vault for an environment. val vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX) // 2. Build pre-named VGS fields and bind them. val cardNumber = CoinmeFields.cardNumber(context) val expiry = CoinmeFields.expiry(context) val cvc = CoinmeFields.cvc(context) val holder = CoinmeFields.cardHolder(context) vault.bind(cardNumber, expiry, cvc, holder) // add the views to your layout too // 3. Observe form validity (drive your submit button's enabled state). lifecycleScope.launch { vault.formState.collect { state -> submitButton.isEnabled = state.isValid } } // 4. Submit. Throws CoinmeVaultException on failure. lifecycleScope.launch { val result = vault.submit( VaultSubmitOptions( extraData = mapOf("accountId" to "abc", "country" to "US"), headers = mapOf("Authorization" to "Bearer $transientAuthToken"), ) ) println("status=${result.status} body=${result.body}") } // 5. Release VGS resources when done (e.g. onDestroy / onDispose). vault.dispose() ``` ## Core Concepts | Type | Role | | --- | --- | | `CoinmeVault` | Entry point. Wraps a `VGSCollect` collector, tracks form validity, performs submits. | | `CoinmeVaultEnvironment` | `SANDBOX` or `LIVE`. Selects the baked-in vault ID / ingress / path. | | `CoinmeFields` | Factory that builds VGS field views with the correct Coinme field name pre-set. | | `VaultFieldNames` | The dot-notation field-name constants VGS deep-merges into nested JSON. | | `VaultSubmitOptions` | Per-submit `extraData` (non-secure JSON) and `headers`. | | `VaultSubmitResult` | `status: Int`, `body: String?`, `data: JsonElement?` on success. | | `CoinmeVaultException` | Sealed error hierarchy thrown by `submit`. | The collector is exposed as `vault.collector: VGSCollect` — the documented escape hatch for advanced VGS usage not covered by the wrapper. You rarely need it. ### Creating a vault ```kotlin val vault = CoinmeVault.create( context = context, environment = CoinmeVaultEnvironment.SANDBOX, config = null, // optional RuntimeVaultConfig; see "Runtime configuration overrides" ) ``` `create` resolves the vault configuration, builds the underlying `VGSCollect`, and registers a single form-state listener. Create **one** `CoinmeVault` per form/screen and `dispose()` it when the screen goes away. ### Field names Android VGS has no `{{ placeholder }}` templating. Field names are **dot-notation keys** that VGS deep-merges with `setCustomData` into nested submit JSON. They are defined in `VaultFieldNames`: | Constant | Value | Notes | | --- | --- | --- | | `CARD_NUMBER` | `card.cardNumber` | | | `EXP_MONTH` | `card.month` | child of the expiry serializer | | `EXP_YEAR` | `card.year` | child of the expiry serializer | | `CVC` | `card.cvv` | | | `CARD_HOLDER` | `cardHolderName` | | | `ADDRESS1` | `billingAddress.addressLine1` | | | `ADDRESS2` | `billingAddress.addressLine2` | | | `CITY` | `billingAddress.city` | | | `ZIPCODE` | `billingAddress.zipCode` | | | `EXPIRY` | `card` | parent field name for `ExpirationDateEditText` | Unlike the RN SDK's template allowlist, **Android submits every bound field.** Bind only the fields you intend to send. The expiry field is the special case: its own field name is `card` and it uses a `VGSExpDateSeparateSerializer("card.month", "card.year")` so a single input writes two JSON keys. `CoinmeFields.expiry()` configures this for you. ## Integration Paths The same `CoinmeVault` instance supports three ways of constructing fields. ### 1.`CoinmeFields`factory (Kotlin / Java) **Recommended for native (View-based and Compose) usage.** VGS field views are `final` and cannot be subclassed, so the SDK does not ship `CoinmeXField` subclasses. Instead, `CoinmeFields` is a factory that builds a stock VGS view with the correct default field name already applied. ```kotlin import com.coinme.vaultsdk.widget.CoinmeFields val cardNumber = CoinmeFields.cardNumber(context) // VGSCardNumberEditText, name "card.cardNumber" val expiry = CoinmeFields.expiry(context) // ExpirationDateEditText, separate-date serializer val cvc = CoinmeFields.cvc(context) // CardVerificationCodeEditText, name "card.cvv" val holder = CoinmeFields.cardHolder(context) // PersonNameEditText, name "cardHolderName" val custom = CoinmeFields.text(context, "myField") // VGSEditText, arbitrary field name container.addView(cardNumber) container.addView(expiry) vault.bind(cardNumber, expiry, cvc, holder) ``` `cardNumber`, `cvc`, and `cardHolder` accept an optional `fieldName` override; `expiry` does not (its serializer is fixed); `text` requires the field name. ### 2. XML layouts Declare the VGS view classes directly in your layout and set `app:fieldName` to the matching `VaultFieldNames` value. ```markup ``` ```markup val vault = CoinmeVault.create(this, CoinmeVaultEnvironment.SANDBOX) vault.bind( findViewById(R.id.card_number), findViewById(R.id.cvc), findViewById(R.id.card_holder), ) ``` **Expiry in XML:** the separate-date serializer can't be expressed in XML attributes. Either build the expiry field via `CoinmeFields.expiry(context)` in code and add it to your layout, or set the serializer on the `ExpirationDateEditText` after `findViewById`: ```markup findViewById(R.id.expiry).setSerializer( VGSExpDateSeparateSerializer(VaultFieldNames.EXP_MONTH, VaultFieldNames.EXP_YEAR) ) ``` ### 3. Jetpack Compose (AndroidView) The SDK ships **no Compose artifact**. VGS fields are Android Views, so Compose support is just `AndroidView` interop. Copy these two reference helpers into your app (the canonical copy lives in the demo at `app/.../screens/VaultFields.kt`): ```kotlin @Composable fun rememberCoinmeVault( environment: CoinmeVaultEnvironment, config: RuntimeVaultConfig? = null, ): CoinmeVault { val context = LocalContext.current val vault = remember(environment, config) { CoinmeVault.create(context, environment, config) } DisposableEffect(vault) { onDispose { vault.dispose() } } return vault } /** Builds a Coinme widget, binds it to [vault], and renders it via AndroidView. */ @Composable fun VaultField( vault: CoinmeVault, modifier: Modifier = Modifier, factory: (Context) -> T, configure: (T.() -> Unit)? = null, ) { AndroidView( modifier = modifier, factory = { context -> factory(context).apply { configure?.invoke(this) vault.bind(this) } }, ) } ``` ## Observing Form State ```kotlin val formState: StateFlow // whole-form snapshot fun fieldState(fieldName: String): Flow // one field data class VaultFormState( val fields: Map = emptyMap(), val isValid: Boolean = false, // true only when every bound field is valid ) data class VaultFieldState( val fieldName: String, val isValid: Boolean, val isEmpty: Boolean, val isFocused: Boolean, val contentLength: Int, val cardBrand: String? = null, // card-number field only val last4: String? = null, // card-number field only ) ``` Binding seeds each field as invalid (RN parity) — a freshly bound form reports `isValid == false` until VGS emits its first state change. **No secure values are ever present in these flows** — only validity and the non-sensitive metadata shown above. ## Submitting > **Never use your partner access token with the Vault SDK.** > > The `Authorization` header must be `Bearer ` 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. ```kotlin suspend fun submit(options: VaultSubmitOptions = VaultSubmitOptions()): VaultSubmitResult data class VaultSubmitOptions( val extraData: Map = emptyMap(), // deep-merged into the submit JSON alongside fields val headers: Map = emptyMap(), // merged with trace headers; caller wins on conflict ) ``` What `submit()` does, in order: 1. **Pre-validates** from the tracker; if the form is invalid it throws `CoinmeVaultException.Validation`**before any network call**. 2. Generates per-request `X-B3-TraceId` / `X-B3-SpanId` and merges your `headers` on top (your headers win on conflict). 3. Builds a `POST` to the configured submit path with `extraData` as custom data, then calls VGS **synchronously** on `Dispatchers.IO`. 4. Maps the response — including the **CAAS envelope** case where VGS returns HTTP 200 with an `errorResponse` payload (thrown as `CoinmeVaultException.Caas`, not returned as success). **Only one submit may be in flight at a time** — a concurrent call throws `CoinmeVaultException.SubmitInProgress`. ### Callback variant (Java / non-coroutine) ```kotlin vault.submit(VaultSubmitOptions()) { result: Result -> result.onSuccess { /* ... */ }.onFailure { /* ... */ } } ``` ### Payment-method convenience ```kotlin import com.coinme.vaultsdk.models.PaymentMethodInput import com.coinme.vaultsdk.models.PaymentProcessAssociation import com.coinme.vaultsdk.core.submitPaymentMethod val result = vault.submitPaymentMethod( PaymentMethodInput( accountId = "abc", providerId = "prov-1", webSessionId = "sess-1", paymentProcessAssociation = PaymentProcessAssociation.BUY, // optional billingAddress* fields default to ""/omitted; country defaults to "US" ), headers = mapOf("Authorization" to "Bearer $transientAuthToken"), ) ``` It builds the CAAS `extraData` shape (`accountId`, `stagingProviderId`, `webSessionId`, `paymentProcessAssociation`, `billingAddress`) and delegates to `submit`. ## Error Handling `submit` throws `CoinmeVaultException`, a sealed hierarchy: ```kotlin try { vault.submit(options) } catch (e: CoinmeVaultException.Validation) { e.fields.forEach { (name, reasons) -> showFieldError(name, reasons) } } catch (e: CoinmeVaultException.Caas) { when (e.submitCardError) { SubmitCardError.CARD_IN_USE_BY_ANOTHER_USER -> showCardInUse() SubmitCardError.MAX_NUMBER_OF_CARDS_REACHED -> showTooManyCards() else -> showGenericError() } } catch (e: CoinmeVaultException.Server) { showServerError(e.status) } catch (e: CoinmeVaultException) { showGenericError() } ``` | Subclass | Meaning | Key fields | | --- | --- | --- | | `Validation` | Form invalid; thrown before any network call. | `fields: Map>` (`"required"` / `"invalid"` per field) | | `Network` | Connectivity / timeout. | `cause` | | `Server` | HTTP 4xx/5xx from the vault. | `status: Int`, `body: String?` | | `Caas` | HTTP 200 with a CAAS error envelope. | `status: Int`, `errorResponse: CaasErrorResponse`, `submitCardError: SubmitCardError?` | | `Unknown` | Anything else. | `cause` | | `SubmitInProgress` | A submit is already in flight. | — | `SubmitCardError` (in `com.coinme.vaultsdk.enums`) maps known CAAS error codes to enum constants and is ported from the Coinme app to ease migration. `e.submitCardError` resolves the first known error code to a `SubmitCardError` (or `null` if the code is unrecognized); the raw code remains available via `e.errorResponse.firstKnownError()` (a `CaasErrorData` with `errorCode`, `message`). **Exception messages never contain field values (PII).** Log them freely. ## Runtime Configuration Overrides The vault ID is **always** baked in at build time and cannot be overridden. The ingress host and submit path **can** be overridden at runtime by passing a `RuntimeVaultConfig` to `create`: ```kotlin val runtime = RuntimeVaultConfig( sandbox = EnvironmentOverride(ingress = "tnt-xyz.sandbox.verygoodproxy.com", path = "/caas/v2/paymentmethods"), live = EnvironmentOverride(ingress = "tnt-xyz.live.verygoodproxy.com", path = "/caas/v2/paymentmethods"), ) val vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX, runtime) ``` When a `RuntimeVaultConfig` is supplied, both environments' `ingress` and `path` must be non-blank (an `IllegalArgumentException` is thrown otherwise). When it is `null`, the baked-in `BuildConfig` values are used. ## Lifecycle Call `vault.dispose()` when the form is gone (Activity/Fragment `onDestroy`, or Compose `onDispose` via `rememberCoinmeVault`). It cancels the internal coroutine scope and calls `collector.onDestroy()` to release VGS resources. After disposal the instance must not be reused — create a new one. ## Java Interop `CoinmeVault.create`, `CoinmeFields.*`, and the callback-based `submit` are annotated `@JvmStatic` / `@JvmOverloads`, so they read naturally from Java: ```kotlin CoinmeVault vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX); VGSCardNumberEditText cardNumber = CoinmeFields.cardNumber(context); vault.bind(cardNumber); vault.submit(new VaultSubmitOptions(), result -> { if (result.isSuccess()) { /* result.getOrNull() */ } return Unit.INSTANCE; }); ``` For Flow-based state observation from Java, collect via the standard `kotlinx-coroutines` Java interop or expose a wrapper on the Kotlin side. --- --- title: "Coinme Vault SDK for React Native" url: "https://platformdocs.coinme.com/#/docs/coinme-vault-sdk-for-react-native" markdown: "https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-react-native.md" summary: "`@coinme-security/vault-sdk-react-native` is a typed JavaScript wrapper that lets your React" surface: "caas" platform: "reactNative" 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"} source: "https://docs.coinme.com/docs/coinme-vault-sdk-for-react-native" updated: "2026-10-28" --- # 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= 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 ( ``` ```typescript import { CoinmeVaultError, createCoinmeVault, } from '@coinme-security/vault-sdk-js'; // createCoinmeVault is async - it loads VGS Collect.js from the VGS CDN. const vault = await createCoinmeVault({ environment: 'sandbox' }); // Mount secure fields into the container elements. // These calls return raw VGS field instances. vault.createCardNumberField('#pan', { placeholder: 'Card number' }); vault.createExpiryField('#expiry', { placeholder: 'MM / YYYY' }); vault.createCvcField('#cvc', { placeholder: 'CVC' }); // Subscribe to form state changes to gate the submit button. const button = document.querySelector('#submit')!; vault.subscribe(() => { button.disabled = !vault.getFormState().isValid; }); button.addEventListener('click', async () => { try { const result = await vault.submit(); // result.status is the HTTP status; result.data is the parsed response body. // Raw field values are never available here. console.log('OK', result.status); } catch (error) { if (error instanceof CoinmeVaultError) { console.log(`${error.kind}: ${error.message}`); } } }); // Call when the hosting view is removed. // vault.dispose(); ``` Three things to notice: - `createCoinmeVault`**is async.** It loads VGS Collect.js from the CDN before resolving. Wait for it before calling any field factories. - **Field containers must exist first.** The factory calls (`createCardNumberField`, etc.) mount iframes into DOM elements. Create the vault and call the factories only after your containers are in the DOM. - `vault.subscribe` notifies on every field-state change and returns an unsubscribe function. Poll `vault.getFormState().isValid` inside it to keep your submit button in sync. > **It's Easy!** > > For the vast majority of deployments, all you need to pass to `createCoinmeVault` 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. ## Framework setup The SDK is framework-agnostic, but a few integration patterns are worth following per framework to get lifecycle and cleanup right. ### React Vault creation is async and browser-only, so it belongs in a `useEffect`. Secure fields must be created after their container `
`s mount, and deleted in cleanup to prevent React 18 StrictMode's double-invocation from stacking duplicate iframes: ```tsx import { createCoinmeVault, type CoinmeVault, } from '@coinme-security/vault-sdk-js'; import { useEffect, useState, useSyncExternalStore } from 'react'; /** Creates the vault on mount (browser-only), disposes on unmount. */ const useCoinmeVault = () => { const [vault, setVault] = useState(); useEffect(() => { let disposed = false; let created: CoinmeVault | undefined; createCoinmeVault({ environment: 'sandbox' }).then((v) => { if (disposed) return v.dispose(); created = v; setVault(v); }); return () => { disposed = true; created?.dispose(); }; }, []); return vault; }; /** Reactive form state - snapshot is referentially stable, no memo needed. */ const useVaultFormState = (vault: CoinmeVault) => useSyncExternalStore(vault.subscribe, vault.getFormState); ``` Create fields in a separate effect, with cleanup: ```tsx useEffect(() => { if (!vault) return; const fields = [ vault.createCardNumberField('#pan'), vault.createExpiryField('#expiry'), vault.createCvcField('#cvc'), ]; // Delete fields in cleanup so React StrictMode's double-run doesn't stack iframes. return () => fields.forEach((field) => field.delete()); }, [vault]); ``` A full working example is in `examples/react` in the SDK repository. ### Vue 3 Same lifecycle, Vue idioms - create the vault in `onMounted`, dispose in `onUnmounted`, mirror form state into a `ref`: ```markup ``` ### SSR frameworks (Next.js, Nuxt, SvelteKit, …) Importing the package on the server is safe - the module has no load-time browser side effects. **Creating a vault is browser-only** - `createCoinmeVault` rejects if there is no `window`. Keep these points in mind: - Create the vault inside client-side lifecycle code: `useEffect` (Next.js), `onMounted` (Nuxt), `onMount` (SvelteKit). The React and Vue examples above already do this. - In Next.js App Router, add the `'use client'` directive to your form component. - Don't render secure-field containers on the server expecting them to be filled - fields mount only after the client-side vault exists. - Add CSP headers in your framework's config (e.g. `next.config.js` headers) - see [CSP](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#content-security-policy). ## Secure fields Five factory methods are available on the vault instance. Each one mounts a cross-origin iframe into the container matched by the CSS selector you pass, and returns the raw VGS field instance. All VGS field methods - `mask()`, `replacePattern()`, `update()`, `reset()`, `delete()`, `focus()`, `on()`/`off()`, and the `promise` readiness signal - work exactly as [VGS documents them](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/reference-documentation). | Factory | Purpose | | --- | --- | | `createCardNumberField` | Card number with Luhn validation, brand detection, and masking. Defaults to name `pan`. Add `showCardIcon: true` for a brand icon inside the field. | | `createExpiryField` | Expiry date in `MM / YYYY` format, with a built-in not-in-the-past check. On submit, a serializer splits it into `exp_month` and a 4-digit `exp_year`. Defaults to name `expiry`. | | `createCvcField` | Security code; adapts to the detected card brand (3 or 4 digits). Defaults to name `cvc`. | | `createCardHolderField` | Cardholder name - for flows that need it collected securely. (The payment-method helper accepts name literals instead.) Defaults to name `cardholder`. | | `createTextField` | Generic secure field for other sensitive values: billing address lines, city, ZIP, SSN, etc. `name` is required. Choose field behaviour with `type` (`'text'`, `'ssn'`, `'zip-code'`, `'password'`, `'textarea'`, and others). | Every factory passes all options through to VGS unfiltered, so new VGS options work without an SDK update. > **Expiry year width.** > > The payment-method endpoint requires a 4-digit year. The expiry factory defaults to `MM / YYYY` accordingly. Override `yearLength: 2` only if your endpoint accepts 2-digit years. ### Field names `VAULT_FIELD_NAMES` provides the conventional field-name constants - `pan`, `cvc`, `expiry`, `address1`, `address2`, `city`, `zipcode`. The card factories default to them. Pass them explicitly on `createTextField` so collected values line up with the payment-method request template: ```typescript import { VAULT_FIELD_NAMES } from '@coinme-security/vault-sdk-js'; vault.createTextField('#address1', { name: VAULT_FIELD_NAMES.address1, validations: ['required'], }); ``` ## Styling Because secure fields render inside VGS iframes, ordinary page CSS cannot reach inside them. There are two complementary approaches. ### Inside the field: the `css` option Style the field's text input with the `css` option. It supports regular CSS properties, pseudo-classes and pseudo-elements, nested `&` selectors, the VGS field state classes, web fonts via `@font-face`, and media queries: ```typescript vault.createCardNumberField('#pan', { css: { 'font-family': '"Inter", system-ui, sans-serif', 'font-size': '16px', color: '#1b1d1f', '&::placeholder': { color: '#9aa0a6' }, '&:focus': { color: '#000' }, // VGS state classes: valid, invalid, empty, dirty, touched '&.invalid.touched': { color: '#c5221f' }, '@font-face': { 'font-family': 'Inter', src: 'url("https://example.com/inter.woff2")', }, }, }); ``` > Media queries inside `css` are computed against the **iframe's** width, not the page's. ### Around the field: the `classes` option Your host container `
` receives state classes from VGS that you can target with regular page CSS. Map them to your own class names with the `classes` option: ```typescript vault.createCvcField('#cvc', { classes: { invalid: 'field-invalid', focused: 'field-focused' }, }); ``` ```css .field-focused { border-color: #1a73e8; } .field-invalid { border-color: #c5221f; } ``` VGS's default class names (if you don't override them) are `vgs-collect-container__invalid`, `__focused`, `__empty`, `__dirty`, and `__touched`. ### Masks and input shaping Text-like fields expose VGS's chainable formatting API on the returned instance: ```typescript const ssn = vault.createTextField('#ssn', { name: 'ssn', type: 'ssn' }); ssn.mask('999-99-9999', '*'); // 9: digit, a: letter, *: alphanumeric ssn.replacePattern('/[^0-9-]+/g'); // strip anything else as the user types ``` For the full option-by-option reference, see the VGS [customization](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/customization) and [formatting](https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/formatting) pages - everything there is reachable through the factories' options and returned instances. ## Form state and validity `vault.getFormState()` returns `{ isValid, fields }`. `vault.subscribe(listener)` fires on every field-state change and returns an unsubscribe function. ```typescript const unsubscribe = vault.subscribe(() => { const { isValid, fields } = vault.getFormState(); submitButton.disabled = !isValid; panHint.hidden = !(fields.pan?.isDirty && !fields.pan?.isValid); }); ``` `isValid` is `true` only when at least one field exists and every field reports valid. A validation-free `createTextField` (e.g. an optional apartment line) counts as valid while empty and won't block submission; fields with `validations` stay invalid until they pass. Each entry in `fields` carries non-sensitive state and metadata: `isValid`, `isDirty`, `isEmpty`, `isFocused`, `isTouched`, `errorMessages`, and for card fields `last4`, `bin`, and `cardType`. Raw field values are never included. The form state snapshot is referentially stable between changes, so it plugs directly into React's `useSyncExternalStore`: ```typescript useSyncExternalStore(vault.subscribe, () => vault.getFormState()) ``` > Plain (non-PCI) inputs collected with a regular `` - such as a billing `state` > > dropdown - are not part of the vault. Gate your submit on `isValid` **and** your own checks for any plain inputs. ## Submitting a payment method > **Never use your partner access token with the Vault SDK.** > > The `Authorization` header must be `Bearer ` 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 browser. 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 by their `VAULT_FIELD_NAMES`; the remaining values (`customerId`, billing first/last name, etc.) are plain literals you supply. ```typescript import { submitPaymentMethod, VAULT_FIELD_NAMES, } from '@coinme-security/vault-sdk-js'; // Mount secure fields using VAULT_FIELD_NAMES so values line up with the request template. vault.createCardNumberField('#pan'); vault.createExpiryField('#expiry'); vault.createCvcField('#cvc'); vault.createTextField('#address1', { name: VAULT_FIELD_NAMES.address1, validations: ['required'] }); vault.createTextField('#address2', { name: VAULT_FIELD_NAMES.address2 }); vault.createTextField('#city', { name: VAULT_FIELD_NAMES.city, validations: ['required'] }); vault.createTextField('#zipcode', { name: VAULT_FIELD_NAMES.zipcode, validations: ['required', 'postal_code/us'] }); 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: 'WA', // plain literal, e.g. from a regular ` values are validated separately - they don't register with the vault and don't count toward `isValid`. **Submits succeed but hit the wrong host** - an unregistered ingress CNAME silently falls back to the default vault URL rather than failing. Verify the ingress value in sandbox before using it in production - see the [ingress caveat](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#custom-ingress-or-submit-path). **React StrictMode shows doubled fields in development** - create fields in a `useEffect` and delete them in its cleanup function. See the [React setup](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md#react) section and `examples/react` in the SDK repository. ## 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`. ## 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 ` 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 resolves without an error, 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 Javascript](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-javascript.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md) --- --- name: coinme-vault-ios description: "Add card capture to an iOS app with the Coinme Vault SDK: add the package, configure the vault, build and bind the secure fields, observe form state, 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 an iOS or Swift app." metadata: surface: "caas" package: "CoinmeVault · Swift" version: "1.0.1" --- # Coinme Vault SDK on iOS ## When to use this skill The human wants an iOS 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 An iOS 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 same device fingerprint the Risk SDK gets. ## 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 `, 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`. The submit also needs a Risk SDK session id, fetched right before the submit because a session tag lives 30 minutes. 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 `. | | `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 => { 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 iOS Native ## Introduction The Coinme Vault SDK for iOS is a Swift SDK that wraps the VGS Collect iOS SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process. It is the iOS counterpart to the Coinme Vault SDK for Android, and the public API mirrors the Android SDK for cross-platform parity. **Security model:** Secure field values (card number, CVV, …) never leave the VGS field views and never enter your application process. The SDK exposes only validity and non-sensitive metadata (`isValid`, `isEmpty`, `cardBrand`, `last4`, …). Submission goes directly from the VGS views to the vault. **Error messages never contain field values (PII).** ### What Does It Collect? The SDK collects only the payment data you explicitly bind into its fields, and submits it directly to the Coinme vault. The supported fields are: - **Card data** — card number, expiry month/year, CVV - **Cardholder name** - **Billing address** — address lines, city, ZIP code Your application never receives the raw field values — it sees only validity state and non-sensitive metadata such as the detected card brand and the last four digits. ## SDK Requirements | Requirement | Value | | --- | --- | | Minimum iOS | 15.0 | | Swift | 5.9 | | VGS Collect | `~> 1.18` (resolves transitively) | VGS Collect is resolved as a normal dependency, so the VGS field-view classes (`VGSCardTextField`, …) are available on your compile classpath without an extra dependency. ## Installation **IMPORTANT:** Ask your Coinme integration contact to obtain your Cloudsmith **entitlement token**. The library publishes to Cloudsmith (`coinme/coinme-sdk-mobile`) for both Swift Package Manager and CocoaPods. ### Swift Package Manager One-time registry login (uses your Cloudsmith entitlement token): ``` swift package-registry set https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/swift package-registry login https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ \ --username YOUR_USERNAME --password YOUR_ENTITLEMENT_TOKEN ``` Then add the dependency: `Package.swift` ```swift // Package.swift .package(id: "coinme.CoinmeVaultSDK", from: "1.0.0") ``` The SDK pulls VGSCollectSDK via SCM. To resolve it through the registry instead, run: ``` swift package --replace-scm-with-registry resolve ``` To add the package in Xcode: **File → Add Package Dependencies**, add the registry URL above, then search for `coinme.CoinmeVaultSDK`. ### CocoaPods `Podfile` ```swift # Podfile — supplied by Coinme source 'https://dl.cloudsmith.io//coinme/coinme-sdk-mobile/cocoapods/index.git' source 'https://cdn.cocoapods.org/' target 'YourApp' do use_frameworks! pod 'CoinmeVaultSDK', '~> 1.0' # pulls VGSCollectSDK transitively end ``` ## Configuration The account-scoped **vault ID** is baked into the library per environment at publish time and is never passed by callers. For local development, copy `local.properties.example` to `local.properties` and fill in: ``` COINME_VAULT_ID_SANDBOX=your_sandbox_vault_id COINME_VAULT_ID_LIVE=your_live_vault_id ``` **Ingress hostnames and the submit path are not configured here** — they are public, stable values baked into the SDK per environment (`config/VaultDefaults.swift`): sandbox → `secure.payments-stage.coinme.com`, live → `secure.payments.coinme.com`, path → `/caas/v2/paymentmethods`. They can be overridden per-runtime (but never the vault ID) via `RuntimeVaultConfig` — see Runtime configuration overrides below. ## Quick Start ```swift import CoinmeVaultSDK // 1. Create the vault for an environment. let vault = try CoinmeVault.create(environment: .sandbox) // 2. Build pre-named VGS fields against the vault's collector and bind them. let cardNumber = CoinmeFields.cardNumber(collector: vault.collector) let expiry = CoinmeFields.expiry(collector: vault.collector) let cvc = CoinmeFields.cvc(collector: vault.collector) let holder = CoinmeFields.cardHolder(collector: vault.collector) vault.bind(cardNumber, expiry, cvc, holder) // add the views to your view hierarchy too // 3. Observe form validity (drive your submit button's enabled state). vault.onFormStateChange = { state in submitButton.isEnabled = state.isValid } // 4. Submit. Throws CoinmeVaultError on failure. let result = try await vault.submit( VaultSubmitOptions( extraData: ["accountId": "abc", "country": "US"], headers: ["X-Request-Source": "ios"] ) ) print("status=\(result.status) body=\(result.body ?? "")") // 5. Release VGS resources when done (e.g. on screen teardown). vault.dispose() ``` `CoinmeVault` is `@MainActor` — create it, build fields, bind, and observe state on the main actor. ## Core Concepts | Type | Role | | --- | --- | | `CoinmeVault` | Entry point. Wraps a `VGSCollect` collector, tracks form validity, performs submits. `@MainActor`. | | `CoinmeVaultEnvironment` | `.sandbox` or `.live`. Selects the baked-in vault ID / ingress / path. | | `CoinmeFields` | Factory that builds VGS text fields with the correct Coinme field name and VGS type pre-set. | | `VaultFieldNames` | The dot-notation field-name constants VGS deep-merges into nested submit JSON. | | `VaultSubmitOptions` | Per-submit `extraData` (non-secure JSON) and `headers`. | | `VaultSubmitResult` | `status: Int`, `body: String?`, `data: Any?` on success. | | `CoinmeVaultError` | Error enum thrown by `submit`. | The collector is exposed as `vault.collector: VGSCollect` — both the input to the `CoinmeFields` factories and the documented escape hatch for advanced VGS usage not covered by the wrapper. ### Creating a vault ```swift let vault = try CoinmeVault.create( environment: .sandbox, config: nil // optional RuntimeVaultConfig; see "Runtime configuration overrides" ) ``` `create()` resolves the vault configuration, builds the underlying `VGSCollect`, and registers a single form-state listener. It throws `CoinmeVaultError.invalidConfiguration` if the vault ID is not baked in or an override is incomplete. Create **one** `CoinmeVault` per form/screen and `dispose()` it when the screen goes away. ### Field names Field names are **dot-notation keys** that VGS deep-merges into nested submit JSON (`card.cardNumber` → `{"card":{"cardNumber":...}}`). They are defined in `VaultFieldNames`: | Constant | Value | Notes | | --- | --- | --- | | `cardNumber` | `card.cardNumber` | | | `expMonth` | `card.month` | child of the expiry serializer | | `expYear` | `card.year` | child of the expiry serializer | | `cvc` | `card.cvv` | | | `cardHolder` | `cardHolderName` | | | `address1` | `billingAddress.addressLine1` | | | `address2` | `billingAddress.addressLine2` | | | `city` | `billingAddress.city` | | | `zipCode` | `billingAddress.zipCode` | | | `expiry` | `card` | parent field name for the expiry field | **The SDK submits every bound field.** Bind only the fields you intend to send. The expiry field is the special case: its own field name is `card` and it uses a `VGSExpDateSeparateSerializer(monthFieldName: "card.month", yearFieldName: "card.year")` so a single input writes two JSON keys. The year is forced to 4 digits on output. `CoinmeFields.expiry()` configures all of this for you. ## Building Fields VGS field views subscribe to their collector the moment their `configuration` is set, so each `CoinmeFields` factory takes the owning vault's collector: ```swift import CoinmeVaultSDK let cardNumber = CoinmeFields.cardNumber(collector: vault.collector) // VGSCardTextField, "card.cardNumber" let expiry = CoinmeFields.expiry(collector: vault.collector) // VGSExpDateTextField, separate-date serializer let cvc = CoinmeFields.cvc(collector: vault.collector) // VGSCVCTextField, "card.cvv" let holder = CoinmeFields.cardHolder(collector: vault.collector) // VGSTextField, "cardHolderName" let custom = CoinmeFields.text(collector: vault.collector, fieldName: "billingAddress.city") ``` `cardNumber`, `cvc`, and `cardHolder` accept an optional `fieldName` override; `expiry` does not (its serializer is fixed); `text` requires the field name. Returned views are ordinary `VGSTextField` subclasses — style them, add them to your view hierarchy, and `vault.bind(...)` them. ### Rendering VGS fields VGS fields are UIKit `UIView`s. In UIKit, add them to your view hierarchy directly. In SwiftUI, wrap each field in a `UIViewRepresentable` (the demo's `VGSFieldView` is the canonical reference): ```swift struct VGSFieldView: UIViewRepresentable { let field: VGSTextField func makeUIView(context: Context) -> VGSTextField { field } func updateUIView(_ uiView: VGSTextField, context: Context) {} } ``` Build the fields once (e.g. in your view model) so they aren't recreated on every SwiftUI render, then render each with `VGSFieldView(field: cardNumber)`. See the `Example/` app for a full working form. ### Binding fields ```swift func bind(_ fields: VGSTextField...) // required fields func bindOptional(_ fields: VGSTextField...) // optional fields ``` `bind` registers each field name with the form-validity tracker. **Registration seeds the field as invalid** — a freshly bound form reports `isValid == false` until VGS emits its first state change. Bind a field once. VGS emits no initial state, so an untouched field's validity is unknown until the user edits it. Use `bindOptional` for fields that may be left empty (e.g. `billingAddress.addressLine2`): they seed as **valid**, so an untouched form can still reach `isValid == true`. Fields with no configured `fieldName` are skipped by `bind`/`bindOptional` — always build them via `CoinmeFields` first. ## Observing Form State ```swift var formState: VaultFormState // current snapshot var formStatePublisher: AnyPublisher // Combine stream var onFormStateChange: ((VaultFormState) -> Void)? // non-Combine callback func fieldState(_ fieldName: String) -> VaultFieldState? // one field public struct VaultFormState: Equatable { public let fields: [String: VaultFieldState] public let isValid: Bool // true only when every bound field is valid } public struct VaultFieldState: Equatable { public let fieldName: String public let isValid: Bool public let isEmpty: Bool public let isFocused: Bool public let contentLength: Int public let cardBrand: String? // card-number field only public let last4: String? // card-number field only } ``` Typical use — drive the submit button: ```swift // Callback style: vault.onFormStateChange = { state in submitButton.isEnabled = state.isValid } // Combine style: vault.formStatePublisher .map(\.isValid) .receive(on: RunLoop.main) .assign(to: \.isEnabled, on: submitButton) .store(in: &cancellables) // React to a single field, e.g. show the detected card brand: let brand = vault.fieldState(VaultFieldNames.cardNumber)?.cardBrand ``` **No secure values are ever present in these snapshots** — only validity and the non-sensitive metadata shown above. ## Submitting the Data > **Never use your partner access token with the Vault SDK.** > > The `Authorization` header must be `Bearer ` 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. ```swift @discardableResult func submit(_ options: VaultSubmitOptions = VaultSubmitOptions()) async throws -> VaultSubmitResult public struct VaultSubmitOptions { public let extraData: [String: Any] // deep-merged into the submit JSON alongside fields public let headers: [String: String] // merged with trace headers; caller wins on conflict } ``` What `submit` does, in order: 1. **Pre-validates** from the tracker; if the form is invalid it throws `CoinmeVaultError.validation(fields:)` **before any network call**. 2. Generates per-request `X-B3-TraceId` / `X-B3-SpanId` and merges your `headers` on top (your headers win on conflict). 3. POSTs to the configured submit path with `extraData` as custom data via VGS. 4. Maps the response — including the **CAAS envelope** case where VGS returns HTTP 200 with a nested `errorResponse` payload (thrown as `CoinmeVaultError.caas`, not returned as success). **Only one submit may be in flight at a time** — a concurrent call throws `CoinmeVaultError.submitInProgress`. ### Completion-handler variant ```swift vault.submit(VaultSubmitOptions()) { (result: Result) in switch result { case .success(let r): // ... case .failure(let e): // ... } } ``` ### Payment-method convenience A higher-level helper for the CAAS payment-method endpoint: ```swift let result = try await vault.submitPaymentMethod( PaymentMethodInput( accountId: "abc", providerId: "prov-1", webSessionId: "sess-1", paymentProcessAssociation: .buy, // optional billingAddress* fields default to ""/omitted; country defaults to "US" billingAddressFirstName: "Jane", billingAddressLastName: "Doe", billingAddressState: "WA" ), headers: ["Authorization": "Bearer \(transientAuthToken)"] ) ``` It builds the CAAS `extraData` shape (`accountId`, `stagingProviderId`, `webSessionId`, `paymentProcessAssociation`, `billingAddress`) and delegates to `submit`. The card fields themselves are supplied securely by the bound VGS fields. ## Error Handling `submit` only ever throws `CoinmeVaultError` ```swift do { try await vault.submit(options) } catch let error as CoinmeVaultError { switch error { case .validation(let fields): fields.forEach { name, reasons in showFieldError(name, reasons) } case .caas: switch error.submitCardError { case .cardInUseByAnotherUser: showCardInUse() case .maxNumberOfCardsReached: showTooManyCards() default: showGenericError() } case .server(let status, _): showServerError(status) default: showGenericError() } } ``` | Case | Meaning | Associated values | | --- | --- | --- | | `.validation(fields:)` | Form invalid; thrown before any network call. | `[String: [String]]` — `["required"]` / `["invalid"]` per field | | `.network(underlying:)` | Connectivity / transport failure. | `Error?` | | `.server(status:body:)` | HTTP 4xx/5xx with no recognizable CAAS envelope. | `Int`, `String?` | | `.caas(status:errorResponse:)` | CAAS error envelope (4xx/5xx, or nested in an HTTP 200). | `Int`, `CaasErrorResponse` | | `.submitInProgress` | A submit is already in flight. | — | | `.invalidConfiguration(_:)` | Missing/invalid configuration (e.g. an unbaked vault ID). | `String` | | `.unknown(underlying:)` | Anything else. | `Error?` | `error.submitCardError` is a convenience on `CoinmeVaultError` that resolves the first known CAAS error code to a `SubmitCardError` (or `nil` if unrecognized). The raw code remains available via the associated `CaasErrorResponse` (`errorResponse.firstKnownError()?.errorCode`). `SubmitCardError` maps known CAAS card-submit codes to enum constants and is ported from the Coinme app to ease migration. **Error cases never carry a field value (PCI).** Log them freely. ## Runtime Configuration Overrides The vault ID is **always** baked in at publish time and cannot be overridden. The ingress host and submit path **can** be overridden at runtime by passing a `RuntimeVaultConfig` to `create`: ```swift let runtime = RuntimeVaultConfig( sandbox: EnvironmentOverride(ingress: "tnt-xyz.sandbox.verygoodproxy.com", path: "/caas/v2/paymentmethods"), live: EnvironmentOverride(ingress: "tnt-xyz.live.verygoodproxy.com", path: "/caas/v2/paymentmethods") ) let vault = try CoinmeVault.create(environment: .sandbox, config: runtime) ``` When `config` is `nil`, the baked-in defaults are used: a blank ingress means the VGS default host, and the path defaults to `/caas/v2/paymentmethods`. ## Lifecycle Call `vault.dispose()` when the form is gone. It stops state observation and unsubscribes all VGS text fields to release resources. After disposal the instance must not be reused — create a new one. In SwiftUI, tie disposal to the view's lifetime (e.g. call `dispose()` from `.onDisappear` on the view model that owns the vault). ## 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 ` 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 iOS Native](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-ios-native.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md) --- --- name: coinme-vault-android description: "Add card capture to an Android app with the Coinme Vault SDK: add the repository and dependency, configure the vault, build the fields in Kotlin, XML or Compose, observe form state, 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 an Android or Kotlin app." metadata: surface: "caas" package: "CoinmeVault · Kotlin" version: "1.0.0" --- # Coinme Vault SDK on Android ## When to use this skill The human wants an Android 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 An Android 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 same device fingerprint the Risk SDK gets. ## 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 `, 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`. The submit also needs a Risk SDK session id, fetched right before the submit because a session tag lives 30 minutes. 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 `. | | `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 => { 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 Android Native ## Introduction The Coinme Vault SDK is a Kotlin library for Android that wraps the VGS Collect Android SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process. It is the Android counterpart to the `vault-sdk-react-native` SDK, and the public API mirrors the React Native SDK for cross-platform parity. **Security model:** Secure field values (card number, CVV, …) never leave the VGS field views and never enter your application process. The SDK exposes only validity and non-sensitive metadata (`isValid`, `isEmpty`, `cardBrand`, `last4`, …). Submission goes directly from the VGS views to the vault. **Error messages never contain field values (PII).** ### What Does It Collect? The SDK collects only the payment data you explicitly bind into its fields, and submits it directly to the Coinme vault. The supported fields are: - **Card data** — card number, expiry month/year, CVV - **Cardholder name** - **Billing address** — address lines, city, ZIP code Your application never receives the raw field values — it sees only validity state and non-sensitive metadata such as the detected card brand and the last four digits. ## SDK Requirements | Requirement | Value | | --- | --- | | Minimum Android version | Android 7.0 (Nougat) — API Level 24 | | Compile SDK | 37 | | JVM target | 17 | | VGS Collect | 1.11.0 (re-exported as `api`) | The SDK ships **no Compose dependency** — VGS fields are Android Views, so "Compose support" is just `AndroidView` interop (see Integration path 3 below). ## Installation **IMPORTANT:** Ask your Coinme integration contact to obtain your Cloudsmith entitlement token. The library publishes to Cloudsmith (`coinme/coinme-sdk-mobile`) as `com.coinme:vault-sdk-android`. ### Step 1: Add the Repository In `settings.gradle.kts`: `settings.gradle.kts` ```kotlin dependencyResolutionManagement { repositories { google() mavenCentral() maven { url = uri("https://maven.cloudsmith.io/coinme/coinme-sdk-mobile/") // Cloudsmith entitlement token, supplied by Coinme. credentials(HttpHeaderCredentials::class) { name = "Authorization" value = "Bearer ${providers.gradleProperty("CLOUDSMITH_ENTITLEMENT_TOKEN").get()}" } authentication { create("header") } } } } ``` ### Step 2: Add the Dependency In `app/build.gradle.kts`: `app/build.grqadle.kts` ```kotlin dependencies { implementation("com.coinme:vault-sdk-android:1.0.0") } ``` Because the SDK declares `api(vgscollect)`, the VGS field-view classes (`VGSCardNumberEditText`, …) are available on your compile classpath without an extra dependency. ## Configuration The account-scoped **vault ID** is baked into the library as a `BuildConfig` field, read from an **environment variable with a** `local.properties` **fallback**. Copy `local.properties.example` to `local.properties` and fill in the values, or set the env vars in CI: ``` COINME_VAULT_ID_SANDBOX=your_sandbox_vault_id COINME_VAULT_ID_LIVE=your_live_vault_id ``` The env var names match the React Native SDK's `gen-vault-config`, so one `.env` serves both repos. **Ingress hostnames and the submit path are not configured here** — they are public, stable values baked into the SDK per environment: sandbox → `secure.payments-stage.coinme.com`, live → `secure.payments.coinme.com`, path → `/caas/v2/paymentmethods`. They can be overridden per-runtime (but never the vault ID) via `RuntimeVaultConfig` — see Runtime configuration overrides below. ## Quick Start ```kotlin import com.coinme.vaultsdk.CoinmeVault import com.coinme.vaultsdk.CoinmeVaultEnvironment import com.coinme.vaultsdk.core.VaultSubmitOptions import com.coinme.vaultsdk.widget.CoinmeFields // 1. Create the vault for an environment. val vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX) // 2. Build pre-named VGS fields and bind them. val cardNumber = CoinmeFields.cardNumber(context) val expiry = CoinmeFields.expiry(context) val cvc = CoinmeFields.cvc(context) val holder = CoinmeFields.cardHolder(context) vault.bind(cardNumber, expiry, cvc, holder) // add the views to your layout too // 3. Observe form validity (drive your submit button's enabled state). lifecycleScope.launch { vault.formState.collect { state -> submitButton.isEnabled = state.isValid } } // 4. Submit. Throws CoinmeVaultException on failure. lifecycleScope.launch { val result = vault.submit( VaultSubmitOptions( extraData = mapOf("accountId" to "abc", "country" to "US"), headers = mapOf("Authorization" to "Bearer $transientAuthToken"), ) ) println("status=${result.status} body=${result.body}") } // 5. Release VGS resources when done (e.g. onDestroy / onDispose). vault.dispose() ``` ## Core Concepts | Type | Role | | --- | --- | | `CoinmeVault` | Entry point. Wraps a `VGSCollect` collector, tracks form validity, performs submits. | | `CoinmeVaultEnvironment` | `SANDBOX` or `LIVE`. Selects the baked-in vault ID / ingress / path. | | `CoinmeFields` | Factory that builds VGS field views with the correct Coinme field name pre-set. | | `VaultFieldNames` | The dot-notation field-name constants VGS deep-merges into nested JSON. | | `VaultSubmitOptions` | Per-submit `extraData` (non-secure JSON) and `headers`. | | `VaultSubmitResult` | `status: Int`, `body: String?`, `data: JsonElement?` on success. | | `CoinmeVaultException` | Sealed error hierarchy thrown by `submit`. | The collector is exposed as `vault.collector: VGSCollect` — the documented escape hatch for advanced VGS usage not covered by the wrapper. You rarely need it. ### Creating a vault ```kotlin val vault = CoinmeVault.create( context = context, environment = CoinmeVaultEnvironment.SANDBOX, config = null, // optional RuntimeVaultConfig; see "Runtime configuration overrides" ) ``` `create` resolves the vault configuration, builds the underlying `VGSCollect`, and registers a single form-state listener. Create **one** `CoinmeVault` per form/screen and `dispose()` it when the screen goes away. ### Field names Android VGS has no `{{ placeholder }}` templating. Field names are **dot-notation keys** that VGS deep-merges with `setCustomData` into nested submit JSON. They are defined in `VaultFieldNames`: | Constant | Value | Notes | | --- | --- | --- | | `CARD_NUMBER` | `card.cardNumber` | | | `EXP_MONTH` | `card.month` | child of the expiry serializer | | `EXP_YEAR` | `card.year` | child of the expiry serializer | | `CVC` | `card.cvv` | | | `CARD_HOLDER` | `cardHolderName` | | | `ADDRESS1` | `billingAddress.addressLine1` | | | `ADDRESS2` | `billingAddress.addressLine2` | | | `CITY` | `billingAddress.city` | | | `ZIPCODE` | `billingAddress.zipCode` | | | `EXPIRY` | `card` | parent field name for `ExpirationDateEditText` | Unlike the RN SDK's template allowlist, **Android submits every bound field.** Bind only the fields you intend to send. The expiry field is the special case: its own field name is `card` and it uses a `VGSExpDateSeparateSerializer("card.month", "card.year")` so a single input writes two JSON keys. `CoinmeFields.expiry()` configures this for you. ## Integration Paths The same `CoinmeVault` instance supports three ways of constructing fields. ### 1.`CoinmeFields`factory (Kotlin / Java) **Recommended for native (View-based and Compose) usage.** VGS field views are `final` and cannot be subclassed, so the SDK does not ship `CoinmeXField` subclasses. Instead, `CoinmeFields` is a factory that builds a stock VGS view with the correct default field name already applied. ```kotlin import com.coinme.vaultsdk.widget.CoinmeFields val cardNumber = CoinmeFields.cardNumber(context) // VGSCardNumberEditText, name "card.cardNumber" val expiry = CoinmeFields.expiry(context) // ExpirationDateEditText, separate-date serializer val cvc = CoinmeFields.cvc(context) // CardVerificationCodeEditText, name "card.cvv" val holder = CoinmeFields.cardHolder(context) // PersonNameEditText, name "cardHolderName" val custom = CoinmeFields.text(context, "myField") // VGSEditText, arbitrary field name container.addView(cardNumber) container.addView(expiry) vault.bind(cardNumber, expiry, cvc, holder) ``` `cardNumber`, `cvc`, and `cardHolder` accept an optional `fieldName` override; `expiry` does not (its serializer is fixed); `text` requires the field name. ### 2. XML layouts Declare the VGS view classes directly in your layout and set `app:fieldName` to the matching `VaultFieldNames` value. ```markup ``` ```markup val vault = CoinmeVault.create(this, CoinmeVaultEnvironment.SANDBOX) vault.bind( findViewById(R.id.card_number), findViewById(R.id.cvc), findViewById(R.id.card_holder), ) ``` **Expiry in XML:** the separate-date serializer can't be expressed in XML attributes. Either build the expiry field via `CoinmeFields.expiry(context)` in code and add it to your layout, or set the serializer on the `ExpirationDateEditText` after `findViewById`: ```markup findViewById(R.id.expiry).setSerializer( VGSExpDateSeparateSerializer(VaultFieldNames.EXP_MONTH, VaultFieldNames.EXP_YEAR) ) ``` ### 3. Jetpack Compose (AndroidView) The SDK ships **no Compose artifact**. VGS fields are Android Views, so Compose support is just `AndroidView` interop. Copy these two reference helpers into your app (the canonical copy lives in the demo at `app/.../screens/VaultFields.kt`): ```kotlin @Composable fun rememberCoinmeVault( environment: CoinmeVaultEnvironment, config: RuntimeVaultConfig? = null, ): CoinmeVault { val context = LocalContext.current val vault = remember(environment, config) { CoinmeVault.create(context, environment, config) } DisposableEffect(vault) { onDispose { vault.dispose() } } return vault } /** Builds a Coinme widget, binds it to [vault], and renders it via AndroidView. */ @Composable fun VaultField( vault: CoinmeVault, modifier: Modifier = Modifier, factory: (Context) -> T, configure: (T.() -> Unit)? = null, ) { AndroidView( modifier = modifier, factory = { context -> factory(context).apply { configure?.invoke(this) vault.bind(this) } }, ) } ``` ## Observing Form State ```kotlin val formState: StateFlow // whole-form snapshot fun fieldState(fieldName: String): Flow // one field data class VaultFormState( val fields: Map = emptyMap(), val isValid: Boolean = false, // true only when every bound field is valid ) data class VaultFieldState( val fieldName: String, val isValid: Boolean, val isEmpty: Boolean, val isFocused: Boolean, val contentLength: Int, val cardBrand: String? = null, // card-number field only val last4: String? = null, // card-number field only ) ``` Binding seeds each field as invalid (RN parity) — a freshly bound form reports `isValid == false` until VGS emits its first state change. **No secure values are ever present in these flows** — only validity and the non-sensitive metadata shown above. ## Submitting > **Never use your partner access token with the Vault SDK.** > > The `Authorization` header must be `Bearer ` 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. ```kotlin suspend fun submit(options: VaultSubmitOptions = VaultSubmitOptions()): VaultSubmitResult data class VaultSubmitOptions( val extraData: Map = emptyMap(), // deep-merged into the submit JSON alongside fields val headers: Map = emptyMap(), // merged with trace headers; caller wins on conflict ) ``` What `submit()` does, in order: 1. **Pre-validates** from the tracker; if the form is invalid it throws `CoinmeVaultException.Validation`**before any network call**. 2. Generates per-request `X-B3-TraceId` / `X-B3-SpanId` and merges your `headers` on top (your headers win on conflict). 3. Builds a `POST` to the configured submit path with `extraData` as custom data, then calls VGS **synchronously** on `Dispatchers.IO`. 4. Maps the response — including the **CAAS envelope** case where VGS returns HTTP 200 with an `errorResponse` payload (thrown as `CoinmeVaultException.Caas`, not returned as success). **Only one submit may be in flight at a time** — a concurrent call throws `CoinmeVaultException.SubmitInProgress`. ### Callback variant (Java / non-coroutine) ```kotlin vault.submit(VaultSubmitOptions()) { result: Result -> result.onSuccess { /* ... */ }.onFailure { /* ... */ } } ``` ### Payment-method convenience ```kotlin import com.coinme.vaultsdk.models.PaymentMethodInput import com.coinme.vaultsdk.models.PaymentProcessAssociation import com.coinme.vaultsdk.core.submitPaymentMethod val result = vault.submitPaymentMethod( PaymentMethodInput( accountId = "abc", providerId = "prov-1", webSessionId = "sess-1", paymentProcessAssociation = PaymentProcessAssociation.BUY, // optional billingAddress* fields default to ""/omitted; country defaults to "US" ), headers = mapOf("Authorization" to "Bearer $transientAuthToken"), ) ``` It builds the CAAS `extraData` shape (`accountId`, `stagingProviderId`, `webSessionId`, `paymentProcessAssociation`, `billingAddress`) and delegates to `submit`. ## Error Handling `submit` throws `CoinmeVaultException`, a sealed hierarchy: ```kotlin try { vault.submit(options) } catch (e: CoinmeVaultException.Validation) { e.fields.forEach { (name, reasons) -> showFieldError(name, reasons) } } catch (e: CoinmeVaultException.Caas) { when (e.submitCardError) { SubmitCardError.CARD_IN_USE_BY_ANOTHER_USER -> showCardInUse() SubmitCardError.MAX_NUMBER_OF_CARDS_REACHED -> showTooManyCards() else -> showGenericError() } } catch (e: CoinmeVaultException.Server) { showServerError(e.status) } catch (e: CoinmeVaultException) { showGenericError() } ``` | Subclass | Meaning | Key fields | | --- | --- | --- | | `Validation` | Form invalid; thrown before any network call. | `fields: Map>` (`"required"` / `"invalid"` per field) | | `Network` | Connectivity / timeout. | `cause` | | `Server` | HTTP 4xx/5xx from the vault. | `status: Int`, `body: String?` | | `Caas` | HTTP 200 with a CAAS error envelope. | `status: Int`, `errorResponse: CaasErrorResponse`, `submitCardError: SubmitCardError?` | | `Unknown` | Anything else. | `cause` | | `SubmitInProgress` | A submit is already in flight. | — | `SubmitCardError` (in `com.coinme.vaultsdk.enums`) maps known CAAS error codes to enum constants and is ported from the Coinme app to ease migration. `e.submitCardError` resolves the first known error code to a `SubmitCardError` (or `null` if the code is unrecognized); the raw code remains available via `e.errorResponse.firstKnownError()` (a `CaasErrorData` with `errorCode`, `message`). **Exception messages never contain field values (PII).** Log them freely. ## Runtime Configuration Overrides The vault ID is **always** baked in at build time and cannot be overridden. The ingress host and submit path **can** be overridden at runtime by passing a `RuntimeVaultConfig` to `create`: ```kotlin val runtime = RuntimeVaultConfig( sandbox = EnvironmentOverride(ingress = "tnt-xyz.sandbox.verygoodproxy.com", path = "/caas/v2/paymentmethods"), live = EnvironmentOverride(ingress = "tnt-xyz.live.verygoodproxy.com", path = "/caas/v2/paymentmethods"), ) val vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX, runtime) ``` When a `RuntimeVaultConfig` is supplied, both environments' `ingress` and `path` must be non-blank (an `IllegalArgumentException` is thrown otherwise). When it is `null`, the baked-in `BuildConfig` values are used. ## Lifecycle Call `vault.dispose()` when the form is gone (Activity/Fragment `onDestroy`, or Compose `onDispose` via `rememberCoinmeVault`). It cancels the internal coroutine scope and calls `collector.onDestroy()` to release VGS resources. After disposal the instance must not be reused — create a new one. ## Java Interop `CoinmeVault.create`, `CoinmeFields.*`, and the callback-based `submit` are annotated `@JvmStatic` / `@JvmOverloads`, so they read naturally from Java: ```kotlin CoinmeVault vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX); VGSCardNumberEditText cardNumber = CoinmeFields.cardNumber(context); vault.bind(cardNumber); vault.submit(new VaultSubmitOptions(), result -> { if (result.isSuccess()) { /* result.getOrNull() */ } return Unit.INSTANCE; }); ``` For Flow-based state observation from Java, collect via the standard `kotlinx-coroutines` Java interop or expose a wrapper on the Kotlin side. ## 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 ` 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 Android Native](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-android-native.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md) --- --- 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 `, 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 `. | | `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 => { 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= 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 (