# Risk SDK: Coinme App Platform > Every page and skill for the Risk SDK, in one file: the SDK documents and guides, and the Agent Skills that integrate it. The Risk 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 Risk SDK" url: "https://platformdocs.coinme.com/#/docs/coinme-risk-sdk" markdown: "https://platformdocs.coinme.com/docs/coinme-risk-sdk.md" summary: "The Coinme Risk SDKs integrate your application with the Coinme Risk Engine — a system that aggregates device, location, connection, and behavioral data to assess the risk of users and transactions in real time. This allows Coinme to detect fraud signals such as automation, VPN usage, and suspicious interaction patterns before processing a transaction." surface: "caas" source: "https://docs.coinme.com/docs/coinme-risk-sdk" updated: "2026-06-11" --- # Coinme Risk SDK The Coinme Risk SDKs integrate your application with the Coinme Risk Engine — a system that aggregates device, location, connection, and behavioral data to assess the risk of users and transactions in real time. This allows Coinme to detect fraud signals such as automation, VPN usage, and suspicious interaction patterns before processing a transaction. **SDKs are available for three platforms:** - **Web** — an NPM package for browser-based applications - **iOS** — for native Apple platform integrations - **Android** — for native Android integrations > **Required for Transactional Services** > > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme Risk Engine SDK. --- --- title: "Coinme Risk SDK for Web" url: "https://platformdocs.coinme.com/#/docs/using-the-coinme-risk-sdk-for-web" markdown: "https://platformdocs.coinme.com/docs/using-the-coinme-risk-sdk-for-web.md" summary: "The Coinme Risk Engine SDK is a library, distributed as an NPM package, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions." surface: "caas" platform: "web" package: "@coinme-security/risk-sdk-js" version: "1.2.0" source: "https://docs.coinme.com/docs/using-the-coinme-risk-sdk-for-web" updated: "2026-10-28" --- # Coinme Risk SDK for Web ## Introduction The Coinme Risk Engine SDK is a library, distributed as an NPM package, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions. > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme risk engine SDK. **What is it?** The Coinme risk engine aggregates data about user behavior for your application. It collects: - Device data such as the type of device, browser, etc. - Location data such as where the user is connecting from. - Connection data such as if the user is using a proxy or VPN, etc. - Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, etc. This data is used to determine the relative riskiness of the user / transaction. > **Why is Risk Tagging Important?** > > Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**. > > As an example, if the risk engine determines that the user is connected with an unknown browser type, via a VPN or proxy, and that interactions with elements of your app are happening much faster than would be normal for a human, then the engine may determine automation is at play and may **rank the transaction as high risk**. ## How to Use the SDK The Coinme Risk Engine SDK is an NPM package. You may install it as follows. > **This package is not public** > > You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact. ### What You'll Need to Get Started Before integrating the SDK, you will need the following credentials from your Coinme integration contact: | Credential | Required For | Notes | | --- | --- | --- | | NPM auth token | Installing the package | Required to access the private npm registry | | `clientId` | `setupCoinmeRiskEngine` | Environment-specific — you will need one for development and one for production | | `x-partner-id` | `getSessionTag` | Passed via `additionalHeaders` | | `x-ramp-id` | `getSessionTag` (Ramp partners only) | Passed via `additionalHeaders` | ### Installation #### For SDK Consumers To install the package, configure your `.npmrc` or `.yarnrc` (or equivalent) to include your authentication token: ``` @coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/ //npm.coinme.com/coinme-security-wrapper/:_authToken= always-auth=true ``` > Replace `` with your provided token. Then install via: NPM: ``` npm install @coinme-security/risk-sdk-js ``` Yarn: ``` yarn add @coinme-security/risk-sdk-js ``` PNPM: ``` pnpm add @coinme-security/risk-sdk-js ``` #### Quick Start You can use the Coinme Risk Engine SDK in your project by following the steps below. #### Setup the Coinme Risk Engine The setup function initializes the Risk Engine and applies all necessary configurations. ```typescript import { setupCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; setupCoinmeRiskEngine({ mode: "test", clientId: "client-id", }) .catch((error) => { console.error("Error setting up Risk Engine:", error); }) .finally(() => { console.log("Risk Engine setup complete!"); }); ``` > setupCoinmeRiskEngine is **not sufficient** in and of itself to use the risk SDK; this call is to be made when your app starts up in order to initialize the risk engine. There are other conditions which will require you to update additional parameters dynamically during the user session, such as when a user starts a high-risk action like a transaction, after a user has onboarded and now there is a customerId, etc. In these cases, use updateCoinmeRiskEngine. > **Key Takeaway: When should I use this?** > > You should call setupCoinmeRiskEngine when your application instantiates. > You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals. #### Get Current Configuration To check which risk parameters are applied, use: ```typescript import { getCoinmeRiskEngineConfig } from "@coinme-security/risk-sdk-js"; const config = getCoinmeRiskEngineConfig(); console.log(config); ``` > The Risk Engine configuration is only available after setup completes. #### Update Coinme Risk Engine Configuration While setup handles initial configuration, you can and should manually update specific parameters when needed. An example would be after a user has onboarded or logged in, as at this point you will have a customerId available to you; this helps the risk engine associate user behavior with your user. Another example is when you wish to update the flow identifier being sent to the risk engine. This is necessary so that when your user is entering a specific flow in your app such as **onboarding**, **linking a payment method**, or **transacting**, these special activities will be properly tagged; the risk engine examines user behavior in such flows closely. Therefore, you should tag these flows by updating the risk engine config by providing a flow identifier as seen below. > **What is a Flow Identifier?** > > A flow identifier is a string that acts as a tag to uniquely identify that data the risk engine is logging belongs to a contiguous and related flow of user actions. ```typescript import { updateCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "customer-123", flow: "customer-onboarding", }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Configuration updated"); }); ``` #### Flow Types There are certain flows that are universal, and which are important to the operation of the coinme risk engine. You can use a pre-defined FlowType in these cases to ensure you are properly tagging these flows. We export a FlowType enumeration that exposes these common flows which our risk engine can understand and use when making risk decisions. This enum is structured as follows: ```typescript export enum FlowType { Onboarding = 'customer-onboarding', CardTransaction = 'card-transaction', CardLinking = 'payment-method-linking', } ``` For maximum value, you should use the appropriate FlowType as the flow identifier when you are onboarding users, adding a payment method, or undertaking a transaction. > **Why Use Flow Identifiers?** > > Flow identifiers help **group multiple actions into a single session** so that risk is assessed based on **contextual user behavior**. Instead of analyzing each interaction separately, the risk engine can **detect patterns within a specific user journey**. > > For example: > > - If a user **enters payment details too quickly** after onboarding, this might indicate a **scripted attack** rather than a real person. > - If a user **switches IP addresses** midway through a transaction, it could indicate a **fraud attempt**. > - If a user **is interacting normally but suddenly switches to rapid inputs**, the system can **adapt its risk evaluation in real time**. > > By tagging actions with the correct FlowType, your application **provides the risk engine with the necessary context** to assess transactional legitimacy. > The Coinme risk engine requires the specific flow identifiers exposed by the risk SDK for any of these pre-defined flow types; **if you do not use the supported identifier, your users and transactions may not be appropriately scored and you will be at risk of high denial rates for your transactions.** **Usage Examples** Each example demonstrates when and how to use updateCoinmeRiskEngine with a **specific flow type**. **Example 1: Onboarding Flow** When a **new user signs up**, you must tag their session as **onboarding** so the risk engine can monitor suspicious activities. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "new-user-456", flow: FlowType.Onboarding, }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("User onboarding flow tracked."); }); ``` > **When to use?** > > Call this **when the user starts** the signup process. **Example 2: After Onboarding or Sign-in** After a **new user finishes signing up**, or after a **user has signed in**, you must update the risk engine with their userID so that data can now be associated with the user rather than a session. This allows the risk engine to aggregate and interpret data over time. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "user-456", }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("User ID now tracked."); }); ``` > **When to use?** > > Call this **right after the user completes** the signup **or login** process and the user’s permanent ID is known. **Example 3: Linking a New Card** If a user is adding a **new payment method**, this is a **high-risk action** that must be monitored. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "user-789", flow: FlowType.CardLinking, }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Card linking flow tracked."); }); ``` > **When to use?** > > Call this **when the user enters a process to add a payment method**. **Example 4: Processing a Card Transaction** When a user makes a **purchase or transaction**, you should explicitly tag it. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "user-123", flow: FlowType.CardTransaction, }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Card transaction flow tracked."); }); ``` > **When to use?** > > Call this **when the user enters a transactional flow** such as when they start a buy or sell transaction. > **Proper Use** > > The updateCoinmeRiskEngine function is designed to modify the risk engine's configuration after the initial setup. However, since both setupCoinmeRiskEngine and updateCoinmeRiskEngine are **asynchronous**, calling them sequentially without ensuring the setup is complete may cause the update function to override the initial configuration. #### How to Update Correctly - Ensure that setupCoinmeRiskEngine is completed before calling updateCoinmeRiskEngine. - If calling both on the first render (e.g., in a React setup), chain them properly using await or a state check. - Calling updateCoinmeRiskEngine before setupCoinmeRiskEngine finishes may lead to an incomplete or overridden configuration. **Example: Correct Usage - Await the Setup Before Updating** ```typescript async function initializeRiskEngine() { await setupCoinmeRiskEngine({ mode: "test", clientId: "client-id", }); console.log("Setup complete:", getCoinmeRiskEngineConfig()); await updateCoinmeRiskEngine({ customerId: "a@mail.com", flow: "flow-id", }); console.log("Update complete:", getCoinmeRiskEngineConfig()); } initializeRiskEngine(); ``` > **Why is this correct?** > > - Ensures setup completes before update can be called **Example: Incorrect Usage - Running Setup and Update in Parallel** ```typescript setupCoinmeRiskEngine({ mode: "test", clientId: "client-id", }); updateCoinmeRiskEngine({ customerId: "a@mail.com", flow: "flow-id", }); ``` > **Why is this wrong?** > > - updateCoinmeRiskEngine may execute before setupCoinmeRiskEngine completes. > - The update call might override important setup details. > - Leads to unpredictable behavior in the risk engine configuration. > **Key Takeaway: When should I use this?** > > You should call updateCoinmeRiskEngine: > > - After a user has onboarded or logged in, and you have a customerId > - By updating the risk engine with the customerId, you ensure that the risk engine can understand the user’s behavior over time, which leads to better risk modeling. > - When a user begins a flow that needs to be explicitly identified, such as onboarding, linking a payment method, or transacting. > - **These are key actions that should be tagged** with the correct flow identifier. #### Tagging Elements You can add Risk attributes to elements, components, or strings with the addCoinmeRiskTag function. The risk engine SDK automatically detects these tags and will flow behavioral metrics into the risk engine from any tagged entities automatically. **Examples:** - Returning a pre-tagged HTML element: ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; // Using a raw HTML string const elementAsString = addCoinmeRiskTag({ element: '
Hello, World!
', riskIdentifier: 'my-element', }); console.log(elementAsString); // Outputs a div with the risk data attribute 'my-element' added. ``` - Tagging an existing DOM element: ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; // Using an existing DOM element const divElement = document.createElement('div'); divElement.textContent = 'Hello, World!'; const taggedElement = addCoinmeRiskTag({ element: divElement, riskIdentifier: 'my-element' }); console.log(taggedElement.outerHTML); // Outputs a div with the risk data attribute 'my-element' added. ``` - Tagging a React-Like object: ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; // Tagging a React/Vue-style object const reactLikeObject = { type: 'div', props: { children: 'Hello, World!' }, }; const taggedObject = addCoinmeRiskTag({ element: reactLikeObject, riskIdentifier: 'my-element' }); console.log(taggedObject); // Outputs a react / vue style object with the risk data attribute 'my-element' added. ``` ## Core concepts #### Client ID Requirement > You must provide your clientId to use the SDK. If you don't have your clientId, ask your Coinme integration contact. The clientId uniquely identifies your partner integration within the Risk Engine. - It is provided by Coinme during onboarding. - Issued alongside your other Coinme credentials. It is not a secret and is meant to run in the browser; never put your partner access token or client secret in the browser alongside it. The Risk SDK itself takes no auth token. - Without it, the SDK will throw an error and refuse to initialize. #### Understanding sessionKey The sessionKey is a unique identifier for tracking a specific user session. > **In-Memory Only** > > The SDK does **not** persist session keys to localStorage, sessionStorage, or cookies. The session key is only held in memory. On page refresh, the key is lost. Don't persist a session tag to rehydrate it later: call `getSessionTag()` again right before the call that needs it. | Behavior | Outcome | | --- | --- | | Provide sessionKey in setup | Used & cached in memory | | Provide sessionKey in update | Overrides & caches in memory | | No sessionKey provided, stored key exists | Stored key reused automatically | | No sessionKey provided, no stored key | A stand-in key is cached; Coinme refuses it as a `webSessionId`, so read the session ID with `getWebSessionId()` (from 1.2.0) rather than `getCoinmeRiskEngineConfig().sessionKey`, which is deprecated for this | | Call getSessionTag() | webSessionID from server becomes the cached sessionKey | | Call clearSessionKey() | Clears the in-memory key; from 1.2.0 also the user identity (`customerId`, `flow`, `parentSessionKey`), keeping `partnerId` and the `enable*` flags | > When you call `getSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one. > **Why this matters** > > It is essential that the Risk Engine use the session tag returned by this endpoint once it is called. If you change the session key after this call is made, risk metrics will not be properly associated with your user. When you call `getSessionTag()`, you are signifying that you want Coinme to track your user's session — your own session ID is no longer relevant to this tracking. > **A session tag lives 30 minutes** > > Coinme keeps a session tag for 30 minutes from when it issued it, and using it doesn't extend that. You can't tell from the browser how long a tag has left, so don't store a `webSessionID` and reuse it on later page loads. > **Call `getSessionTag()` right before each add-payment-method call and each order.** > > Send the `webSessionID` it returns as `webSessionId` on that call. Calling `getSessionTag()` again while a tag is still live returns the same tag, so it doesn't start a new risk assessment session; once the tag is 30 minutes old it returns a new one. #### Clearing the sessionKey ```typescript import { clearSessionKey } from "@coinme-security/risk-sdk-js"; clearSessionKey(); ``` > This clears the **in-memory** session key. From 1.2.0 it clears the whole in-memory user identity: the session key plus the `customerId`, `flow` and `parentSessionKey` you passed to setup or update. App-level settings (`partnerId` and the `enable*` flags) are kept. The next setup or update starts from a clean identity, so nothing from the previous user is sent with the next user's session. It doesn't reset Sardine's own state; Sardine takes the next user's values through its normal update. Before 1.2.0 it clears only the session key. Use this in SPAs when: > > - Logging out users (without a page refresh) > - Switching accounts > - Resetting state for tests > > For non-SPA apps or full page reloads, the in-memory key is cleared automatically. If you stored a session key yourself (for example in `localStorage`), remove it as well; the SDK can't clear storage it doesn't own. #### Typical Session Flow Example ```typescript // Setup with auto-generated sessionKey await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'client-id', }); // Later — Update without providing sessionKey (uses stored one) await updateCoinmeRiskEngine({ flow: 'customer-onboarding', }); // On session end (e.g., logout in a SPA) clearSessionKey(); // Start new user/session await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'client-id', }); ``` #### Session Flow with getSessionTag (Recommended for Transactions) ```typescript import { setupCoinmeRiskEngine, getSessionTag, clearSessionKey, } from "@coinme-security/risk-sdk-js"; // Once, when your app starts await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'client-id', }); // Right before each add-payment-method call and each order: // a session tag lives 30 minutes, so fetch it every time async function freshWebSessionId(customerId) { const sessionData = await getSessionTag({ apiBaseUrl: 'https://api.example.com', // From 1.2.0 you may leave fingerprint out; earlier releases require it. customerId, additionalHeaders: { 'x-partner-id': 'your-partner-id', 'x-ramp-id': 'your-ramp-id', // only needed for ramp partners }, }); return sessionData.webSessionID; } const webSessionId = await freshWebSessionId('customer-123'); // Send webSessionId with the payment-method or order call. // On logout or account switch (SPA only; a page refresh clears it) clearSessionKey(); ``` ## API Reference The Coinme Risk Engine SDK provides the following functions for interacting with the Risk Engine. You can find detailed information about each function below or in the **API Reference** (internal to Coinme, not public)**.** ### setupCoinmeRiskEngine Sets up the Coinme Risk Engine with the provided options. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | mode | `'test' \| 'prod'` | ✅ | Operating environment | | clientId | string | ✅ | Partner-specific risk engine client ID | | partnerId | string | optional | Partner identifier | | customerId | string | optional | Customer identifier | | sessionKey | string | optional | Custom session tracking key | | flow | `string \| FlowType` | optional | Flow context | **Example:** ```typescript import { setupCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; setupCoinmeRiskEngine({ mode: "test", clientId: "client-id" }) .catch((error) => { console.error("Error setting up Risk Engine:", error); }) .finally(() => { console.log("Risk Engine setup complete!"); }); ``` ### getCoinmeRiskEngineConfig Retrieves the latest risk assessment settings applied to the current session. **Returns:** - `Partial`: An object containing the current Risk Engine configuration. All fields are optional and include: `partnerId`, `customerId`, `sessionKey`, `flow`, `parentSessionKey`, `enableBiometrics`, `enableGeoLocation`, `enablePortScanning`. - If no configuration has been set, it returns `{}`. **Example:** ```typescript import { getCoinmeRiskEngineConfig } from "@coinme-security/risk-sdk-js"; const config = getCoinmeRiskEngineConfig(); console.log(config); // Outputs: { partnerId: "...", sessionKey: "...", ... } ``` ### updateCoinmeRiskEngine Updates the Coinme risk assessment settings for the current session. This ensures that risk evaluations, such as device fingerprinting and geolocation tracking, are correctly applied. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | partnerId | string | optional | Partner identifier | | customerId | string | optional | Customer identifier | | sessionKey | string | optional | Override session key | | flow | `string \| FlowType` | optional | Flow context | | parentSessionKey | string | optional | Parent session key | | enableBiometrics | boolean | optional | Enable biometric signals | | enableGeoLocation | boolean | optional | Enable geo-location | | enablePortScanning | boolean | optional | Enable port scanning | **Example:** ```typescript import { updateCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "customer-123", flow: "onboarding", }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Configuration updated"); }); ``` ### addCoinmeRiskTag Enhances an element, component, or string representation of HTML by tagging the element with a risk tag. The risk engine SDK automatically detects these tags and will flow metrics into the risk engine from any tagged entities automatically. **Parameters:** | Prop | Type | Required | Description | | --- | --- | --- | --- | | element | `HTMLElement \| string \| object` | ✅ | Target element | | riskIdentifier | string | ✅ | Unique risk tag | **Returns:** - The same element with the risk tag applied. **Example:** ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; const element = addCoinmeRiskTag({ element: '
Hello, World!
', riskIdentifier: 'my-element', }); console.log(element); // Outputs a div tagged with the specified risk tag ``` ### withCoinmeRiskTag Creates a higher-order component that adds a risk tag to the wrapped component's output. The tagging behavior depends on what the component returns: - **String**: the string output is wrapped in a new `
` element. - **HTMLElement**: the `data-sardine-id` attribute is added directly to the element. - **Object with `props`** (React/Vue-style): `data-sardine-id` is added to the `props` object. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | Component | function | ✅ | The component function to wrap. | | id | string | ✅ | Unique risk tag to apply. | **Returns:** - A wrapped component with the risk tag attribute added to props or its equivalent. **Examples:** Wrapping a simple component: ```typescript import { withCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; const MyComponent = (props) => `
${props.text}
`; const TaggedComponent = withCoinmeRiskTag(MyComponent, 'my-element'); console.log(TaggedComponent({ text: 'Hello, world!' })); // The string output is wrapped in a new tagged div: //
Hello, world!
``` Wrapping a object-based component: ```typescript import { withCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; const MyObjectComponent = (props) => ({ type: 'div', props: { children: props.text }, }); const WrappedObject = withCoinmeRiskTag(MyObjectComponent, 'object-component'); console.log(WrappedObject({ text: 'Hello, world!' })); // Outputs an object tagged with the specified risk tag ``` ### getSessionTag Retrieves the Sardine session tag data from the public `/pub/get-session-tag` endpoint. This call obtains the session information needed for transaction risk assessment. Upon successful retrieval, the `webSessionID` is automatically used to update the Sardine configuration and is stored as the active session key for all subsequent SDK calls. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | apiBaseUrl | string | ✅ | The base URL of the API endpoint | | fingerprint | string | optional | The device fingerprint, sent as `x-device-fingerprint`. From 1.2.0, when omitted the SDK sends the one the other Coinme SDKs on this device share, or creates and shares one (see [Device fingerprint](https://platformdocs.coinme.com/docs/using-the-coinme-risk-sdk-for-web.md#device-fingerprint)); earlier releases require it | | customerId | string | ✅ | The customer ID, sent as the `accountId` query parameter | | additionalHeaders | `Record` | ✅ | Additional headers. Must include `x-partner-id` with the value provided by your Coinme integration contact. Example: `additionalHeaders: { 'X-Partner-ID': 'partner-123' }` | | timeout | number | optional | Request timeout in milliseconds (default: 10000) | **Returns:** - `Promise`: A promise that resolves with the session tag data containing `webSessionID` and `orgID`. The Sardine configuration is automatically updated with the `webSessionID` as the session key. **Example:** ```typescript import { getSessionTag } from "@coinme-security/risk-sdk-js"; const sessionData = await getSessionTag({ apiBaseUrl: 'https://api.example.com', // From 1.2.0 you may leave fingerprint out; earlier releases require it. customerId: 'customer-123', additionalHeaders: { 'x-partner-id': 'your-partner-id', }, }); // The webSessionID is automatically set in Sardine configuration const webSessionId = sessionData.webSessionID; const orgId = sessionData.orgID; ``` > **When to use?** > > Call this **right before each add-payment-method call and each order** to retrieve the session tag and automatically configure Sardine with the proper session key, then send the returned `webSessionID` as `webSessionId` on that call. A session tag lives 30 minutes from when it was issued, and using it doesn't extend that. > After calling `getSessionTag()`, the `webSessionID` becomes the stored session key. You do not need to pass it to subsequent `updateCoinmeRiskEngine()` calls — the SDK will automatically use it. If you need to override this behavior, explicitly pass a different `sessionKey` to `updateCoinmeRiskEngine()`. > **No token needed.** > > Don't pass an `authToken` or an `Authorization` header to `getSessionTag()`: this call authenticates with your `customerId` and `x-partner-id`. Never put your partner access token or client secret in the browser. ## 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`. ## Reading the session tag From 1.2.0, `getWebSessionId()` returns the session ID to send as `webSessionId`: the `webSessionID` from your last `getSessionTag()` call, or a session key you passed yourself. It returns `undefined` when there is none. Use it instead of `getCoinmeRiskEngineConfig().sessionKey`, which is deprecated for this: before a session tag exists, `sessionKey` holds a stand-in the SDK made up, which Coinme refuses. --- --- title: "Coinme Risk SDK for iOS Native Apps" url: "https://platformdocs.coinme.com/#/docs/risk-sdk-for-ios-native-apps" markdown: "https://platformdocs.coinme.com/docs/risk-sdk-for-ios-native-apps.md" summary: "The iOS Coinme Risk Engine SDK is a Swift library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions." surface: "caas" platform: "ios" package: "CoinmeRisk · Swift" version: "1.1.2" source: "https://docs.coinme.com/docs/risk-sdk-for-ios-native-apps" updated: "2026-10-28" --- # Coinme Risk SDK for iOS Native Apps ## Introduction The iOS Coinme Risk Engine SDK is a Swift library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions. > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme risk engine SDK. **What is it?** The Coinme risk engine aggregates data about user behavior for your application. It collects: - Device data such as the type of device, OS name and version, etc. - Location data such as where the user is connecting from. - Connection data such as if the user is using a proxy or VPN, etc. - Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, use of clipboard functions, etc. This data is used to determine the relative riskiness of the user / transaction. > **Why is Risk Tagging Important?** > > Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**. > > As an example, if the risk engine determines that the user location changes suddenly via a VPN to access a region restricted transaction type, then the engine may determine automation is at play and may **rank the transaction as high risk**. ## Implementing the iOS SDK > **This package is not public** > > You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact. ### What You'll Need to Get Started Before integrating the SDK, you will need the following credentials from your Coinme integration contact: | Credential | Required For | Notes | | --- | --- | --- | | Cloudsmith auth token | Accessing the library | Required to access the private library in Cloudsmith | | `clientId` | `RiskEngineSetupOptions` | Environment-specific — you will need one for development and one for production | | `partnerId` | `getPartnerSessionTag()` | Passed via `GetPartnerSessionTagOptions`, this is your Partner identifier needed for integration with Coinme APIs | > You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals. ### Installation #### Set Your Entitlement Token Create a `coinme.properties` file in your project root directory: ```properties COINME_TOKEN= ``` Replace `` with the token provided by your Coinme integration contact. Do not commit this file to version control. Important: Add `coinme.properties` to your `.gitignore` to keep your token secure: `coinmme.properties` ``` coinme.properties ``` #### Add the SDK Repository and Dependency to your project - CocoaPods Update your `Podfile`: `CocoaPods Setup` ```swift source 'https://github.com/CocoaPods/Specs.git' # Read token from properties file def read_token properties_file = File.join(File.dirname(__FILE__), 'coinme.properties') if File.exist?(properties_file) File.foreach(properties_file) do |line| key, value = line.split('=') return value.strip if key.strip == 'COINME_TOKEN' end end ENV['COINME_TOKEN'] || '' end token = read_token plugin 'cocoapods-cloudsmith', { 'source' => "https://packages.coinme.com/{COINME_TOKEN}/coinme-sdk-mobile/cocoapods/index.git" } target 'YourApp' do use_frameworks! pod 'CoinmeRiskSDK', '~> 1.1.2' end ``` `Environment Variable Setup` ```swift source 'https://github.com/CocoaPods/Specs.git' token = ENV['COINME_TOKEN'] || '' plugin 'cocoapods-cloudsmith', { 'source' => "https://packages.coinme.com/{COINME_TOKEN}/coinme-sdk-mobile/cocoapods/index.git" } target 'YourApp' do use_frameworks! pod 'CoinmeRiskSDK', '~> 1.1.2' end ``` If installing via an Environment Variable, you will also need to set the environment variable in your shell ```bash export COINME_TOKEN= ``` #### Add the SDK Repository and Dependency to your project - Swift Package Manager The SDK is also published to the Cloudsmith Swift Package Registry. Authenticate once with your entitlement token, then add the dependency. Configure and log in to the registry (one-time): ``` swift package-registry set https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ swift package-registry login https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ --token YOUR_ENTITLEMENT_TOKEN ``` Next, add the dependency in your `Package.swift`: ``` dependencies: [ .package(id: "coinme.CoinmeRiskSDK", from: "1.1.2"), ] ``` Or in Xcode: File > Add Package Dependencies… > Add from Registry and search for coinme.CoinmeRiskSDK. The package bundles MobileIntelligence (SardineSDK) — no extra dependency is required. ### App Store Requirements Before releasing your application with the Coinme Risk SDK, update your App Store Connect settings in your Apple developer portal. #### App Privacy — Data Collection In **App Store Connect > App Privacy**, declare the following: 1. **Data Collection:** Select **"Yes, we collect data from this app"** 2. **Location:** - Select **Coarse Location** and/or **Precise Location** (depending on your app settings) - Purpose: **App Functionality** - Reason: Required for fraud detection and prevention 3. **Identifiers — Device ID:** - Purpose: **App Functionality** - Check: **Yes, device ID is linked to user identity** #### Privacy Policy Update your App Store privacy policy to include the following disclosure: > **Required Privacy Policy Language** > > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, and location information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN or other location-spoofing tools. ### Required Permissions Add location permissions to your `Info.plist`: `Info.plist` ```swift ... NSLocationAlwaysAndWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. NSLocationWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. ``` This is a required permission for fraud detection and should be requested at runtime. Ensure your app handles the permission request appropriately for optimal risk assessment and to avoid issues from App Store Review. ### Implementation Privacy & Compliance Notice Important: If you use the Behavior Biometrics feature (enableBehaviourBiometrics = true), please ensure that your end users agree to your privacy policy before you begin collecting their Behavior Biometric data. This is required for compliance with privacy regulations. #### Configuration Options RiskEngineSetupOptions | Option | Type | Required | Description | | --- | --- | --- | --- | | `mode` | `Mode` | Yes | Used to point to environment `.Test` or `.Prod` | | `clientId` | `String` | Yes | Your environment-specific Client ID | | `partnerId` | `String?` | No | Partner Identifier | | `customerId` | `String?` | No | Customer/User's identifier | | `sessionKey` | `String?` | No | Session key (automatically generated if not provided) | | `flow` | `FlowType?` | No | Current User flow (Onboarding, CardTransaction, or CardLinking) | | `region` | `AppRegion` | No | Your app's region of service (`.default` (US), `.ca`, `.eu`, `.au`, `.in`) | | `enableBehaviourBiometrics` | `Bool` | No | Enabled behavior tracking (default: true) | | `enableClipboardTracking` | `Bool` | No | Enable clipboard tracking (default: false) | | `enableFieldTracking` | `Bool` | No | Enable automatic field tracking (default: true) | | `setCloudEntitlements` | `Bool` | No | Enable iCloud feature (default: false, requires additional setup) | #### FlowType Options - `FlowType.Onboarding` - New user registration flow - `FlowType.CardTransaction` - Payment/card transaction flow - `FlowType.CardLinking` - Adding payment methods flow #### sessionKey The `sessionKey` is a unique identifier for tracking a specific user session. Once a key is provided for the set up, it will be cached for the duration of the app's active session. If no value is provided, the key will be automatically generated. You will want to invoke `.getPartnerSessionTag()` to get an updated value that our backend will use to associate collected user data and risk score. Failure to call this and get the expected session key value may result in loss of data for accurate risk assessment. Call it right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that. Using `.updateCoinmeRiskEngine()` with a new key will override and update the cached value. To clear a `sessionKey`, you may call `.resetStoredSessionKey()` > When you call `getPartnerSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one. #### getPartnerSessionTag() Retrieve the session tag from the backend API. The resulting `webSessionID` is automatically used to update the `CoinmeRiskEngine` configuration. ```swift try await CoinmeRiskEngine.getPartnerSessionTag(options: GetPartnerSessionTagOptions) -> SessionTagData ``` Parameters of `GetPartnerSessionTagOptions`. The SDK sends them as request headers and a query parameter, to the host your `mode` selects: | Param | Type | Required | Description | | --- | --- | --- | --- | | `partnerId` | `String` | Yes | Your partner identifier, sent as the `partnerId` header | | `accountId` | `String` | Yes | The customer ID, sent as the `accountId` query parameter | | `fingerprint` | `String` | Yes | The device fingerprint, sent as the `X-Device-Fingerprint` header | | `rampId` | `String?` | No | Your Ramp ID, sent as the `X-ramp-id` header (Ramp partners only) | | `additionalHeaders` | `[String: String]` | No | Additional headers that may be included if needed by the backend | | `timeout` | `Int` | No | Request timeout in milliseconds (default: 10000) | #### Initialize the SDK Initialize the Risk Engine in your app's initialization: ```swift import CoinmeRiskSDK let options = RiskEngineSetupOptions( mode: .Prod, // Use .Test for testing clientId: "your-client-id", enableBehaviourBiometrics: true, enableFieldTracking: false // Set to false for manual tracking ) CoinmeRiskEngine.setupCoinmeRiskEngine(options: options) ``` #### Update the SDK You can update the configuration with flow, sessionKey and customerId options: ```swift CoinmeRiskEngine.updateCoinmeRiskEngine( RiskEngineUpdateOptions( sessionKey: "new-session-key", flow: .cardTransaction, customerId: "customer-id" ) ) ``` #### Submit Data Before Transactions Submits all collected behavioral and device date to the backend for risk assessment. Use callback version to ensure data is submitted before making subsequent API calls. ```swift CoinmeRiskEngine.submit( onSuccess: { // Data successfully submitted - safe to proceed with transaction API call processPayment() }, onError: { error in print("Risk SDK submission failed: \(error)") handleError(error) } ) ``` #### What it collects: - Sensor data (motion, orientation, pressure) - Behavioral biometrics (typing patterns, interaction timing) - Device context (clipboard activity, focus patterns) - Page/screen engagement metrics #### When to call: - Before payment/transaction API calls - Before critical actions (login, signup, money transfer) - After form completion or user interaction flow #### Other Utility Methods #### Get Current Config Returns the current runtime configuration. ```swift CoinmeRiskEngine.getCoinmeRiskEngineConfig() -> RiskEngineUpdateOptions ``` #### Reset Session Resets the stored session key. ```swift CoinmeRiskEngine.resetStoredSessionKey() ``` #### Reset SDK Clears the singleton instance and cleans up resources. ```swift CoinmeRiskEngine.reset() ``` #### Manual Input Field Tracking > If you choose to manually track input fields, first disabled automatic field tracking in the configuration. This can be done by ensuring `enableFieldTracking = false` when you set options for the `CoinmeRiskEngine`. How to set up custom `TextField` for tracking: `SwiftUI` ```swift import SwiftUI import CoinmeRiskSDK struct LoginView: View { @State private var email = "" @FocusState private var isEmailFocused: Bool var body: some View { TextField("Email", text: $email) .focused($isEmailFocused) .onChange(of: email) { newValue in CoinmeRiskEngine.trackTextChange(viewId: "email", text: newValue) } .onChange(of: isEmailFocused) { isFocused in CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: isFocused) } } } ``` `UIKit` ```swift // In your UIViewController class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() emailTextField.delegate = self } // UITextFieldDelegate - Track focus changes func textFieldDidBeginEditing(_ textField: UITextField) { CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: true) } func textFieldDidEndEditing(_ textField: UITextField) { CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: false) } // UITextFieldDelegate - Track text changes func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentText = textField.text ?? "" let newText = (currentText as NSString).replacingCharacters(in: range, with: string) CoinmeRiskEngine.trackTextChange(viewId: "email", text: newText) return true } } ``` Be descriptive when assigning a value for `viewId` ("email", "password", "debitCardNumber", etc) #### Tracking Methods Track text changes to an input field ```swift CoinmeRiskEngine.trackTextChange(viewId: String, text: String) ``` Track focus change to a field ```swift CoinmeRiskEngine.trackFocusChange(viewId: String, isFocus: Bool) ``` Note: Be sure to use the same `viewId` for both `trackTextChange()` and `trackFocusChange()` if they are used to reference the same text field or other custom UI component. #### Optional Features #### Enable Location Service Initialize Apple's LocationManager to provide live location updates: ```swift import CoreLocation class LocationService: NSObject, CLLocationManagerDelegate { let locationManager: CLLocationManager? override init() { locationManager = CLLocationManager() locationManager?.requestWhenInUseAuthorization() super.init() locationManager?.delegate = self } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) { if CLLocationManager.isRangingAvailable() { let latitude = manager.location?.coordinate.latitude let longitude = manager.location?.coordinate.longitude print("Location: \(latitude ?? 0), \(longitude ?? 0)") } } } } } ``` #### Enable Wi-Fi Information Tracking Wi-Fi BSSID and SSID can provide additional location signals. 1. Enable Location Services (required) 2. In Xcode: - Go to your target scheme - Click **Signing & Capabilities** - Click **+ Capability** - Add **Access WiFi Information** #### Enable iCloud Record ID iCloud Record ID remains consistent across devices that are associated with the same Apple account. 1. In Xcode 2. Set the flag in the SDK configuration: > DO NOT set `setCloudEntitlements` to true unless CloudKit is properly configured, or the SDK will crash. #### Enable Biometric Authentication Detection Detect the use of FaceID and TouchID Update your `Info.plist` ``` ... NSFaceIDUsageDescription Face ID is used to verify your identity. ``` --- --- title: "Coinme Risk SDK for Android Native Apps" url: "https://platformdocs.coinme.com/#/docs/risk-sdk-for-android-native-apps" markdown: "https://platformdocs.coinme.com/docs/risk-sdk-for-android-native-apps.md" summary: "The Android Coinme Risk Engine SDK is a Kotlin library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions." surface: "caas" platform: "android" package: "CoinmeRisk · Kotlin" version: "1.1.2" source: "https://docs.coinme.com/docs/risk-sdk-for-android-native-apps" updated: "2026-10-28" --- # Coinme Risk SDK for Android Native Apps ## Introduction The Android Coinme Risk Engine SDK is a Kotlin library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions. > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme Risk Engine SDK. **What is it?** The Coinme Risk Engine aggregates data about user behavior for your application. It collects: - Device data such as the type of device, OS name and version, etc. - Location data such as where the user is connecting from. - Connection data such as if the user is using a proxy or VPN, etc. - Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, use of clipboard functions, etc. This data is used to determine the relative riskiness of the user / transaction. > **Why is Risk Tagging Important?** > > Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**. > > As an example, if the risk engine determines that the user location changes suddenly via a VPN to access a region restricted transaction type, then the engine may determine automation is at play and may **rank the transaction as high risk**. ## Implementing the Android SDK > **This package is not public** > > You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact. ### What You'll Need to Get Started Before integrating the SDK, you will need the following credentials from your Coinme integration contact: | Credential | Required For | Notes | | --- | --- | --- | | Cloudsmith auth token | Accessing the library | Required to access the private library in Cloudsmith | | `clientId` | `RiskEngineSetupOptions` | Environment-specific — you will need one for development and one for production | | `partnerId` | `getPartnerSessionTag()` | Passed via `GetPartnerSessionTagOptions`, this is your Partner identifier needed for integration with Coinme APIs | > You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals. ### Installation #### Set Your Entitlement Token Add your token to `local.properties` file in your project root directory: ```properties COINME_TOKEN= ``` Replace `` with the token provided by your Coinme integration contact. Note: `local.properties` is already gitignored by Android Studio to keep your tokens secure, but it is good to ensure this token is not exposed and the file is in your `.gitignore` #### Add the SDK Repository and Dependency to your project Add the repository to either your `settings.gradle` OR `build.gradle.kts` depending on your setup `settings.gradle` ```kotlin dependencyResolutionManagement { repositories { google() mavenCentral() maven { name = "CoinmeSDK" url = uri("https://dl.cloudsmith.io/${findProperty("COINME_TOKEN") ?: ""}/coinme/coinme-sdk-mobile/maven/") } } } ``` `build.gradle` ```kotlin allprojects { repositories { google() mavenCentral() maven { name = "CoinmeSDK" val token = project.findProperty("COINME_TOKEN")?.toString() ?: "" url = uri("https://dl.cloudsmith.io/$token/coinme/coinme-sdk-mobile/maven/") } } } ``` Then in your `app/build.gradle.kts` add the dependency `app/build.gradle.kts` ```kotlin dependencies { implementation("com.coinme:risk-sdk-android:1.1.2") } ``` ### Google Play Requirements Before releasing your application with the Coinme Risk SDK, update your Google Play settings in your developer portal. #### Privacy Policy Update your Google Play Store privacy policy with the following message: > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, MAC Address, and SIM information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN, VPN apps with location spoofing, or other related tools. #### Data Safety For the Data Safety section in the Google Play Console: 1. Navigate to App content > Data safety in your Play Console 2. Declare the following data types are collected: - Location (Approximate and Precise) - Device or other IDs (Device ID) - App info and performance (Crash logs, Diagnostics) - Files and docs (for storage-related fraud detection) Note: You may need to add any other data types your app collects beyond what the SDK requires. For easier setup, you can download and import the Data Safety CSV file from the Sardine SDK documentation if provided by your Coinme integration contact. ### Permissions Neither the Risk SDK nor the components it bundles declares permissions in its own manifest, so your app declares the ones it wants the SDK to use. Only `INTERNET` and `ACCESS_NETWORK_STATE` are needed for a transaction to be scored. Every other permission is optional: it enables an additional device, carrier or location signal, and if it is not declared, or the user does not grant it at runtime, that signal is skipped. Declare only the permissions you are willing to disclose in your Google Play Data Safety form (see above). #### Required permissions `AndroidManifest.xml` ```markup ``` #### Optional permissions `AndroidManifest.xml` ```markup ``` The external-storage permissions (`WRITE_EXTERNAL_STORAGE`, `READ_EXTERNAL_STORAGE`) are also optional. They are used for reinstall detection and storage size, and scoped storage on Android 10+ limits what they can reach. Confirm with your Coinme integration contact whether you need them. > Location and phone state are dangerous permissions on Android 6.0+ and require runtime permission requests, and declaring them is not enough: without the user's grant the SDK collects nothing from them. On Android 10+ identifiers such as IMEI and phone number are not available to regular apps, so `READ_PHONE_STATE` yields only carrier and network information. Permission usage: | Permission | Required | Usage | | --- | --- | --- | | `INTERNET` | Yes | Network communication for fraud detection | | `ACCESS_NETWORK_STATE` | Yes | Get user's network information and state | | `ACCESS_WIFI_STATE` | No | Get user's WiFi name and status | | `READ_PHONE_STATE` | No | Call status detection; phone and network info (MNC, MCC, phone type, SIM info) | | `READ_MEDIA_IMAGES` | No | Screenshot detection (Android 13+) | | `USE_BIOMETRIC` / `USE_FINGERPRINT` | No | Get user's biometric authentication settings (Face or Fingerprint) | | `ACCESS_COARSE_LOCATION` / `ACCESS_FINE_LOCATION` | No | Get user's GPS location for fraud detection | | `READ_GSERVICES` | No | Get Device GSF ID (Google Services Framework ID) | | `WRITE_EXTERNAL_STORAGE` / `READ_EXTERNAL_STORAGE` | No | Reinstall detection; external storage status and size | The SDK also adds a `` block to your merged manifest, which lets it detect whether certain apps are installed. Account for it in your Data Safety form. ### ProGuard Configuration If you use ProGuard or R8 for code obfuscation, add the following rules to your `proguard-rules.pro` file: ``` # Keep Google Play Services classes -keep class com.google.android.gms.** { *; } -keep class com.google.android.gms.tasks.** { *; } -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient { *; } # Keep Sardine SDK classes -keep class ai.sardine.** { *; } -keepclassmembers class ai.sardine.** { *; } ``` ### Implementation **Privacy & Compliance Notice** Important: If you use the Behavior Biometrics feature (enableBehaviourBiometrics = true), please ensure that your end users agree to your privacy policy before you begin collecting their Behavior Biometric data. This is required for compliance with privacy regulations. #### Configuration Options RiskEngineSetupOptions | Option | Type | Required | Description | | --- | --- | --- | --- | | `mode` | `Mode` | Yes | Used to point to environment `Mode.Test` or `Mode.Prod` | | `clientId` | `String` | Yes | Your environment-specific Client ID | | `partnerId` | `String?` | No | Partner Identifier | | `customerId` | `String?` | No | Customer/User's identifier | | `sessionKey` | `String?` | No | Session key (automatically generated if not provided) | | `flow` | `FlowType?` | No | Current User flow (Onboarding, CardTransaction, or CardLinking) | | `appRegion` | `AppRegion` | No | Your app's region of service (`AppRegion.DEFAULT` (US), `CA`, `EU`, `AU`, `IN`; default: `DEFAULT`) | | `enableBehaviourBiometrics` | `Boolean` | No | Enabled behavior tracking (default: true) | | `enableClipboardTracking` | `Boolean` | No | Enable clipboard tracking (default: false) | | `enableFieldTracking` | `Boolean` | No | Enable automatic field tracking (default: true) | #### FlowType Options - `FlowType.Onboarding` - New user registration flow - `FlowType.CardTransaction` - Payment/card transaction flow - `FlowType.CardLinking` - Adding payment methods flow #### sessionKey The `sessionKey` is a unique identifier for tracking a specific user session. Once a key is provided for the set up, it will be cached for the duration of the app's active session. If no value is provided, the key will be automatically generated. You will want to invoke `.getPartnerSessionTag()` to get an updated value that our backend will use to associate collected user data and risk score. Failure to call this and get the expected session key value may result in loss of data for accurate risk assessment. Call it right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that. Using `.updateCoinmeRiskEngine()` with a new key will override and update the cached value. To clear a `sessionKey`, you may call `.resetStoredSessionKey()` > When you call `getPartnerSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one. #### getPartnerSessionTag() Retrieve the session tag from the backend API. The resulting `webSessionID` is automatically used to update the `CoinmeRiskEngine` configuration. ```kotlin suspend CoinmeRiskEngine.getPartnerSessionTag(options: GetPartnerSessionTagOptions): SessionTagData ``` Parameters of `GetPartnerSessionTagOptions`. The SDK sends them as request headers and a query parameter, to the host your `mode` selects: | Param | Type | Required | Description | | --- | --- | --- | --- | | `partnerId` | `String` | Yes | Your partner identifier, sent as the `partnerId` header | | `accountId` | `String` | Yes | The customer ID, sent as the `accountId` query parameter | | `fingerprint` | `String` | Yes | The device fingerprint, sent as the `X-Device-Fingerprint` header | | `rampId` | `String?` | No | Your Ramp ID, sent as the `X-ramp-id` header (Ramp partners only) | | `additionalHeaders` | `Map` | No | Additional headers that may be included if needed by the backend | | `timeout` | `Long` | No | Request timeout in milliseconds (default: 10000) | ### Initialize the SDK Initialize the Risk Engine in your Activity's `onCreate()`: `mainActivity` ```kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val options = RiskEngineSetupOptions( mode = Mode.Prod, // Use Mode.Test for testing clientId = "your-client-id", enableBehaviourBiometrics = true, enableFieldTracking = false // Set to false for manual tracking ) CoinmeRiskEngine.setupCoinmeRiskEngine(this, options) } } ``` Note: Initializing the configuration automatically calls submit(), no need to do it manually. If you need to update the configuration, please use update() method. #### Update the SDK You can update the configuration with flow, sessionKey and customerId options: ```kotlin CoinmeRiskEngine.updateCoinmeRiskEngine( RiskEngineUpdateOptions( sessionKey = "new-session-key", flow = "new-flow", customerId = "customer-id") ``` #### Submit Data Before Transactions Submits all collected behavioral and device date to the backend for risk assessment. Use callback version to ensure data is submitted before making subsequent API calls. ```kotlin CoinmeRiskEngine.submit( onSuccess = { // Data successfully submitted - safe to proceed lifecycleScope.launch { processCardPayment() } }, onError = { error -> Log.e("RiskSDK", "Submission failed", error) handleError(error) } ) ``` #### What it collects: - Sensor data (motion, orientation, pressure) - Behavioral biometrics (typing patterns, interaction timing) - Device context (clipboard activity, focus patterns) - Page/screen engagement metrics #### When to call: - Before payment/transaction API calls - Before critical actions (login, signup, money transfer) - After form completion or user interaction flow #### Other Utility Methods #### Setup Risk Engine (Factory Method) Initializes the Risk Engine singleton. Safe to call multiple times - returns existing instance if already initialized. ```kotlin CoinmeRiskEngine.setupCoinmeRiskEngine( activity: Activity, options: RiskEngineSetupOptions ) ``` #### Update Configuration Updates the runtime configuration (customer ID, session key, flow). Note: This method may throw exceptions if the update fails. Wrap in try-catch for production: ```kotlin CoinmeRiskEngine.updateCoinmeRiskEngine(config: RiskEngineUpdateOptions) ``` #### Get Current Config Returns the current runtime configuration ```kotlin CoinmeRiskEngine.getCoinmeRiskEngineConfig(): RiskEngineUpdateOptions ``` #### Reset Session Resets the stored session key. ```kotlin CoinmeRiskEngine.resetStoredSessionKey() ``` #### Reset SDK Clears the singleton instance and cleans up resources. ```kotlin CoinmeRiskEngine.reset() ``` ### Manual Input Field Tracking > If you choose to manually track input fields, first disabled automatic field tracking in the configuration. This can be done by ensuring `enableFieldTracking = false` when you set options for the `CoinmeRiskEngine`. How to set up custom fields for tracking: `Kotlin` ```kotlin // Track text changes emailEditText.addTextChangedListener(object : TextWatcher { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { CoinmeRiskEngine.trackTextChange("email", s?.toString() ?: "") } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun afterTextChanged(s: Editable?) {} }) // Track focus changes emailEditText.setOnFocusChangeListener { _, hasFocus -> CoinmeRiskEngine.trackFocusChange("email", hasFocus) } ``` Be descriptive when assigning a value for `viewId` ("email", "password", "debitCardNumber", etc) #### Tracking Methods #### Track custom events and user interactions ```kotlin // Track a user action val data = JSONObject().apply { put("action", "card_transaction_started") put("amount", 149.99) put("currency", "USD") } CoinmeRiskEngine.trackCustomData(data) ``` Or use the Map extension for convenience ```kotlin val data = mapOf( "action" to "card_payment_initiated", "amount" to 299.99 ).toJSONObject() CoinmeRiskEngine.trackCustomData(data) ``` #### Track Text Change Track text input in a text field ```kotlin CoinmeRiskEngine.trackTextChange(viewId: String, text: String) ``` #### Track Focus Change Track focus change events on a field or UI component ```kotlin CoinmeRiskEngine.trackFocusChange(viewId: String, isFocus: Boolean) ``` **Note**: If referencing the same UI component but calling various tracking methods, make sure to use the same viewId. --- --- title: "Coinme Risk SDK for React Native" url: "https://platformdocs.coinme.com/#/docs/coinme-risk-sdk-for-react-native" markdown: "https://platformdocs.coinme.com/docs/coinme-risk-sdk-for-react-native.md" summary: "Real-time fraud detection and risk assessment for React Native apps; a thin native-module bridge over Coinme's production iOS and Android risk SDKs, exposed as a typed JS/TS API." surface: "caas" platform: "reactNative" package: "@coinme-security/risk-sdk-react-native" version: "1.1.0" peerDependencies: {"react":">=18","react-native":">=0.72"} source: "https://docs.coinme.com/docs/coinme-risk-sdk-for-react-native" updated: "2026-10-28" --- # Coinme Risk SDK for React Native > Real-time fraud detection and risk assessment for React Native apps; a thin native-module bridge over Coinme's production iOS and Android risk SDKs, exposed as a typed JS/TS API. **Package:** `@coinme-security/risk-sdk-react-native` **Version:** `1.0.1` **License:** Proprietary — Coinme, Inc. ## What this SDK is `@coinme-security/risk-sdk-react-native` is the React Native binding for the Coinme Risk Engine. It wraps Coinme's native iOS (`risk-sdk-ios`) and Android (`risk-sdk-android`) SDKs via a thin React Native native-module bridge and exposes a single typed JS/TS API that matches its sibling SDKs. One npm package. One native module name. One consumer-facing API. If you're already using `@coinme-security/risk-sdk-js` on web or the native iOS / Android SDKs, this is the RN port of the same conceptual model: > **setup → get session tag → update → submit data before each transaction-initiating server call** > > ### What it collects The native engine collects a layered set of signals from the user's session: - **Behavioral biometrics** — typing cadence, interaction timing, touch patterns - **Sensor data** — motion, orientation, device pressure - **Device context** — clipboard activity, focus patterns, screen engagement - **Device fingerprinting** — device identifiers, network state, SIM info (Android), location (with user consent) - **Field interactions** — text changes and focus events on tracked inputs Those signals are flushed to Coinme's Risk Engine when you call `submitCoinmeRiskData()`. Coinme's transaction services consume the signals internally when evaluating the transactions your app initiates. ## Why does Risk SDK exist? Coinme uses real-time behavioral risk signals as part of how we evaluate whether to process or reject a transaction. The Risk SDK is the mechanism that collects those signals on-device and correlates them — via a device fingerprint every Coinme SDK in your app shares — to the server calls they belong to. > **Integration is required.** > > Partners cannot use Coinme's transactional services without integrating the Risk SDK on every surface that initiates a transaction. Transactions unsupported by risk metrics will be rejected outright. **Your responsibilities as an integrator:** - Send the device fingerprint the Coinme SDKs share on your own backend calls (see section 9) - Call `submitCoinmeRiskData()` before every transaction-initiating server request (see section 12) - Handle privacy policy disclosures and store-listing compliance (see section 14) ## How does the Risk SDK work? ``` ┌──────────────────────────────────────────────────────────────┐ │ Your React Native app │ │ │ │ ┌────────────────────────────────────────────────────┐ │ │ │ @coinme-security/risk-sdk-react-native (JS/TS) │ │ │ │ setupCoinmeRiskEngine / updateCoinmeRiskEngine │ │ │ │ getPartnerSessionTag │ │ │ │ submitCoinmeRiskData / CoinmeTrackedTextInput │ │ │ └───────────────────────┬────────────────────────────┘ │ │ │ RN bridge │ │ ┌───────────────────────┴────────────────────────────┐ │ │ │ Native module: CoinmeRiskEngine │ │ │ │ ├── iOS: risk-sdk-ios (xcframework) │ │ │ │ └── Android: risk-sdk-android (aar) │ │ │ └────────────────────┬───────────────────────────────┘ │ └───────────────────────┼──────────────────────────────────────┘ │ ▼ Coinme Risk Engine ◀── session tag + signals │ ▼ Consumed by Coinme's transaction services during evaluation of customer transaction requests ``` The JS layer forwards typed calls across the bridge to the native engine, which does the actual signal collection. The public API mirrors `CoinmeRiskEngine` on iOS and Android, so integration code looks the same across all three platforms. **The signals are consumed by Coinme's internal transaction services, not returned to partners.** The SDK submits behavioral, device, and interaction data to the Risk Engine, which Coinme uses as part of its decision to process or reject a transaction. Risk scores and the underlying signals are not exposed to partner backends. ## Compatibility | Requirement | Supported | | --- | --- | | Node | 20.9+ | | React | 18+ | | React Native | 0.72 – 0.81 (see note below) | | iOS | 16.0+ (required by the underlying `CoinmeRiskSDK` xcframework) | | Android | `minSdkVersion` 24+ (Android 7.0 Nougat) | | Expo | ✅ SDK 51+ (managed workflow with `expo prebuild`) — see [Expo support](#expo-support) | > **React Native 0.82+ is not yet supported.** > > The bridge targets RN's legacy (bridge) architecture; TurboModule support is planned but has not landed. RN 0.82 defaults the New Architecture ON and removes the off-switch. **Pin to 0.81 or older until TurboModule support ships.** ## Obtaining access The Risk SDK is distributed privately. You need a **Coinme Cloudsmith entitlement token** — a single credential that authenticates three things: 1. The private npm registry at `npm.coinme.com` (for the JS package) 2. The CocoaPods repository (for the iOS native artifact) 3. The Maven repository (for the Android native artifact) One token covers all three. If you don't already have one, ask your Coinme integration contact — this is not a self-serve credential. Throughout this guide, the token is referred to as `CLOUDSMITH_TEAM_TOKEN`. Export it as an environment variable before any build step: ``` export CLOUDSMITH_TEAM_TOKEN= ``` For persistence across shells, also add it to: - `~/.gradle/gradle.properties` (covers Gradle) - Your shell rc file (`/.zshrc`, `/.bashrc`, etc. — covers CocoaPods) **Do not commit the token to version control.** Use CI secrets for automated builds. ## Installation ### 1. Install the npm package The package is hosted on Coinme's private npm registry. Configure the scope before installing. **For npm / Yarn Classic**, add to `.npmrc` at your repo root: ```bash @coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/ //npm.coinme.com/coinme-security-wrapper/:_authToken=${CLOUDSMITH_TEAM_TOKEN} always-auth=true ``` **For Yarn Berry (v2+)**, add to `.yarnrc.yml`: ```bash nodeLinker: node-modules npmScopes: coinme-security: npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/' npmAuthToken: '${CLOUDSMITH_TEAM_TOKEN}' ``` Then install: ```bash export CLOUDSMITH_TEAM_TOKEN= yarn add @coinme-security/risk-sdk-react-native # or npm install @coinme-security/risk-sdk-react-native ``` Autolinking will discover this package automatically — you do not need to register the native module by hand on either platform. ### 2. iOS setup Three things to do in `ios/Podfile`: 1. **Add the Cloudsmith and CocoaPods CDN sources at the very top of the file.** Use double quotes so Ruby interpolates the env var: ```bash source "https://dl.cloudsmith.io/#{ENV['CLOUDSMITH_TEAM_TOKEN']}/coinme/coinme-sdk-mobile/cocoapods/index.git" source "https://cdn.cocoapods.org/" ``` 1. **Set the iOS deployment target.** `CoinmeRiskSDK` requires iOS 16+ and RN's default is lower: ```bash platform :ios, '16.0' ``` 1. **Disable the New Architecture** by passing `new_arch_enabled: false` to `use_react_native!` (or set `RCT_NEW_ARCH_ENABLED=0` at install time). Inside the main `target '' do` block, confirm `use_frameworks! :linkage => :static` is present (most modern RN templates include this). Then install: ```bash export CLOUDSMITH_TEAM_TOKEN= cd ios && pod install ``` Autolinking picks up the package's podspec automatically. You do **not** add a `pod '...'` line yourself. ### 3. Android setup **Step 1 — Add Coinme's Cloudsmith Maven repo.** In `android/settings.gradle` (or `.kts`), add a `dependencyResolutionManagement` block. Read the token from the environment rather than committing it: ```kotlin def cloudsmithToken = System.getenv('CLOUDSMITH_TEAM_TOKEN') ?: '' dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) repositories { google() mavenCentral() maven { name = "CoinmeSDK" url = uri("https://dl.cloudsmith.io/${cloudsmithToken}/coinme/coinme-sdk-mobile/maven/") } } } ``` > If your template uses `allprojects { repositories { … } }` in the root `build.gradle` instead of `dependencyResolutionManagement` (common on RN 0.72–0.75), add the same Maven block there. **Step 2 — Force Kotlin 2.3.0.** `risk-sdk-android` is compiled with Kotlin 2.3.0. React Native's Gradle plugin pins an older version, which causes this build failure: > Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 2.3.0, expected version is 2.1.x. In `android/build.gradle`, set `kotlinVersion` to `2.3.0`, pin the plugin explicitly, and add resolution strategies in **both** `buildscript` and `allprojects`: ```kotlin buildscript { ext { buildToolsVersion = "35.0.0" minSdkVersion = 24 compileSdkVersion = 35 targetSdkVersion = 35 ndkVersion = "27.1.12297006" kotlinVersion = "2.3.0" // ← must be 2.3.0 } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}") } // Force Kotlin 2.3.0 for classpath dependencies configurations.classpath { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'org.jetbrains.kotlin') { details.useVersion kotlinVersion } } } } // Force Kotlin stdlib 2.3.0 for all subprojects allprojects { configurations.all { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'org.jetbrains.kotlin' && details.requested.name.startsWith('kotlin-stdlib')) { details.useVersion rootProject.ext.kotlinVersion } } } } apply plugin: "com.facebook.react.rootproject" ``` > `allprojects` must be at the **root level** of `build.gradle`, not nested inside `buildscript`. **Step 3 — Disable the New Architecture.** In `android/gradle.properties`: ```kotlin newArchEnabled=false ``` **Step 4 — Build.** ```bash export CLOUDSMITH_TEAM_TOKEN= cd android && ./gradlew clean ``` Autolinking links the module; you do **not** add an `implementation("com.coinme:...")` line yourself. ## Platform configuration ### 1. Android permissions Add these to `AndroidManifest.xml`: ```markup ``` **Usage reference:** | Permission | Usage | | --- | --- | | `INTERNET` | Network communication for fraud detection | | `ACCESS_COARSE_LOCATION` / `ACCESS_FINE_LOCATION` | Location signals for fraud detection | | `ACCESS_WIFI_STATE` | WiFi name and status | | `ACCESS_NETWORK_STATE` | Network information and state | | `READ_PHONE_STATE` | Phone/network info (MNC, MCC, IMEI, phone number, phone type, SIM number) | | `USE_BIOMETRIC` / `USE_FINGERPRINT` | Biometric authentication settings (Face / Fingerprint) | | `WRITE_EXTERNAL_STORAGE` | Write data to check re-installation behavior | | `READ_EXTERNAL_STORAGE` | External storage status, total size, free size | | `READ_GSERVICES` | Device GSF ID (Google Services Framework ID) | > Location and phone-state permissions are **dangerous permissions** on Android 6.0+ and require runtime permission requests. Handle the flow in your app. ### 2. Android ProGuard / R8 If you use ProGuard or R8 for code obfuscation, add these rules to `proguard-rules.pro`: ```bash # Keep Google Play Services classes -keep class com.google.android.gms.** { *; } -keep class com.google.android.gms.tasks.** { *; } -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient { *; } # Keep Sardine SDK classes -keep class ai.sardine.** { *; } -keepclassmembers class ai.sardine.** { *; } ``` ### 3. Google Play Console requirements Before releasing your app with the Risk SDK: **Privacy Policy** — update your Play Store privacy policy with the following disclosure: > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, MAC Address, and SIM information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN, VPN apps with location spoofing, or other related tools. **Data Safety declaration** — in the Play Console, go to **App content → Data safety** and declare these collected data types: - **Location** (Approximate and Precise) - **Device or other IDs** (Device ID) - **App info and performance** (Crash logs, Diagnostics) - **Files and docs** (for storage-related fraud detection) > Add any other data types your app collects beyond what the SDK requires. Your Coinme integration contact may provide a Data Safety CSV you can import directly. ### 4. iOS Info.plist keys Location permissions are required. Add to `Info.plist`: ```swift NSLocationAlwaysAndWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. NSLocationWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. ``` If you also want Face ID signal detection: ```swift NSFaceIDUsageDescription Face ID is used to verify your identity. ``` **Optional iOS capabilities** (added via Xcode → Signing & Capabilities): - **Access WiFi Information** — required for WiFi BSSID/SSID as an additional location signal. Requires location services to be enabled first. - **iCloud + CloudKit** — enables iCloud record ID (consistent across devices on the same Apple account). If you add this capability, you must set `setCloudEntitlements: true` in the setup options. **Do not enable** `setCloudEntitlements` **without adding the CloudKit capability — the underlying native SDK will crash.** ### 5. App Store Connect requirements Before releasing, update **App Store Connect → App Privacy**: 1. **Data Collection** — select "Yes, we collect data from this app" 2. **Location** — select Coarse and/or Precise Location. Purpose: App Functionality. Reason: "Required for fraud detection and prevention." 3. **Identifiers → Device ID** — Purpose: App Functionality. Check "Yes, device ID is linked to user identity." **Privacy Policy** — update your App Store privacy policy with the following disclosure: > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, and location information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN or other location-spoofing tools. ## Quickstart The canonical flow: > `setupCoinmeRiskEngine` **→** `getPartnerSessionTag` **→** `updateCoinmeRiskEngine` **with the returned** `webSessionID` **→** `submitCoinmeRiskData` **→ your server call.** ```typescript import { getDeviceFingerprint, getPartnerSessionTag, setupCoinmeRiskEngine, submitCoinmeRiskData, updateCoinmeRiskEngine, } from '@coinme-security/risk-sdk-react-native'; // 1. Initialise the engine first — before any session-tag call. await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'your-client-id', customerId: 'customer-123', }); // 2. Right before the payment-method or order call, fetch the session tag // (requires the engine to be initialised). Tags live 30 minutes. // Partner apps use getPartnerSessionTag; it takes no auth token. const { webSessionID } = await getPartnerSessionTag({ partnerId: 'your-partner-id', customerId: 'customer-123', rampId: 'optional-ramp-id', // From 1.1.0 fingerprint is optional: the shared device fingerprint is sent for you. }); // 3. Bind the session key to the running engine. await updateCoinmeRiskEngine({ sessionKey: webSessionID }); // 4. Flush signals before the transaction-initiating server call. await submitCoinmeRiskData(); // 5. Make the server call with the fingerprint every Coinme SDK sends. await fetch('https://api.coinme.com/transactions', { headers: { 'x-device-fingerprint': await getDeviceFingerprint() }, // ... }); ``` `getPartnerSessionTag` resolves its URL automatically from the `mode` you passed to `setupCoinmeRiskEngine`. It needs your partner ID and no token. > **The Risk SDK takes no auth token from your app.** > > In a partner app, always get the session tag with `getPartnerSessionTag`. Never pass your partner access token (from `POST /services/authorize`) or a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) to the Risk SDK. ## The fingerprint contract The fingerprint sent with `getPartnerSessionTag` **MUST be byte-identical** to the `x-device-fingerprint` header on every other Coinme call for the same user in the same launch of your app: the calls the other Coinme SDKs make and your own backend calls. It only has to match within a launch; it is not a permanent device ID. **Mismatched fingerprints get calls refused.** Adding a payment method and placing orders fail with `WEB_SESSION_ID_MISMATCH`. ### The SDK keeps the fingerprint for you From release 1.1.0 you don't have to generate or store a fingerprint, and `fingerprint` is optional. The SDK uses the value you pass; otherwise the one another Coinme SDK already shared in your app; otherwise it creates one and shares it. It keeps the value in native storage, so the same value survives relaunches. Import the Risk SDK at the top of your app's entry file (for example `index.js`), so it loads the stored value before the other Coinme SDKs need it: ```typescript // index.js import '@coinme-security/risk-sdk-react-native'; ``` If you already have a device ID of your own, such as `getUniqueId()` from `react-native-device-info`, you can keep passing it as `fingerprint`; it becomes the shared value. Pass it to the Risk SDK before the other Coinme SDKs make a call, or pass the same value to all of them. A `:` in it is replaced with `-`. With a release older than 1.1.0, `fingerprint` is required: pass one value to `getPartnerSessionTag` and send the same value as `x-device-fingerprint` on your other calls. ### Sending it on your own calls `getDeviceFingerprint()` returns a Promise of the shared value. Read it in the app and send it to your server with each request; route your HTTP client through it so the value never drifts: ```typescript // src/api/fetch.ts import { getDeviceFingerprint } from '@coinme-security/risk-sdk-react-native'; export const apiFetch = async (url: string, init: RequestInit = {}) => fetch(url, { ...init, headers: { ...(init.headers as Record), 'x-device-fingerprint': await getDeviceFingerprint(), }, }); ``` ## Lifecycle The three calls you need to think about: ``` App start ─▶ setupCoinmeRiskEngine ◀── no sessionKey needed yet │ ▼ getPartnerSessionTag (returns webSessionID) │ ▼ updateCoinmeRiskEngine ◀── sessionKey = webSessionID (also: customerId, flow, …) │ ▼ submitCoinmeRiskData ◀── before every transaction-initiating call │ ▼ your server call (x-device-fingerprint header) ``` 1. **Setup once per app session.** `sessionKey` is optional at setup — the native SDK auto-generates one if omitted. After calling `getPartnerSessionTag`, pass the returned `webSessionID` to `updateCoinmeRiskEngine`. Call `getPartnerSessionTag` again right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that. 2. **Update whenever context changes.** - User logs in → `updateCoinmeRiskEngine({ customerId })` - User starts a high-risk flow → `updateCoinmeRiskEngine({ flow: FlowType.CardTransaction })` Cached config is merged, not replaced. The underlying native SDK auto-submits on update. 1. **Submit before every transaction-initiating server call.** Forgetting this produces no error at the SDK layer — signals are collected but never flushed — and the downstream transaction will be rejected by Coinme's services. **On session rotation** (logout, account switch), call `clearSessionKey()` and start the cycle over with a fresh `getPartnerSessionTag`. ## Tracking user input ### `` — the recommended path A drop-in replacement for React Native's `TextInput`. Wires `onChangeText` / `onFocus` / `onBlur` to the native risk engine under a stable `riskIdentifier`, and forwards every other prop — including your own callbacks and refs — unchanged. ```typescript import { useState } from 'react'; import { CoinmeTrackedTextInput } from '@coinme-security/risk-sdk-react-native'; export const LoginForm = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); return ( <> ); }; ``` Works in both controlled and uncontrolled mode. Your own `onChangeText` / `onFocus` / `onBlur` are still invoked. ### Raw trackers (escape hatches) For custom components or imperative flows where `CoinmeTrackedTextInput` doesn't fit: ```typescript import { trackRiskFocusChange, trackRiskTextChange, } from '@coinme-security/risk-sdk-react-native'; await trackRiskTextChange('coupon_code', value); await trackRiskFocusChange('coupon_code', true); ``` **Rules:** - Use the same `riskIdentifier` for both the text and focus calls on a given field - Use descriptive, stable identifiers: `"email"`, `"password"`, `"cardNumber"` — not `"input1"` - Prefer `CoinmeTrackedTextInput` when you can — it handles the wiring for you > **No page tracking.** > > The iOS and Android SDKs don't expose a page-tracking primitive, and this package matches that. There is no `trackRiskPage` or `useTrackCoinmeRiskPage` export. ## When to submit data `submitCoinmeRiskData()` flushes the in-memory buffer of collected signals to the Risk Engine. It is what makes the signals available to Coinme's transaction services for evaluation. ### Call it before every transaction-initiating server call Examples of calls that require a preceding `submitCoinmeRiskData()`: - Payment and card charge endpoints - Wallet transfers and crypto transactions - Onboarding and KYC submissions - Adding or updating payment methods - Money transfers and withdrawals If you are unsure whether a given endpoint requires risk signals, assume it does. Transactions that reach Coinme's services without correlated risk data will be rejected. ### What gets submitted - Behavioral biometrics (typing patterns, interaction timing) - Sensor data (motion, orientation, device position) - Device context (clipboard, focus patterns, screen time) - All tracked field interactions ### Operational notes - **Safe to call multiple times** — the latest collected data is sent each time - **Always await it** before the server call it precedes - **Submit failures are not automatically retried** — if the call rejects, the subsequent transaction will not have correlated signals and will be rejected by Coinme's services ```typescript try { await submitCoinmeRiskData(); await processPayment(); } catch (err) { console.error('Risk subtumit failed', err); // The subsequent transaction will not have correlated signals — do not proceed. } ``` ## API reference All exports are named. There are no default exports. ### Functions | Export | Description | | --- | --- | | `setupCoinmeRiskEngine` | Initialize the native Risk Engine. `sessionKey` is optional — omit at setup, then pass the `webSessionID` from the session-tag call via `updateCoinmeRiskEngine`. | | `updateCoinmeRiskEngine` | Merge config updates (`customerId`, `flow`, `sessionKey`, …) into the cached session. Throws if called before setup. | | `getCoinmeRiskEngineConfig` | Returns the locally cached config. Never round-trips to native. | | `clearSessionKey` | Clears the in-memory session key. Use on logout / account switch. | | `submitCoinmeRiskData` | Flushes collected signals to the Risk Engine. Call before every transaction-initiating server request. | | `getPartnerSessionTag` | Calls Coinme's public partner session-tag endpoint. URL is auto-resolved from `mode`. | | `getDeviceFingerprint` | From 1.1.0. Returns a Promise of the device fingerprint the Coinme SDKs in your app share. | | `getWebSessionId` | From 1.1.0. Returns the session ID to send as `webSessionId`: the `webSessionID` from the last session-tag call, or `undefined`. | | `trackRiskTextChange` | Imperative text-change tracker. | | `trackRiskFocusChange` | Imperative focus / blur tracker. | ### Components | Export | Description | | --- | --- | | `CoinmeTrackedTextInput` | `TextInput` wrapper that tracks change / focus / blur by `riskIdentifier`. Forwards all other props unchanged. | ### Enums and types | Type | Description | | --- | --- | | `FlowType` | Enum — `Onboarding`, `CardTransaction`, `CardLinking`. | | `Mode` | `'test' \| 'prod'`. | | `AppRegion` | `'default' \| 'eu' \| 'ca' \| 'in' \| 'au'`. Mirrors the native SDKs. | | `RiskEngineSetupOptions` | Options for `setupCoinmeRiskEngine`: `mode`, `clientId`, `sessionKey?`, `flow?`, `customerId?`, `partnerId?`, `region?`, `enableBehaviorBiometrics?`, `enableClipboardTracking?`, `enableFieldTracking?`. | | `RiskEngineUpdateOptions` | Partial update shape: `sessionKey?`, `flow?`, `customerId?`, … | | `RiskEngineConfig` | Shape of the cached config returned from `getCoinmeRiskEngineConfig`. | | `GetPartnerSessionTagOptions` | Options for `getPartnerSessionTag`: `partnerId`, `customerId`, `fingerprint?`, `rampId?`, `timeout?`, `additionalHeaders?`. | | `SessionTagData` | `{ webSessionID: string; orgID?: string }`. | | `CoinmeTrackedTextInputProps` | Extends React Native's `TextInputProps` with a required `riskIdentifier: string`. | ### Setup options in detail | Option | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `mode` | `Mode` | Yes | — | `'test'` or `'prod'` | | `clientId` | `string` | Yes | — | Your Coinme-issued client ID | | `partnerId` | `string` | No | — | Partner identifier (distinct from `clientId`) | | `customerId` | `string` | No | — | Customer / user identifier | | `sessionKey` | `string` | No | auto | Session key — auto-generated if omitted | | `flow` | `FlowType` | No | — | `Onboarding`, `CardTransaction`, or `CardLinking` | | `region` | `AppRegion` | No | default | `default` (US), `eu`, `ca`, `au`, `in` | | `enableBehaviorBiometrics` | `boolean` | No | `true` | Enable behavioral biometrics collection | | `enableClipboardTracking` | `boolean` | No | `false` | Enable clipboard activity tracking | | `enableFieldTracking` | `boolean` | No | `true` | Enable automatic field tracking | > `clientId` and `partnerId` are **different values**. Do not use them interchangeably. ### Platform parity This package's public API mirrors the `CoinmeRiskEngine` surface of `risk-sdk-ios` and `risk-sdk-android` — the same lifecycle, the same option names, the same two session-tag variants. If you maintain a native iOS or Android app alongside an RN app, your integration code will look the same in all three. ## Privacy & compliance ### User consent for behavior biometrics If `enableBehaviorBiometrics` is `true` (the default), ensure users have agreed to your privacy policy **before** collecting any biometric data. This is required for GDPR, CCPA, and equivalent privacy regulations. One way to handle this is to defer `setupCoinmeRiskEngine` until consent is recorded on first launch, or to initialise with `enableBehaviorBiometrics: false` and flip it later via `updateCoinmeRiskEngine`. The right approach depends on your app's consent flow — check with your legal and compliance teams. ### Privacy policy disclosures Update your app's privacy policy to disclose data collection for fraud protection. The required disclosure text is in section 7.3 (Android) and section 7.5 (iOS). ### Store-listing requirements - **Google Play** — declare data types in the Data Safety section (see section 7.3) - **App Store** — declare data types in App Privacy (see section 7.5) Your Coinme integration contact may provide pre-filled CSV imports for both. ## Expo support Step-by-step instructions for adding `@coinme-security/risk-sdk-react-native` to an existing Expo app (managed workflow with `expo prebuild`). ### Prerequisites - Expo SDK 51+ - iOS deployment target 16.0+ (set automatically by the plugin) - Android `minSdkVersion` 24+ - `CLOUDSMITH_TEAM_TOKEN` — the Cloudsmith entitlement token provided by Coinme during onboarding. Ask your Coinme integration contact if you don't have it. ### Before you begin — export your token Export `CLOUDSMITH_TEAM_TOKEN` once at the start of your terminal session. All subsequent commands in this guide (package install, `pod install`, Gradle build) will pick it up automatically. ```bash export CLOUDSMITH_TEAM_TOKEN= ``` ### 1. Install the JS package The package is hosted on a private Cloudsmith npm registry. Configure the scope before installing by adding the registry to your project's config file at the repo root. `.npmrc` (npm / Yarn Classic): ```bash @coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/ //npm.coinme.com/coinme-security-wrapper/:_authToken=${CLOUDSMITH_TEAM_TOKEN} ``` `.yarnrc.yml` (Yarn Berry v2+): ```yaml nodeLinker: node-modules npmScopes: coinme-security: npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/' npmAuthToken: '${CLOUDSMITH_TEAM_TOKEN}' ``` Then install: ```bash yarn add @coinme-security/risk-sdk-react-native ``` ### 2. Add the config plugin Add the plugin to your Expo config. No options are required — native credentials are resolved from `CLOUDSMITH_TEAM_TOKEN` at build time, not stored in the config. `app.json`: ```json { "expo": { "plugins": [ "@coinme-security/risk-sdk-react-native" ] } } ``` `app.config.js` (if you use a dynamic config): ```javascript export default { // ... plugins: [ '@coinme-security/risk-sdk-react-native', ], }; ``` ### 3. Build and run The plugin applies all native changes automatically during prebuild. You do not need to manually edit any native files. | Platform | What the plugin configures | | --- | --- | | iOS `Podfile` | Adds Cloudsmith CocoaPods source (token read at `pod install` time via `ENV.fetch`) | | iOS `Podfile` | Sets deployment target to `16.0` | | Android `build.gradle` | Adds Cloudsmith Maven repository (token read at build time via `System.getenv`) | | Android `build.gradle` | Forces Kotlin 2.3.0 and adds resolution strategies | **iOS:** ```bash npx expo run:ios ``` **Android:** ```bash npx expo run:android ``` These commands run `expo prebuild` (if needed), `pod install` / Gradle build, and launch on device. Because `CLOUDSMITH_TEAM_TOKEN` is already exported, no extra steps are required. > To regenerate native directories from scratch, run `expo prebuild --clean` before `npx expo run:ios` / `npx expo run:android`. ### 4. JS integration #### 4a. Initialization sequence The native engine must be initialized **before** calling `getPartnerSessionTag`. Use `setupCoinmeRiskEngine` first, then fetch the session tag and update the engine with it: ```typescript import { setupCoinmeRiskEngine, getPartnerSessionTag, updateCoinmeRiskEngine, FlowType, } from '@coinme-security/risk-sdk-react-native'; // Step 1 — initialize the native engine await setupCoinmeRiskEngine({ mode: 'test', // 'test' | 'prod' clientId: CLIENT_ID, partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, flow: FlowType.Onboarding, enableFieldTracking: true, enableBehaviorBiometrics: true, }); // Step 2 — right before each add-payment-method call and each order, get the // session tag (requires the engine to be initialized). Tags live 30 minutes. const tag = await getPartnerSessionTag({ partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, }); // Step 3 — bind the session key to the running engine await updateCoinmeRiskEngine({ sessionKey: tag.webSessionID }); ``` > `CLIENT_ID` and `CAAS_PARTNER_ID` are **different values**. Do not use them interchangeably. #### 4b. Tracked input fields Replace standard `TextInput` components with `CoinmeTrackedTextInput` to forward keystrokes and focus events to the native SDK: ```typescript import { CoinmeTrackedTextInput } from '@coinme-security/risk-sdk-react-native'; ``` `riskIdentifier` is a stable string label that the SDK uses to associate events with a specific field. ### 5. Complete integration skeleton Minimal end-to-end example — SDK calls only, no UI boilerplate. Replace the `REPLACE_ME_*` constants with your real values. ```typescript import { CoinmeTrackedTextInput, FlowType, getPartnerSessionTag, setupCoinmeRiskEngine, updateCoinmeRiskEngine, } from '@coinme-security/risk-sdk-react-native'; const CLIENT_ID = 'REPLACE_ME_CLIENT_ID'; const CAAS_PARTNER_ID = 'REPLACE_ME_CAAS_PARTNER_ID'; // distinct from CLIENT_ID const CUSTOMER_ID = 'REPLACE_ME_CUSTOMER_ID'; // Step 1 — initialize the native engine const handleInit = async () => { await setupCoinmeRiskEngine({ mode: 'test', // 'test' | 'prod' clientId: CLIENT_ID, partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, flow: FlowType.Onboarding, enableFieldTracking: true, enableBehaviorBiometrics: true, }); }; // Step 2 — right before each add-payment-method call and each order, fetch a // session tag and bind it to the engine. Tags live 30 minutes. const handleGetSessionTag = async () => { const tag = await getPartnerSessionTag({ partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, }); await updateCoinmeRiskEngine({ sessionKey: tag.webSessionID }); }; // Step 3 — tracked input fields (call after step 2) const TrackedForm = () => ( <> ); ``` ### 6. Required values | Value | Description | | --- | --- | | `CLOUDSMITH_TEAM_TOKEN` | Pulls native `CoinmeRiskSDK` binaries during pod install and Gradle sync | | `CLIENT_ID` | Identifies your app to the Risk Engine | | `CAAS_PARTNER_ID` | Partner identifier — distinct from `CLIENT_ID` | ## Troubleshooting ### `Native module CoinmeRiskEngine not linked` The JS layer couldn't find `NativeModules.CoinmeRiskEngine` at runtime. **Likely causes:** - **You added the package but didn't rebuild the native app.** ```bash cd ios && pod install cd .. && yarn ios # and yarn android ``` - **Cloudsmith auth failing.** Check the `pod install` / Gradle sync logs. If CocoaPods or Gradle can't reach Coinme's Cloudsmith, the native module won't link. Verify `CLOUDSMITH_TEAM_TOKEN` is exported in the shell you're building from, or set in `~/.gradle/gradle.properties` for Gradle persistence. - **New Architecture enabled.** The module is registered on the legacy bridge only. If Fabric / TurboModules is on, the runtime won't see it. Confirm `new_arch_enabled: false` in `Podfile` and `newArchEnabled=false` in `android/gradle.properties`. - **Metro cache.** After a successful rebuild, clear Metro with `yarn start --reset-cache`. ### `Module was compiled with an incompatible version of Kotlin` (Android) The native `risk-sdk-android` artifact is compiled with Kotlin 2.3.0, but React Native 0.81's Gradle plugin pins an older Kotlin. Force Kotlin 2.3.0 across all subprojects via `resolutionStrategy` — see section 6.3, Step 2 for the full copy-pasteable block. **Expo:** If the error persists after applying the resolution strategy, re-run prebuild from scratch and verify the plugin ran: ```bash expo prebuild --clean npx expo run:android ``` Check that `android/build.gradle` contains `classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.0")` and the `// @coinme-risk-sdk:kotlin-version` marker. If those are missing, the plugin didn't run — verify `@coinme-security/risk-sdk-react-native` is listed under `plugins` in your Expo config. ### `Could not find com.coinme:risk-sdk-android` `CLOUDSMITH_TEAM_TOKEN` is missing or wrong. Export it before building: ```bash export CLOUDSMITH_TEAM_TOKEN= ``` Also verify the Maven block in `android/settings.gradle` reads from the same env var. **Expo:** Re-export and retry with: ```bash export CLOUDSMITH_TEAM_TOKEN= npx expo run:android ``` ### `pod install` fails with `401 Authentication required` Token is wrong or expired. Re-export `CLOUDSMITH_TEAM_TOKEN` and run `pod install` again. If you have a stale cache from a previous failed attempt: ```bash rm -rf ~/Library/Caches/CocoaPods ~/.cocoapods/repos ``` **Expo:** Re-export and retry with: ```bash export CLOUDSMITH_TEAM_TOKEN= npx expo run:ios ``` ### `KeyError: key not found: CLOUDSMITH_TEAM_TOKEN` (Expo) `CLOUDSMITH_TEAM_TOKEN` was not set when `expo prebuild` triggered `pod install`. Export it and re-run: ```bash export CLOUDSMITH_TEAM_TOKEN= npx expo run:ios ``` ### `NativeModules.CoinmeRiskEngine is undefined` (Expo) The native module didn't link during prebuild. Clean and rebuild: ```bash # iOS expo prebuild --clean && npx expo run:ios # Android expo prebuild --clean && npx expo run:android ``` ### `RiskEngine is not initialized. Call setupCoinmeRiskEngine() first.` `getPartnerSessionTag` / `updateCoinmeRiskEngine` was called before `setupCoinmeRiskEngine` completed. Always `await setupCoinmeRiskEngine(...)` first. ### My integration looks fine but transactions are being rejected **Most common cause:** you're not calling `submitCoinmeRiskData` before your server requests. This produces no error at the SDK layer — the SDK collects signals and never flushes them — but without correlated signals, Coinme's transaction services will reject the downstream request. **Checklist:** 1. `await submitCoinmeRiskData()` immediately before any transaction-initiating server call (checkout, payment-method link, onboarding submit, etc.) 2. Confirm every Coinme SDK and your backend calls send the same `x-device-fingerprint` (read it with `getDeviceFingerprint()`) — see section 9 3. Confirm `mode` is `'prod'` in production builds. A mismatched `mode` / `clientId` routes data to the wrong environment 4. Confirm `setupCoinmeRiskEngine` has completed (await it) before any `updateCoinmeRiskEngine` call. Parallel setup/update races can lead to overridden config ### `updateCoinmeRiskEngine` throws before I've called setup By design. If no `sessionKey` has ever been set (via `setupCoinmeRiskEngine` or `getPartnerSessionTag`), `updateCoinmeRiskEngine` will throw. Call setup first. ## Support For issues, questions, or feature requests, ask your Coinme integration contact. ## 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`. --- --- name: coinme-risk-web description: "Add the Coinme Risk SDK to a web app: install from the private registry, set up the Risk Engine with the client ID, tag the inputs it should observe, and get a session tag right before each add-payment-method call and each order. Use when asked to add risk, fraud or device signals, a session tag or the Coinme Risk Engine to a website or web app." metadata: surface: "caas" package: "@coinme-security/risk-sdk-js" version: "1.2.0" --- # Coinme Risk SDK on the web ## When to use this skill The human wants Coinme's Risk Engine in a web app, which Coinme requires before any transactional service is used from the app. The Widget SDK carries its own risk signals; this skill is for a partner's own app and its own transaction calls. ## 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 web app that initialises the Risk Engine at launch with the client ID, tracks the inputs the guide names, gets a session tag right before each add-payment-method call and each order, and, where the SDK has a submit call, submits its data immediately before each transaction-initiating call to the backend, with the credentials kept out of source. ## 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. | | `clientId` | Identifies the integration to the Risk Engine; the SDK refuses to initialise without it. One per environment. Not a secret: it runs in the client, but the partner access token and client secret never go there with it. | Runtime configuration, not source; keep the development and production values apart. | | `Partner ID (and Ramp ID for Ramp partners)` | Identifiers the session-tag call carries so the Risk Engine attributes the session: on the web the x-partner-id (and x-ramp-id) headers in getSessionTag additionalHeaders; on iOS, Android and React Native the partnerId (and rampId) options of getPartnerSessionTag. | Runtime configuration passed to the SDK; never hard-coded. | ## 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 one exception is the Risk SDK's optional `x-ramp-id` header, which only a Ramp partner sends. - 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 Get the session tag right before each add-payment-method call and each order (getSessionTag on the web, getPartnerSessionTag on iOS, Android and React Native) and send it as webSessionId: a tag lives 30 minutes from when it was issued, using it doesn't extend that, and calling again while it is live returns the same tag. Never persist a tag across reloads or relaunches to reuse it. The device fingerprint is optional from 1.2.0: the Coinme SDKs share one. The app reads it with getDeviceFingerprint() and sends it to its server with each request; never call getDeviceFingerprint() on the server. Where the SDK has a submit call (submitCoinmeRiskData on React Native, CoinmeRiskEngine.submit on iOS and Android), make it immediately before every transaction-initiating server call. The guide's session-flow section is the contract. Store listings and privacy disclosures in the guide are requirements, not suggestions; include them in what you hand back. The Risk SDK takes no auth token from the app. In a partner app the session tag comes from the partner session-tag call (getPartnerSessionTag on iOS, Android and React Native; getSessionTag with the x-partner-id header on the web), which needs no token. Never pass the partner access token or a Transient Auth Token to the Risk SDK. ## 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 Risk SDK for Web ## Introduction The Coinme Risk Engine SDK is a library, distributed as an NPM package, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions. > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme risk engine SDK. **What is it?** The Coinme risk engine aggregates data about user behavior for your application. It collects: - Device data such as the type of device, browser, etc. - Location data such as where the user is connecting from. - Connection data such as if the user is using a proxy or VPN, etc. - Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, etc. This data is used to determine the relative riskiness of the user / transaction. > **Why is Risk Tagging Important?** > > Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**. > > As an example, if the risk engine determines that the user is connected with an unknown browser type, via a VPN or proxy, and that interactions with elements of your app are happening much faster than would be normal for a human, then the engine may determine automation is at play and may **rank the transaction as high risk**. ## How to Use the SDK The Coinme Risk Engine SDK is an NPM package. You may install it as follows. > **This package is not public** > > You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact. ### What You'll Need to Get Started Before integrating the SDK, you will need the following credentials from your Coinme integration contact: | Credential | Required For | Notes | | --- | --- | --- | | NPM auth token | Installing the package | Required to access the private npm registry | | `clientId` | `setupCoinmeRiskEngine` | Environment-specific — you will need one for development and one for production | | `x-partner-id` | `getSessionTag` | Passed via `additionalHeaders` | | `x-ramp-id` | `getSessionTag` (Ramp partners only) | Passed via `additionalHeaders` | ### Installation #### For SDK Consumers To install the package, configure your `.npmrc` or `.yarnrc` (or equivalent) to include your authentication token: ``` @coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/ //npm.coinme.com/coinme-security-wrapper/:_authToken= always-auth=true ``` > Replace `` with your provided token. Then install via: NPM: ``` npm install @coinme-security/risk-sdk-js ``` Yarn: ``` yarn add @coinme-security/risk-sdk-js ``` PNPM: ``` pnpm add @coinme-security/risk-sdk-js ``` #### Quick Start You can use the Coinme Risk Engine SDK in your project by following the steps below. #### Setup the Coinme Risk Engine The setup function initializes the Risk Engine and applies all necessary configurations. ```typescript import { setupCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; setupCoinmeRiskEngine({ mode: "test", clientId: "client-id", }) .catch((error) => { console.error("Error setting up Risk Engine:", error); }) .finally(() => { console.log("Risk Engine setup complete!"); }); ``` > setupCoinmeRiskEngine is **not sufficient** in and of itself to use the risk SDK; this call is to be made when your app starts up in order to initialize the risk engine. There are other conditions which will require you to update additional parameters dynamically during the user session, such as when a user starts a high-risk action like a transaction, after a user has onboarded and now there is a customerId, etc. In these cases, use updateCoinmeRiskEngine. > **Key Takeaway: When should I use this?** > > You should call setupCoinmeRiskEngine when your application instantiates. > You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals. #### Get Current Configuration To check which risk parameters are applied, use: ```typescript import { getCoinmeRiskEngineConfig } from "@coinme-security/risk-sdk-js"; const config = getCoinmeRiskEngineConfig(); console.log(config); ``` > The Risk Engine configuration is only available after setup completes. #### Update Coinme Risk Engine Configuration While setup handles initial configuration, you can and should manually update specific parameters when needed. An example would be after a user has onboarded or logged in, as at this point you will have a customerId available to you; this helps the risk engine associate user behavior with your user. Another example is when you wish to update the flow identifier being sent to the risk engine. This is necessary so that when your user is entering a specific flow in your app such as **onboarding**, **linking a payment method**, or **transacting**, these special activities will be properly tagged; the risk engine examines user behavior in such flows closely. Therefore, you should tag these flows by updating the risk engine config by providing a flow identifier as seen below. > **What is a Flow Identifier?** > > A flow identifier is a string that acts as a tag to uniquely identify that data the risk engine is logging belongs to a contiguous and related flow of user actions. ```typescript import { updateCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "customer-123", flow: "customer-onboarding", }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Configuration updated"); }); ``` #### Flow Types There are certain flows that are universal, and which are important to the operation of the coinme risk engine. You can use a pre-defined FlowType in these cases to ensure you are properly tagging these flows. We export a FlowType enumeration that exposes these common flows which our risk engine can understand and use when making risk decisions. This enum is structured as follows: ```typescript export enum FlowType { Onboarding = 'customer-onboarding', CardTransaction = 'card-transaction', CardLinking = 'payment-method-linking', } ``` For maximum value, you should use the appropriate FlowType as the flow identifier when you are onboarding users, adding a payment method, or undertaking a transaction. > **Why Use Flow Identifiers?** > > Flow identifiers help **group multiple actions into a single session** so that risk is assessed based on **contextual user behavior**. Instead of analyzing each interaction separately, the risk engine can **detect patterns within a specific user journey**. > > For example: > > - If a user **enters payment details too quickly** after onboarding, this might indicate a **scripted attack** rather than a real person. > - If a user **switches IP addresses** midway through a transaction, it could indicate a **fraud attempt**. > - If a user **is interacting normally but suddenly switches to rapid inputs**, the system can **adapt its risk evaluation in real time**. > > By tagging actions with the correct FlowType, your application **provides the risk engine with the necessary context** to assess transactional legitimacy. > The Coinme risk engine requires the specific flow identifiers exposed by the risk SDK for any of these pre-defined flow types; **if you do not use the supported identifier, your users and transactions may not be appropriately scored and you will be at risk of high denial rates for your transactions.** **Usage Examples** Each example demonstrates when and how to use updateCoinmeRiskEngine with a **specific flow type**. **Example 1: Onboarding Flow** When a **new user signs up**, you must tag their session as **onboarding** so the risk engine can monitor suspicious activities. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "new-user-456", flow: FlowType.Onboarding, }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("User onboarding flow tracked."); }); ``` > **When to use?** > > Call this **when the user starts** the signup process. **Example 2: After Onboarding or Sign-in** After a **new user finishes signing up**, or after a **user has signed in**, you must update the risk engine with their userID so that data can now be associated with the user rather than a session. This allows the risk engine to aggregate and interpret data over time. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "user-456", }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("User ID now tracked."); }); ``` > **When to use?** > > Call this **right after the user completes** the signup **or login** process and the user’s permanent ID is known. **Example 3: Linking a New Card** If a user is adding a **new payment method**, this is a **high-risk action** that must be monitored. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "user-789", flow: FlowType.CardLinking, }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Card linking flow tracked."); }); ``` > **When to use?** > > Call this **when the user enters a process to add a payment method**. **Example 4: Processing a Card Transaction** When a user makes a **purchase or transaction**, you should explicitly tag it. ```typescript import { updateCoinmeRiskEngine, FlowType } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "user-123", flow: FlowType.CardTransaction, }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Card transaction flow tracked."); }); ``` > **When to use?** > > Call this **when the user enters a transactional flow** such as when they start a buy or sell transaction. > **Proper Use** > > The updateCoinmeRiskEngine function is designed to modify the risk engine's configuration after the initial setup. However, since both setupCoinmeRiskEngine and updateCoinmeRiskEngine are **asynchronous**, calling them sequentially without ensuring the setup is complete may cause the update function to override the initial configuration. #### How to Update Correctly - Ensure that setupCoinmeRiskEngine is completed before calling updateCoinmeRiskEngine. - If calling both on the first render (e.g., in a React setup), chain them properly using await or a state check. - Calling updateCoinmeRiskEngine before setupCoinmeRiskEngine finishes may lead to an incomplete or overridden configuration. **Example: Correct Usage - Await the Setup Before Updating** ```typescript async function initializeRiskEngine() { await setupCoinmeRiskEngine({ mode: "test", clientId: "client-id", }); console.log("Setup complete:", getCoinmeRiskEngineConfig()); await updateCoinmeRiskEngine({ customerId: "a@mail.com", flow: "flow-id", }); console.log("Update complete:", getCoinmeRiskEngineConfig()); } initializeRiskEngine(); ``` > **Why is this correct?** > > - Ensures setup completes before update can be called **Example: Incorrect Usage - Running Setup and Update in Parallel** ```typescript setupCoinmeRiskEngine({ mode: "test", clientId: "client-id", }); updateCoinmeRiskEngine({ customerId: "a@mail.com", flow: "flow-id", }); ``` > **Why is this wrong?** > > - updateCoinmeRiskEngine may execute before setupCoinmeRiskEngine completes. > - The update call might override important setup details. > - Leads to unpredictable behavior in the risk engine configuration. > **Key Takeaway: When should I use this?** > > You should call updateCoinmeRiskEngine: > > - After a user has onboarded or logged in, and you have a customerId > - By updating the risk engine with the customerId, you ensure that the risk engine can understand the user’s behavior over time, which leads to better risk modeling. > - When a user begins a flow that needs to be explicitly identified, such as onboarding, linking a payment method, or transacting. > - **These are key actions that should be tagged** with the correct flow identifier. #### Tagging Elements You can add Risk attributes to elements, components, or strings with the addCoinmeRiskTag function. The risk engine SDK automatically detects these tags and will flow behavioral metrics into the risk engine from any tagged entities automatically. **Examples:** - Returning a pre-tagged HTML element: ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; // Using a raw HTML string const elementAsString = addCoinmeRiskTag({ element: '
Hello, World!
', riskIdentifier: 'my-element', }); console.log(elementAsString); // Outputs a div with the risk data attribute 'my-element' added. ``` - Tagging an existing DOM element: ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; // Using an existing DOM element const divElement = document.createElement('div'); divElement.textContent = 'Hello, World!'; const taggedElement = addCoinmeRiskTag({ element: divElement, riskIdentifier: 'my-element' }); console.log(taggedElement.outerHTML); // Outputs a div with the risk data attribute 'my-element' added. ``` - Tagging a React-Like object: ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; // Tagging a React/Vue-style object const reactLikeObject = { type: 'div', props: { children: 'Hello, World!' }, }; const taggedObject = addCoinmeRiskTag({ element: reactLikeObject, riskIdentifier: 'my-element' }); console.log(taggedObject); // Outputs a react / vue style object with the risk data attribute 'my-element' added. ``` ## Core concepts #### Client ID Requirement > You must provide your clientId to use the SDK. If you don't have your clientId, ask your Coinme integration contact. The clientId uniquely identifies your partner integration within the Risk Engine. - It is provided by Coinme during onboarding. - Issued alongside your other Coinme credentials. It is not a secret and is meant to run in the browser; never put your partner access token or client secret in the browser alongside it. The Risk SDK itself takes no auth token. - Without it, the SDK will throw an error and refuse to initialize. #### Understanding sessionKey The sessionKey is a unique identifier for tracking a specific user session. > **In-Memory Only** > > The SDK does **not** persist session keys to localStorage, sessionStorage, or cookies. The session key is only held in memory. On page refresh, the key is lost. Don't persist a session tag to rehydrate it later: call `getSessionTag()` again right before the call that needs it. | Behavior | Outcome | | --- | --- | | Provide sessionKey in setup | Used & cached in memory | | Provide sessionKey in update | Overrides & caches in memory | | No sessionKey provided, stored key exists | Stored key reused automatically | | No sessionKey provided, no stored key | A stand-in key is cached; Coinme refuses it as a `webSessionId`, so read the session ID with `getWebSessionId()` (from 1.2.0) rather than `getCoinmeRiskEngineConfig().sessionKey`, which is deprecated for this | | Call getSessionTag() | webSessionID from server becomes the cached sessionKey | | Call clearSessionKey() | Clears the in-memory key; from 1.2.0 also the user identity (`customerId`, `flow`, `parentSessionKey`), keeping `partnerId` and the `enable*` flags | > When you call `getSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one. > **Why this matters** > > It is essential that the Risk Engine use the session tag returned by this endpoint once it is called. If you change the session key after this call is made, risk metrics will not be properly associated with your user. When you call `getSessionTag()`, you are signifying that you want Coinme to track your user's session — your own session ID is no longer relevant to this tracking. > **A session tag lives 30 minutes** > > Coinme keeps a session tag for 30 minutes from when it issued it, and using it doesn't extend that. You can't tell from the browser how long a tag has left, so don't store a `webSessionID` and reuse it on later page loads. > **Call `getSessionTag()` right before each add-payment-method call and each order.** > > Send the `webSessionID` it returns as `webSessionId` on that call. Calling `getSessionTag()` again while a tag is still live returns the same tag, so it doesn't start a new risk assessment session; once the tag is 30 minutes old it returns a new one. #### Clearing the sessionKey ```typescript import { clearSessionKey } from "@coinme-security/risk-sdk-js"; clearSessionKey(); ``` > This clears the **in-memory** session key. From 1.2.0 it clears the whole in-memory user identity: the session key plus the `customerId`, `flow` and `parentSessionKey` you passed to setup or update. App-level settings (`partnerId` and the `enable*` flags) are kept. The next setup or update starts from a clean identity, so nothing from the previous user is sent with the next user's session. It doesn't reset Sardine's own state; Sardine takes the next user's values through its normal update. Before 1.2.0 it clears only the session key. Use this in SPAs when: > > - Logging out users (without a page refresh) > - Switching accounts > - Resetting state for tests > > For non-SPA apps or full page reloads, the in-memory key is cleared automatically. If you stored a session key yourself (for example in `localStorage`), remove it as well; the SDK can't clear storage it doesn't own. #### Typical Session Flow Example ```typescript // Setup with auto-generated sessionKey await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'client-id', }); // Later — Update without providing sessionKey (uses stored one) await updateCoinmeRiskEngine({ flow: 'customer-onboarding', }); // On session end (e.g., logout in a SPA) clearSessionKey(); // Start new user/session await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'client-id', }); ``` #### Session Flow with getSessionTag (Recommended for Transactions) ```typescript import { setupCoinmeRiskEngine, getSessionTag, clearSessionKey, } from "@coinme-security/risk-sdk-js"; // Once, when your app starts await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'client-id', }); // Right before each add-payment-method call and each order: // a session tag lives 30 minutes, so fetch it every time async function freshWebSessionId(customerId) { const sessionData = await getSessionTag({ apiBaseUrl: 'https://api.example.com', // From 1.2.0 you may leave fingerprint out; earlier releases require it. customerId, additionalHeaders: { 'x-partner-id': 'your-partner-id', 'x-ramp-id': 'your-ramp-id', // only needed for ramp partners }, }); return sessionData.webSessionID; } const webSessionId = await freshWebSessionId('customer-123'); // Send webSessionId with the payment-method or order call. // On logout or account switch (SPA only; a page refresh clears it) clearSessionKey(); ``` ## API Reference The Coinme Risk Engine SDK provides the following functions for interacting with the Risk Engine. You can find detailed information about each function below or in the **API Reference** (internal to Coinme, not public)**.** ### setupCoinmeRiskEngine Sets up the Coinme Risk Engine with the provided options. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | mode | `'test' \| 'prod'` | ✅ | Operating environment | | clientId | string | ✅ | Partner-specific risk engine client ID | | partnerId | string | optional | Partner identifier | | customerId | string | optional | Customer identifier | | sessionKey | string | optional | Custom session tracking key | | flow | `string \| FlowType` | optional | Flow context | **Example:** ```typescript import { setupCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; setupCoinmeRiskEngine({ mode: "test", clientId: "client-id" }) .catch((error) => { console.error("Error setting up Risk Engine:", error); }) .finally(() => { console.log("Risk Engine setup complete!"); }); ``` ### getCoinmeRiskEngineConfig Retrieves the latest risk assessment settings applied to the current session. **Returns:** - `Partial`: An object containing the current Risk Engine configuration. All fields are optional and include: `partnerId`, `customerId`, `sessionKey`, `flow`, `parentSessionKey`, `enableBiometrics`, `enableGeoLocation`, `enablePortScanning`. - If no configuration has been set, it returns `{}`. **Example:** ```typescript import { getCoinmeRiskEngineConfig } from "@coinme-security/risk-sdk-js"; const config = getCoinmeRiskEngineConfig(); console.log(config); // Outputs: { partnerId: "...", sessionKey: "...", ... } ``` ### updateCoinmeRiskEngine Updates the Coinme risk assessment settings for the current session. This ensures that risk evaluations, such as device fingerprinting and geolocation tracking, are correctly applied. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | partnerId | string | optional | Partner identifier | | customerId | string | optional | Customer identifier | | sessionKey | string | optional | Override session key | | flow | `string \| FlowType` | optional | Flow context | | parentSessionKey | string | optional | Parent session key | | enableBiometrics | boolean | optional | Enable biometric signals | | enableGeoLocation | boolean | optional | Enable geo-location | | enablePortScanning | boolean | optional | Enable port scanning | **Example:** ```typescript import { updateCoinmeRiskEngine } from "@coinme-security/risk-sdk-js"; updateCoinmeRiskEngine({ customerId: "customer-123", flow: "onboarding", }) .catch((error) => { console.error("Error updating configuration:", error); }) .finally(() => { console.log("Configuration updated"); }); ``` ### addCoinmeRiskTag Enhances an element, component, or string representation of HTML by tagging the element with a risk tag. The risk engine SDK automatically detects these tags and will flow metrics into the risk engine from any tagged entities automatically. **Parameters:** | Prop | Type | Required | Description | | --- | --- | --- | --- | | element | `HTMLElement \| string \| object` | ✅ | Target element | | riskIdentifier | string | ✅ | Unique risk tag | **Returns:** - The same element with the risk tag applied. **Example:** ```typescript import { addCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; const element = addCoinmeRiskTag({ element: '
Hello, World!
', riskIdentifier: 'my-element', }); console.log(element); // Outputs a div tagged with the specified risk tag ``` ### withCoinmeRiskTag Creates a higher-order component that adds a risk tag to the wrapped component's output. The tagging behavior depends on what the component returns: - **String**: the string output is wrapped in a new `
` element. - **HTMLElement**: the `data-sardine-id` attribute is added directly to the element. - **Object with `props`** (React/Vue-style): `data-sardine-id` is added to the `props` object. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | Component | function | ✅ | The component function to wrap. | | id | string | ✅ | Unique risk tag to apply. | **Returns:** - A wrapped component with the risk tag attribute added to props or its equivalent. **Examples:** Wrapping a simple component: ```typescript import { withCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; const MyComponent = (props) => `
${props.text}
`; const TaggedComponent = withCoinmeRiskTag(MyComponent, 'my-element'); console.log(TaggedComponent({ text: 'Hello, world!' })); // The string output is wrapped in a new tagged div: //
Hello, world!
``` Wrapping a object-based component: ```typescript import { withCoinmeRiskTag } from "@coinme-security/risk-sdk-js"; const MyObjectComponent = (props) => ({ type: 'div', props: { children: props.text }, }); const WrappedObject = withCoinmeRiskTag(MyObjectComponent, 'object-component'); console.log(WrappedObject({ text: 'Hello, world!' })); // Outputs an object tagged with the specified risk tag ``` ### getSessionTag Retrieves the Sardine session tag data from the public `/pub/get-session-tag` endpoint. This call obtains the session information needed for transaction risk assessment. Upon successful retrieval, the `webSessionID` is automatically used to update the Sardine configuration and is stored as the active session key for all subsequent SDK calls. **Parameters:** | Param | Type | Required | Description | | --- | --- | --- | --- | | apiBaseUrl | string | ✅ | The base URL of the API endpoint | | fingerprint | string | optional | The device fingerprint, sent as `x-device-fingerprint`. From 1.2.0, when omitted the SDK sends the one the other Coinme SDKs on this device share, or creates and shares one (see [Device fingerprint](https://platformdocs.coinme.com/docs/using-the-coinme-risk-sdk-for-web.md#device-fingerprint)); earlier releases require it | | customerId | string | ✅ | The customer ID, sent as the `accountId` query parameter | | additionalHeaders | `Record` | ✅ | Additional headers. Must include `x-partner-id` with the value provided by your Coinme integration contact. Example: `additionalHeaders: { 'X-Partner-ID': 'partner-123' }` | | timeout | number | optional | Request timeout in milliseconds (default: 10000) | **Returns:** - `Promise`: A promise that resolves with the session tag data containing `webSessionID` and `orgID`. The Sardine configuration is automatically updated with the `webSessionID` as the session key. **Example:** ```typescript import { getSessionTag } from "@coinme-security/risk-sdk-js"; const sessionData = await getSessionTag({ apiBaseUrl: 'https://api.example.com', // From 1.2.0 you may leave fingerprint out; earlier releases require it. customerId: 'customer-123', additionalHeaders: { 'x-partner-id': 'your-partner-id', }, }); // The webSessionID is automatically set in Sardine configuration const webSessionId = sessionData.webSessionID; const orgId = sessionData.orgID; ``` > **When to use?** > > Call this **right before each add-payment-method call and each order** to retrieve the session tag and automatically configure Sardine with the proper session key, then send the returned `webSessionID` as `webSessionId` on that call. A session tag lives 30 minutes from when it was issued, and using it doesn't extend that. > After calling `getSessionTag()`, the `webSessionID` becomes the stored session key. You do not need to pass it to subsequent `updateCoinmeRiskEngine()` calls — the SDK will automatically use it. If you need to override this behavior, explicitly pass a different `sessionKey` to `updateCoinmeRiskEngine()`. > **No token needed.** > > Don't pass an `authToken` or an `Authorization` header to `getSessionTag()`: this call authenticates with your `customerId` and `x-partner-id`. Never put your partner access token or client secret in the browser. ## 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`. ## Reading the session tag From 1.2.0, `getWebSessionId()` returns the session ID to send as `webSessionId`: the `webSessionID` from your last `getSessionTag()` call, or a session key you passed yourself. It returns `undefined` when there is none. Use it instead of `getCoinmeRiskEngineConfig().sessionKey`, which is deprecated for this: before a session tag exists, `sessionKey` holds a stand-in the SDK made up, which Coinme refuses. ## Verify Build and run the app. Confirm the Risk Engine initialises without an error, that a session tag is obtained with the headers the guide names right before each add-payment-method call and each order, that the submit call (where the SDK has one) completes right before a transaction call, and that no client ID or token is in a committed file. Hand back the privacy and store-listing items the guide requires. ### Reading the result **Done when:** Setup completes, a session tag comes back for the customer, and the same device fingerprint is sent on later Coinme calls from this device. **Stop and ask the human when** the client ID is refused, or the partner is unknown (`143-404-317-704`). 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 Risk SDK](https://platformdocs.coinme.com/docs/coinme-risk-sdk.md) - [Coinme Risk SDK for Web](https://platformdocs.coinme.com/docs/using-the-coinme-risk-sdk-for-web.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md) --- --- name: coinme-risk-ios description: "Add the Coinme Risk SDK to an iOS app: add the dependency, meet the App Store privacy and permission requirements, initialise the engine with the client ID, track inputs, and submit data before every transaction. Use when asked to add risk, fraud or device signals or the Coinme Risk Engine to an iOS, Swift or SwiftUI app." metadata: surface: "caas" package: "CoinmeRisk · Swift" version: "1.1.2" --- # Coinme Risk SDK on iOS ## When to use this skill The human wants Coinme's Risk Engine in an iOS app, which Coinme requires before any transactional service is used from the app. The Widget SDK carries its own risk signals; this skill is for a partner's own app and its own transaction calls. ## 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 that initialises the Risk Engine at launch with the client ID, tracks the inputs the guide names, gets a session tag right before each add-payment-method call and each order, and, where the SDK has a submit call, submits its data immediately before each transaction-initiating call to the backend, with the credentials kept out of source. ## 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. | | `clientId` | Identifies the integration to the Risk Engine; the SDK refuses to initialise without it. One per environment. Not a secret: it runs in the client, but the partner access token and client secret never go there with it. | Runtime configuration, not source; keep the development and production values apart. | | `Partner ID (and Ramp ID for Ramp partners)` | Identifiers the session-tag call carries so the Risk Engine attributes the session: on the web the x-partner-id (and x-ramp-id) headers in getSessionTag additionalHeaders; on iOS, Android and React Native the partnerId (and rampId) options of getPartnerSessionTag. | Runtime configuration passed to the SDK; never hard-coded. | ## 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 one exception is the Risk SDK's optional `x-ramp-id` header, which only a Ramp partner sends. - 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 Get the session tag right before each add-payment-method call and each order (getSessionTag on the web, getPartnerSessionTag on iOS, Android and React Native) and send it as webSessionId: a tag lives 30 minutes from when it was issued, using it doesn't extend that, and calling again while it is live returns the same tag. Never persist a tag across reloads or relaunches to reuse it. Pass the same device fingerprint to getPartnerSessionTag and as X-Device-Fingerprint on every other Coinme call for the user. Where the SDK has a submit call (submitCoinmeRiskData on React Native, CoinmeRiskEngine.submit on iOS and Android), make it immediately before every transaction-initiating server call. The guide's session-flow section is the contract. Store listings and privacy disclosures in the guide are requirements, not suggestions; include them in what you hand back. The Risk SDK takes no auth token from the app. In a partner app the session tag comes from the partner session-tag call (getPartnerSessionTag on iOS, Android and React Native; getSessionTag with the x-partner-id header on the web), which needs no token. Never pass the partner access token or a Transient Auth Token to the Risk SDK. ## 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 Risk SDK for iOS Native Apps ## Introduction The iOS Coinme Risk Engine SDK is a Swift library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions. > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme risk engine SDK. **What is it?** The Coinme risk engine aggregates data about user behavior for your application. It collects: - Device data such as the type of device, OS name and version, etc. - Location data such as where the user is connecting from. - Connection data such as if the user is using a proxy or VPN, etc. - Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, use of clipboard functions, etc. This data is used to determine the relative riskiness of the user / transaction. > **Why is Risk Tagging Important?** > > Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**. > > As an example, if the risk engine determines that the user location changes suddenly via a VPN to access a region restricted transaction type, then the engine may determine automation is at play and may **rank the transaction as high risk**. ## Implementing the iOS SDK > **This package is not public** > > You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact. ### What You'll Need to Get Started Before integrating the SDK, you will need the following credentials from your Coinme integration contact: | Credential | Required For | Notes | | --- | --- | --- | | Cloudsmith auth token | Accessing the library | Required to access the private library in Cloudsmith | | `clientId` | `RiskEngineSetupOptions` | Environment-specific — you will need one for development and one for production | | `partnerId` | `getPartnerSessionTag()` | Passed via `GetPartnerSessionTagOptions`, this is your Partner identifier needed for integration with Coinme APIs | > You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals. ### Installation #### Set Your Entitlement Token Create a `coinme.properties` file in your project root directory: ```properties COINME_TOKEN= ``` Replace `` with the token provided by your Coinme integration contact. Do not commit this file to version control. Important: Add `coinme.properties` to your `.gitignore` to keep your token secure: `coinmme.properties` ``` coinme.properties ``` #### Add the SDK Repository and Dependency to your project - CocoaPods Update your `Podfile`: `CocoaPods Setup` ```swift source 'https://github.com/CocoaPods/Specs.git' # Read token from properties file def read_token properties_file = File.join(File.dirname(__FILE__), 'coinme.properties') if File.exist?(properties_file) File.foreach(properties_file) do |line| key, value = line.split('=') return value.strip if key.strip == 'COINME_TOKEN' end end ENV['COINME_TOKEN'] || '' end token = read_token plugin 'cocoapods-cloudsmith', { 'source' => "https://packages.coinme.com/{COINME_TOKEN}/coinme-sdk-mobile/cocoapods/index.git" } target 'YourApp' do use_frameworks! pod 'CoinmeRiskSDK', '~> 1.1.2' end ``` `Environment Variable Setup` ```swift source 'https://github.com/CocoaPods/Specs.git' token = ENV['COINME_TOKEN'] || '' plugin 'cocoapods-cloudsmith', { 'source' => "https://packages.coinme.com/{COINME_TOKEN}/coinme-sdk-mobile/cocoapods/index.git" } target 'YourApp' do use_frameworks! pod 'CoinmeRiskSDK', '~> 1.1.2' end ``` If installing via an Environment Variable, you will also need to set the environment variable in your shell ```bash export COINME_TOKEN= ``` #### Add the SDK Repository and Dependency to your project - Swift Package Manager The SDK is also published to the Cloudsmith Swift Package Registry. Authenticate once with your entitlement token, then add the dependency. Configure and log in to the registry (one-time): ``` swift package-registry set https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ swift package-registry login https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ --token YOUR_ENTITLEMENT_TOKEN ``` Next, add the dependency in your `Package.swift`: ``` dependencies: [ .package(id: "coinme.CoinmeRiskSDK", from: "1.1.2"), ] ``` Or in Xcode: File > Add Package Dependencies… > Add from Registry and search for coinme.CoinmeRiskSDK. The package bundles MobileIntelligence (SardineSDK) — no extra dependency is required. ### App Store Requirements Before releasing your application with the Coinme Risk SDK, update your App Store Connect settings in your Apple developer portal. #### App Privacy — Data Collection In **App Store Connect > App Privacy**, declare the following: 1. **Data Collection:** Select **"Yes, we collect data from this app"** 2. **Location:** - Select **Coarse Location** and/or **Precise Location** (depending on your app settings) - Purpose: **App Functionality** - Reason: Required for fraud detection and prevention 3. **Identifiers — Device ID:** - Purpose: **App Functionality** - Check: **Yes, device ID is linked to user identity** #### Privacy Policy Update your App Store privacy policy to include the following disclosure: > **Required Privacy Policy Language** > > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, and location information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN or other location-spoofing tools. ### Required Permissions Add location permissions to your `Info.plist`: `Info.plist` ```swift ... NSLocationAlwaysAndWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. NSLocationWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. ``` This is a required permission for fraud detection and should be requested at runtime. Ensure your app handles the permission request appropriately for optimal risk assessment and to avoid issues from App Store Review. ### Implementation Privacy & Compliance Notice Important: If you use the Behavior Biometrics feature (enableBehaviourBiometrics = true), please ensure that your end users agree to your privacy policy before you begin collecting their Behavior Biometric data. This is required for compliance with privacy regulations. #### Configuration Options RiskEngineSetupOptions | Option | Type | Required | Description | | --- | --- | --- | --- | | `mode` | `Mode` | Yes | Used to point to environment `.Test` or `.Prod` | | `clientId` | `String` | Yes | Your environment-specific Client ID | | `partnerId` | `String?` | No | Partner Identifier | | `customerId` | `String?` | No | Customer/User's identifier | | `sessionKey` | `String?` | No | Session key (automatically generated if not provided) | | `flow` | `FlowType?` | No | Current User flow (Onboarding, CardTransaction, or CardLinking) | | `region` | `AppRegion` | No | Your app's region of service (`.default` (US), `.ca`, `.eu`, `.au`, `.in`) | | `enableBehaviourBiometrics` | `Bool` | No | Enabled behavior tracking (default: true) | | `enableClipboardTracking` | `Bool` | No | Enable clipboard tracking (default: false) | | `enableFieldTracking` | `Bool` | No | Enable automatic field tracking (default: true) | | `setCloudEntitlements` | `Bool` | No | Enable iCloud feature (default: false, requires additional setup) | #### FlowType Options - `FlowType.Onboarding` - New user registration flow - `FlowType.CardTransaction` - Payment/card transaction flow - `FlowType.CardLinking` - Adding payment methods flow #### sessionKey The `sessionKey` is a unique identifier for tracking a specific user session. Once a key is provided for the set up, it will be cached for the duration of the app's active session. If no value is provided, the key will be automatically generated. You will want to invoke `.getPartnerSessionTag()` to get an updated value that our backend will use to associate collected user data and risk score. Failure to call this and get the expected session key value may result in loss of data for accurate risk assessment. Call it right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that. Using `.updateCoinmeRiskEngine()` with a new key will override and update the cached value. To clear a `sessionKey`, you may call `.resetStoredSessionKey()` > When you call `getPartnerSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one. #### getPartnerSessionTag() Retrieve the session tag from the backend API. The resulting `webSessionID` is automatically used to update the `CoinmeRiskEngine` configuration. ```swift try await CoinmeRiskEngine.getPartnerSessionTag(options: GetPartnerSessionTagOptions) -> SessionTagData ``` Parameters of `GetPartnerSessionTagOptions`. The SDK sends them as request headers and a query parameter, to the host your `mode` selects: | Param | Type | Required | Description | | --- | --- | --- | --- | | `partnerId` | `String` | Yes | Your partner identifier, sent as the `partnerId` header | | `accountId` | `String` | Yes | The customer ID, sent as the `accountId` query parameter | | `fingerprint` | `String` | Yes | The device fingerprint, sent as the `X-Device-Fingerprint` header | | `rampId` | `String?` | No | Your Ramp ID, sent as the `X-ramp-id` header (Ramp partners only) | | `additionalHeaders` | `[String: String]` | No | Additional headers that may be included if needed by the backend | | `timeout` | `Int` | No | Request timeout in milliseconds (default: 10000) | #### Initialize the SDK Initialize the Risk Engine in your app's initialization: ```swift import CoinmeRiskSDK let options = RiskEngineSetupOptions( mode: .Prod, // Use .Test for testing clientId: "your-client-id", enableBehaviourBiometrics: true, enableFieldTracking: false // Set to false for manual tracking ) CoinmeRiskEngine.setupCoinmeRiskEngine(options: options) ``` #### Update the SDK You can update the configuration with flow, sessionKey and customerId options: ```swift CoinmeRiskEngine.updateCoinmeRiskEngine( RiskEngineUpdateOptions( sessionKey: "new-session-key", flow: .cardTransaction, customerId: "customer-id" ) ) ``` #### Submit Data Before Transactions Submits all collected behavioral and device date to the backend for risk assessment. Use callback version to ensure data is submitted before making subsequent API calls. ```swift CoinmeRiskEngine.submit( onSuccess: { // Data successfully submitted - safe to proceed with transaction API call processPayment() }, onError: { error in print("Risk SDK submission failed: \(error)") handleError(error) } ) ``` #### What it collects: - Sensor data (motion, orientation, pressure) - Behavioral biometrics (typing patterns, interaction timing) - Device context (clipboard activity, focus patterns) - Page/screen engagement metrics #### When to call: - Before payment/transaction API calls - Before critical actions (login, signup, money transfer) - After form completion or user interaction flow #### Other Utility Methods #### Get Current Config Returns the current runtime configuration. ```swift CoinmeRiskEngine.getCoinmeRiskEngineConfig() -> RiskEngineUpdateOptions ``` #### Reset Session Resets the stored session key. ```swift CoinmeRiskEngine.resetStoredSessionKey() ``` #### Reset SDK Clears the singleton instance and cleans up resources. ```swift CoinmeRiskEngine.reset() ``` #### Manual Input Field Tracking > If you choose to manually track input fields, first disabled automatic field tracking in the configuration. This can be done by ensuring `enableFieldTracking = false` when you set options for the `CoinmeRiskEngine`. How to set up custom `TextField` for tracking: `SwiftUI` ```swift import SwiftUI import CoinmeRiskSDK struct LoginView: View { @State private var email = "" @FocusState private var isEmailFocused: Bool var body: some View { TextField("Email", text: $email) .focused($isEmailFocused) .onChange(of: email) { newValue in CoinmeRiskEngine.trackTextChange(viewId: "email", text: newValue) } .onChange(of: isEmailFocused) { isFocused in CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: isFocused) } } } ``` `UIKit` ```swift // In your UIViewController class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() emailTextField.delegate = self } // UITextFieldDelegate - Track focus changes func textFieldDidBeginEditing(_ textField: UITextField) { CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: true) } func textFieldDidEndEditing(_ textField: UITextField) { CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: false) } // UITextFieldDelegate - Track text changes func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentText = textField.text ?? "" let newText = (currentText as NSString).replacingCharacters(in: range, with: string) CoinmeRiskEngine.trackTextChange(viewId: "email", text: newText) return true } } ``` Be descriptive when assigning a value for `viewId` ("email", "password", "debitCardNumber", etc) #### Tracking Methods Track text changes to an input field ```swift CoinmeRiskEngine.trackTextChange(viewId: String, text: String) ``` Track focus change to a field ```swift CoinmeRiskEngine.trackFocusChange(viewId: String, isFocus: Bool) ``` Note: Be sure to use the same `viewId` for both `trackTextChange()` and `trackFocusChange()` if they are used to reference the same text field or other custom UI component. #### Optional Features #### Enable Location Service Initialize Apple's LocationManager to provide live location updates: ```swift import CoreLocation class LocationService: NSObject, CLLocationManagerDelegate { let locationManager: CLLocationManager? override init() { locationManager = CLLocationManager() locationManager?.requestWhenInUseAuthorization() super.init() locationManager?.delegate = self } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) { if CLLocationManager.isRangingAvailable() { let latitude = manager.location?.coordinate.latitude let longitude = manager.location?.coordinate.longitude print("Location: \(latitude ?? 0), \(longitude ?? 0)") } } } } } ``` #### Enable Wi-Fi Information Tracking Wi-Fi BSSID and SSID can provide additional location signals. 1. Enable Location Services (required) 2. In Xcode: - Go to your target scheme - Click **Signing & Capabilities** - Click **+ Capability** - Add **Access WiFi Information** #### Enable iCloud Record ID iCloud Record ID remains consistent across devices that are associated with the same Apple account. 1. In Xcode 2. Set the flag in the SDK configuration: > DO NOT set `setCloudEntitlements` to true unless CloudKit is properly configured, or the SDK will crash. #### Enable Biometric Authentication Detection Detect the use of FaceID and TouchID Update your `Info.plist` ``` ... NSFaceIDUsageDescription Face ID is used to verify your identity. ``` ## Verify Build and run the app. Confirm the Risk Engine initialises without an error, that a session tag is obtained with the headers the guide names right before each add-payment-method call and each order, that the submit call (where the SDK has one) completes right before a transaction call, and that no client ID or token is in a committed file. Hand back the privacy and store-listing items the guide requires. ### Reading the result **Done when:** Setup completes and a session tag comes back for the customer on this device. **Stop and ask the human when** the client ID is refused, or the partner is unknown (`143-404-317-704`). 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 Risk SDK](https://platformdocs.coinme.com/docs/coinme-risk-sdk.md) - [Coinme Risk SDK for iOS Native Apps](https://platformdocs.coinme.com/docs/risk-sdk-for-ios-native-apps.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md) --- --- name: coinme-risk-android description: "Add the Coinme Risk SDK to an Android app: add the repository and dependency, meet the Google Play data-safety and permission requirements, configure ProGuard, initialise the engine with the client ID, track inputs, and submit data before every transaction. Use when asked to add risk, fraud or device signals or the Coinme Risk Engine to an Android or Kotlin app." metadata: surface: "caas" package: "CoinmeRisk · Kotlin" version: "1.1.2" --- # Coinme Risk SDK on Android ## When to use this skill The human wants Coinme's Risk Engine in an Android app, which Coinme requires before any transactional service is used from the app. The Widget SDK carries its own risk signals; this skill is for a partner's own app and its own transaction calls. ## 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 that initialises the Risk Engine at launch with the client ID, tracks the inputs the guide names, gets a session tag right before each add-payment-method call and each order, and, where the SDK has a submit call, submits its data immediately before each transaction-initiating call to the backend, with the credentials kept out of source. ## 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. | | `clientId` | Identifies the integration to the Risk Engine; the SDK refuses to initialise without it. One per environment. Not a secret: it runs in the client, but the partner access token and client secret never go there with it. | Runtime configuration, not source; keep the development and production values apart. | | `Partner ID (and Ramp ID for Ramp partners)` | Identifiers the session-tag call carries so the Risk Engine attributes the session: on the web the x-partner-id (and x-ramp-id) headers in getSessionTag additionalHeaders; on iOS, Android and React Native the partnerId (and rampId) options of getPartnerSessionTag. | Runtime configuration passed to the SDK; never hard-coded. | ## 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 one exception is the Risk SDK's optional `x-ramp-id` header, which only a Ramp partner sends. - 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 Get the session tag right before each add-payment-method call and each order (getSessionTag on the web, getPartnerSessionTag on iOS, Android and React Native) and send it as webSessionId: a tag lives 30 minutes from when it was issued, using it doesn't extend that, and calling again while it is live returns the same tag. Never persist a tag across reloads or relaunches to reuse it. Pass the same device fingerprint to getPartnerSessionTag and as X-Device-Fingerprint on every other Coinme call for the user. Where the SDK has a submit call (submitCoinmeRiskData on React Native, CoinmeRiskEngine.submit on iOS and Android), make it immediately before every transaction-initiating server call. The guide's session-flow section is the contract. Store listings and privacy disclosures in the guide are requirements, not suggestions; include them in what you hand back. The Risk SDK takes no auth token from the app. In a partner app the session tag comes from the partner session-tag call (getPartnerSessionTag on iOS, Android and React Native; getSessionTag with the x-partner-id header on the web), which needs no token. Never pass the partner access token or a Transient Auth Token to the Risk SDK. ## 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 Risk SDK for Android Native Apps ## Introduction The Android Coinme Risk Engine SDK is a Kotlin library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions. > In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme Risk Engine SDK. **What is it?** The Coinme Risk Engine aggregates data about user behavior for your application. It collects: - Device data such as the type of device, OS name and version, etc. - Location data such as where the user is connecting from. - Connection data such as if the user is using a proxy or VPN, etc. - Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, use of clipboard functions, etc. This data is used to determine the relative riskiness of the user / transaction. > **Why is Risk Tagging Important?** > > Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**. > > As an example, if the risk engine determines that the user location changes suddenly via a VPN to access a region restricted transaction type, then the engine may determine automation is at play and may **rank the transaction as high risk**. ## Implementing the Android SDK > **This package is not public** > > You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact. ### What You'll Need to Get Started Before integrating the SDK, you will need the following credentials from your Coinme integration contact: | Credential | Required For | Notes | | --- | --- | --- | | Cloudsmith auth token | Accessing the library | Required to access the private library in Cloudsmith | | `clientId` | `RiskEngineSetupOptions` | Environment-specific — you will need one for development and one for production | | `partnerId` | `getPartnerSessionTag()` | Passed via `GetPartnerSessionTagOptions`, this is your Partner identifier needed for integration with Coinme APIs | > You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals. ### Installation #### Set Your Entitlement Token Add your token to `local.properties` file in your project root directory: ```properties COINME_TOKEN= ``` Replace `` with the token provided by your Coinme integration contact. Note: `local.properties` is already gitignored by Android Studio to keep your tokens secure, but it is good to ensure this token is not exposed and the file is in your `.gitignore` #### Add the SDK Repository and Dependency to your project Add the repository to either your `settings.gradle` OR `build.gradle.kts` depending on your setup `settings.gradle` ```kotlin dependencyResolutionManagement { repositories { google() mavenCentral() maven { name = "CoinmeSDK" url = uri("https://dl.cloudsmith.io/${findProperty("COINME_TOKEN") ?: ""}/coinme/coinme-sdk-mobile/maven/") } } } ``` `build.gradle` ```kotlin allprojects { repositories { google() mavenCentral() maven { name = "CoinmeSDK" val token = project.findProperty("COINME_TOKEN")?.toString() ?: "" url = uri("https://dl.cloudsmith.io/$token/coinme/coinme-sdk-mobile/maven/") } } } ``` Then in your `app/build.gradle.kts` add the dependency `app/build.gradle.kts` ```kotlin dependencies { implementation("com.coinme:risk-sdk-android:1.1.2") } ``` ### Google Play Requirements Before releasing your application with the Coinme Risk SDK, update your Google Play settings in your developer portal. #### Privacy Policy Update your Google Play Store privacy policy with the following message: > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, MAC Address, and SIM information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN, VPN apps with location spoofing, or other related tools. #### Data Safety For the Data Safety section in the Google Play Console: 1. Navigate to App content > Data safety in your Play Console 2. Declare the following data types are collected: - Location (Approximate and Precise) - Device or other IDs (Device ID) - App info and performance (Crash logs, Diagnostics) - Files and docs (for storage-related fraud detection) Note: You may need to add any other data types your app collects beyond what the SDK requires. For easier setup, you can download and import the Data Safety CSV file from the Sardine SDK documentation if provided by your Coinme integration contact. ### Permissions Neither the Risk SDK nor the components it bundles declares permissions in its own manifest, so your app declares the ones it wants the SDK to use. Only `INTERNET` and `ACCESS_NETWORK_STATE` are needed for a transaction to be scored. Every other permission is optional: it enables an additional device, carrier or location signal, and if it is not declared, or the user does not grant it at runtime, that signal is skipped. Declare only the permissions you are willing to disclose in your Google Play Data Safety form (see above). #### Required permissions `AndroidManifest.xml` ```markup ``` #### Optional permissions `AndroidManifest.xml` ```markup ``` The external-storage permissions (`WRITE_EXTERNAL_STORAGE`, `READ_EXTERNAL_STORAGE`) are also optional. They are used for reinstall detection and storage size, and scoped storage on Android 10+ limits what they can reach. Confirm with your Coinme integration contact whether you need them. > Location and phone state are dangerous permissions on Android 6.0+ and require runtime permission requests, and declaring them is not enough: without the user's grant the SDK collects nothing from them. On Android 10+ identifiers such as IMEI and phone number are not available to regular apps, so `READ_PHONE_STATE` yields only carrier and network information. Permission usage: | Permission | Required | Usage | | --- | --- | --- | | `INTERNET` | Yes | Network communication for fraud detection | | `ACCESS_NETWORK_STATE` | Yes | Get user's network information and state | | `ACCESS_WIFI_STATE` | No | Get user's WiFi name and status | | `READ_PHONE_STATE` | No | Call status detection; phone and network info (MNC, MCC, phone type, SIM info) | | `READ_MEDIA_IMAGES` | No | Screenshot detection (Android 13+) | | `USE_BIOMETRIC` / `USE_FINGERPRINT` | No | Get user's biometric authentication settings (Face or Fingerprint) | | `ACCESS_COARSE_LOCATION` / `ACCESS_FINE_LOCATION` | No | Get user's GPS location for fraud detection | | `READ_GSERVICES` | No | Get Device GSF ID (Google Services Framework ID) | | `WRITE_EXTERNAL_STORAGE` / `READ_EXTERNAL_STORAGE` | No | Reinstall detection; external storage status and size | The SDK also adds a `` block to your merged manifest, which lets it detect whether certain apps are installed. Account for it in your Data Safety form. ### ProGuard Configuration If you use ProGuard or R8 for code obfuscation, add the following rules to your `proguard-rules.pro` file: ``` # Keep Google Play Services classes -keep class com.google.android.gms.** { *; } -keep class com.google.android.gms.tasks.** { *; } -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient { *; } # Keep Sardine SDK classes -keep class ai.sardine.** { *; } -keepclassmembers class ai.sardine.** { *; } ``` ### Implementation **Privacy & Compliance Notice** Important: If you use the Behavior Biometrics feature (enableBehaviourBiometrics = true), please ensure that your end users agree to your privacy policy before you begin collecting their Behavior Biometric data. This is required for compliance with privacy regulations. #### Configuration Options RiskEngineSetupOptions | Option | Type | Required | Description | | --- | --- | --- | --- | | `mode` | `Mode` | Yes | Used to point to environment `Mode.Test` or `Mode.Prod` | | `clientId` | `String` | Yes | Your environment-specific Client ID | | `partnerId` | `String?` | No | Partner Identifier | | `customerId` | `String?` | No | Customer/User's identifier | | `sessionKey` | `String?` | No | Session key (automatically generated if not provided) | | `flow` | `FlowType?` | No | Current User flow (Onboarding, CardTransaction, or CardLinking) | | `appRegion` | `AppRegion` | No | Your app's region of service (`AppRegion.DEFAULT` (US), `CA`, `EU`, `AU`, `IN`; default: `DEFAULT`) | | `enableBehaviourBiometrics` | `Boolean` | No | Enabled behavior tracking (default: true) | | `enableClipboardTracking` | `Boolean` | No | Enable clipboard tracking (default: false) | | `enableFieldTracking` | `Boolean` | No | Enable automatic field tracking (default: true) | #### FlowType Options - `FlowType.Onboarding` - New user registration flow - `FlowType.CardTransaction` - Payment/card transaction flow - `FlowType.CardLinking` - Adding payment methods flow #### sessionKey The `sessionKey` is a unique identifier for tracking a specific user session. Once a key is provided for the set up, it will be cached for the duration of the app's active session. If no value is provided, the key will be automatically generated. You will want to invoke `.getPartnerSessionTag()` to get an updated value that our backend will use to associate collected user data and risk score. Failure to call this and get the expected session key value may result in loss of data for accurate risk assessment. Call it right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that. Using `.updateCoinmeRiskEngine()` with a new key will override and update the cached value. To clear a `sessionKey`, you may call `.resetStoredSessionKey()` > When you call `getPartnerSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one. #### getPartnerSessionTag() Retrieve the session tag from the backend API. The resulting `webSessionID` is automatically used to update the `CoinmeRiskEngine` configuration. ```kotlin suspend CoinmeRiskEngine.getPartnerSessionTag(options: GetPartnerSessionTagOptions): SessionTagData ``` Parameters of `GetPartnerSessionTagOptions`. The SDK sends them as request headers and a query parameter, to the host your `mode` selects: | Param | Type | Required | Description | | --- | --- | --- | --- | | `partnerId` | `String` | Yes | Your partner identifier, sent as the `partnerId` header | | `accountId` | `String` | Yes | The customer ID, sent as the `accountId` query parameter | | `fingerprint` | `String` | Yes | The device fingerprint, sent as the `X-Device-Fingerprint` header | | `rampId` | `String?` | No | Your Ramp ID, sent as the `X-ramp-id` header (Ramp partners only) | | `additionalHeaders` | `Map` | No | Additional headers that may be included if needed by the backend | | `timeout` | `Long` | No | Request timeout in milliseconds (default: 10000) | ### Initialize the SDK Initialize the Risk Engine in your Activity's `onCreate()`: `mainActivity` ```kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val options = RiskEngineSetupOptions( mode = Mode.Prod, // Use Mode.Test for testing clientId = "your-client-id", enableBehaviourBiometrics = true, enableFieldTracking = false // Set to false for manual tracking ) CoinmeRiskEngine.setupCoinmeRiskEngine(this, options) } } ``` Note: Initializing the configuration automatically calls submit(), no need to do it manually. If you need to update the configuration, please use update() method. #### Update the SDK You can update the configuration with flow, sessionKey and customerId options: ```kotlin CoinmeRiskEngine.updateCoinmeRiskEngine( RiskEngineUpdateOptions( sessionKey = "new-session-key", flow = "new-flow", customerId = "customer-id") ``` #### Submit Data Before Transactions Submits all collected behavioral and device date to the backend for risk assessment. Use callback version to ensure data is submitted before making subsequent API calls. ```kotlin CoinmeRiskEngine.submit( onSuccess = { // Data successfully submitted - safe to proceed lifecycleScope.launch { processCardPayment() } }, onError = { error -> Log.e("RiskSDK", "Submission failed", error) handleError(error) } ) ``` #### What it collects: - Sensor data (motion, orientation, pressure) - Behavioral biometrics (typing patterns, interaction timing) - Device context (clipboard activity, focus patterns) - Page/screen engagement metrics #### When to call: - Before payment/transaction API calls - Before critical actions (login, signup, money transfer) - After form completion or user interaction flow #### Other Utility Methods #### Setup Risk Engine (Factory Method) Initializes the Risk Engine singleton. Safe to call multiple times - returns existing instance if already initialized. ```kotlin CoinmeRiskEngine.setupCoinmeRiskEngine( activity: Activity, options: RiskEngineSetupOptions ) ``` #### Update Configuration Updates the runtime configuration (customer ID, session key, flow). Note: This method may throw exceptions if the update fails. Wrap in try-catch for production: ```kotlin CoinmeRiskEngine.updateCoinmeRiskEngine(config: RiskEngineUpdateOptions) ``` #### Get Current Config Returns the current runtime configuration ```kotlin CoinmeRiskEngine.getCoinmeRiskEngineConfig(): RiskEngineUpdateOptions ``` #### Reset Session Resets the stored session key. ```kotlin CoinmeRiskEngine.resetStoredSessionKey() ``` #### Reset SDK Clears the singleton instance and cleans up resources. ```kotlin CoinmeRiskEngine.reset() ``` ### Manual Input Field Tracking > If you choose to manually track input fields, first disabled automatic field tracking in the configuration. This can be done by ensuring `enableFieldTracking = false` when you set options for the `CoinmeRiskEngine`. How to set up custom fields for tracking: `Kotlin` ```kotlin // Track text changes emailEditText.addTextChangedListener(object : TextWatcher { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { CoinmeRiskEngine.trackTextChange("email", s?.toString() ?: "") } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun afterTextChanged(s: Editable?) {} }) // Track focus changes emailEditText.setOnFocusChangeListener { _, hasFocus -> CoinmeRiskEngine.trackFocusChange("email", hasFocus) } ``` Be descriptive when assigning a value for `viewId` ("email", "password", "debitCardNumber", etc) #### Tracking Methods #### Track custom events and user interactions ```kotlin // Track a user action val data = JSONObject().apply { put("action", "card_transaction_started") put("amount", 149.99) put("currency", "USD") } CoinmeRiskEngine.trackCustomData(data) ``` Or use the Map extension for convenience ```kotlin val data = mapOf( "action" to "card_payment_initiated", "amount" to 299.99 ).toJSONObject() CoinmeRiskEngine.trackCustomData(data) ``` #### Track Text Change Track text input in a text field ```kotlin CoinmeRiskEngine.trackTextChange(viewId: String, text: String) ``` #### Track Focus Change Track focus change events on a field or UI component ```kotlin CoinmeRiskEngine.trackFocusChange(viewId: String, isFocus: Boolean) ``` **Note**: If referencing the same UI component but calling various tracking methods, make sure to use the same viewId. ## Verify Build and run the app. Confirm the Risk Engine initialises without an error, that a session tag is obtained with the headers the guide names right before each add-payment-method call and each order, that the submit call (where the SDK has one) completes right before a transaction call, and that no client ID or token is in a committed file. Hand back the privacy and store-listing items the guide requires. ### Reading the result **Done when:** Setup completes and a session tag comes back for the customer on this device. **Stop and ask the human when** the client ID is refused, or the partner is unknown (`143-404-317-704`). 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 Risk SDK](https://platformdocs.coinme.com/docs/coinme-risk-sdk.md) - [Coinme Risk SDK for Android Native Apps](https://platformdocs.coinme.com/docs/risk-sdk-for-android-native-apps.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md) --- --- name: coinme-risk-react-native description: "Add the Coinme Risk SDK to a React Native or Expo app: install the package and its native setup on both platforms, honour the fingerprint contract, use the tracked inputs, and submit data before every transaction. Use when asked to add risk, fraud or device signals or the Coinme Risk Engine to a React Native or Expo app." metadata: surface: "caas" package: "@coinme-security/risk-sdk-react-native" version: "1.1.0" peerDependencies: "react >=18, react-native >=0.72" --- # Coinme Risk SDK in React Native ## When to use this skill The human wants Coinme's Risk Engine in a React Native or Expo app, which Coinme requires before any transactional service is used from the app. The Widget SDK carries its own risk signals; this skill is for a partner's own app and its own transaction calls. ## 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 that initialises the Risk Engine at launch with the client ID, tracks the inputs the guide names, gets a session tag right before each add-payment-method call and each order, and, where the SDK has a submit call, submits its data immediately before each transaction-initiating call to the backend, with the credentials kept out of source. ## 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. | | `clientId` | Identifies the integration to the Risk Engine; the SDK refuses to initialise without it. One per environment. Not a secret: it runs in the client, but the partner access token and client secret never go there with it. | Runtime configuration, not source; keep the development and production values apart. | | `Partner ID (and Ramp ID for Ramp partners)` | Identifiers the session-tag call carries so the Risk Engine attributes the session: on the web the x-partner-id (and x-ramp-id) headers in getSessionTag additionalHeaders; on iOS, Android and React Native the partnerId (and rampId) options of getPartnerSessionTag. | Runtime configuration passed to the SDK; never hard-coded. | ## 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 one exception is the Risk SDK's optional `x-ramp-id` header, which only a Ramp partner sends. - 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 Get the session tag right before each add-payment-method call and each order (getSessionTag on the web, getPartnerSessionTag on iOS, Android and React Native) and send it as webSessionId: a tag lives 30 minutes from when it was issued, using it doesn't extend that, and calling again while it is live returns the same tag. Never persist a tag across reloads or relaunches to reuse it. The device fingerprint is optional from 1.1.0: the Coinme SDKs share one. The app reads it with getDeviceFingerprint() and sends it to its server with each request; never call getDeviceFingerprint() on the server. Where the SDK has a submit call (submitCoinmeRiskData on React Native, CoinmeRiskEngine.submit on iOS and Android), make it immediately before every transaction-initiating server call. The guide's session-flow section is the contract. Store listings and privacy disclosures in the guide are requirements, not suggestions; include them in what you hand back. The Risk SDK takes no auth token from the app. In a partner app the session tag comes from the partner session-tag call (getPartnerSessionTag on iOS, Android and React Native; getSessionTag with the x-partner-id header on the web), which needs no token. Never pass the partner access token or a Transient Auth Token to the Risk SDK. ## 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 Risk SDK for React Native > Real-time fraud detection and risk assessment for React Native apps; a thin native-module bridge over Coinme's production iOS and Android risk SDKs, exposed as a typed JS/TS API. **Package:** `@coinme-security/risk-sdk-react-native` **Version:** `1.0.1` **License:** Proprietary — Coinme, Inc. ## What this SDK is `@coinme-security/risk-sdk-react-native` is the React Native binding for the Coinme Risk Engine. It wraps Coinme's native iOS (`risk-sdk-ios`) and Android (`risk-sdk-android`) SDKs via a thin React Native native-module bridge and exposes a single typed JS/TS API that matches its sibling SDKs. One npm package. One native module name. One consumer-facing API. If you're already using `@coinme-security/risk-sdk-js` on web or the native iOS / Android SDKs, this is the RN port of the same conceptual model: > **setup → get session tag → update → submit data before each transaction-initiating server call** > > ### What it collects The native engine collects a layered set of signals from the user's session: - **Behavioral biometrics** — typing cadence, interaction timing, touch patterns - **Sensor data** — motion, orientation, device pressure - **Device context** — clipboard activity, focus patterns, screen engagement - **Device fingerprinting** — device identifiers, network state, SIM info (Android), location (with user consent) - **Field interactions** — text changes and focus events on tracked inputs Those signals are flushed to Coinme's Risk Engine when you call `submitCoinmeRiskData()`. Coinme's transaction services consume the signals internally when evaluating the transactions your app initiates. ## Why does Risk SDK exist? Coinme uses real-time behavioral risk signals as part of how we evaluate whether to process or reject a transaction. The Risk SDK is the mechanism that collects those signals on-device and correlates them — via a device fingerprint every Coinme SDK in your app shares — to the server calls they belong to. > **Integration is required.** > > Partners cannot use Coinme's transactional services without integrating the Risk SDK on every surface that initiates a transaction. Transactions unsupported by risk metrics will be rejected outright. **Your responsibilities as an integrator:** - Send the device fingerprint the Coinme SDKs share on your own backend calls (see section 9) - Call `submitCoinmeRiskData()` before every transaction-initiating server request (see section 12) - Handle privacy policy disclosures and store-listing compliance (see section 14) ## How does the Risk SDK work? ``` ┌──────────────────────────────────────────────────────────────┐ │ Your React Native app │ │ │ │ ┌────────────────────────────────────────────────────┐ │ │ │ @coinme-security/risk-sdk-react-native (JS/TS) │ │ │ │ setupCoinmeRiskEngine / updateCoinmeRiskEngine │ │ │ │ getPartnerSessionTag │ │ │ │ submitCoinmeRiskData / CoinmeTrackedTextInput │ │ │ └───────────────────────┬────────────────────────────┘ │ │ │ RN bridge │ │ ┌───────────────────────┴────────────────────────────┐ │ │ │ Native module: CoinmeRiskEngine │ │ │ │ ├── iOS: risk-sdk-ios (xcframework) │ │ │ │ └── Android: risk-sdk-android (aar) │ │ │ └────────────────────┬───────────────────────────────┘ │ └───────────────────────┼──────────────────────────────────────┘ │ ▼ Coinme Risk Engine ◀── session tag + signals │ ▼ Consumed by Coinme's transaction services during evaluation of customer transaction requests ``` The JS layer forwards typed calls across the bridge to the native engine, which does the actual signal collection. The public API mirrors `CoinmeRiskEngine` on iOS and Android, so integration code looks the same across all three platforms. **The signals are consumed by Coinme's internal transaction services, not returned to partners.** The SDK submits behavioral, device, and interaction data to the Risk Engine, which Coinme uses as part of its decision to process or reject a transaction. Risk scores and the underlying signals are not exposed to partner backends. ## Compatibility | Requirement | Supported | | --- | --- | | Node | 20.9+ | | React | 18+ | | React Native | 0.72 – 0.81 (see note below) | | iOS | 16.0+ (required by the underlying `CoinmeRiskSDK` xcframework) | | Android | `minSdkVersion` 24+ (Android 7.0 Nougat) | | Expo | ✅ SDK 51+ (managed workflow with `expo prebuild`) — see [Expo support](https://platformdocs.coinme.com/docs/coinme-risk-sdk-for-react-native.md#expo-support) | > **React Native 0.82+ is not yet supported.** > > The bridge targets RN's legacy (bridge) architecture; TurboModule support is planned but has not landed. RN 0.82 defaults the New Architecture ON and removes the off-switch. **Pin to 0.81 or older until TurboModule support ships.** ## Obtaining access The Risk SDK is distributed privately. You need a **Coinme Cloudsmith entitlement token** — a single credential that authenticates three things: 1. The private npm registry at `npm.coinme.com` (for the JS package) 2. The CocoaPods repository (for the iOS native artifact) 3. The Maven repository (for the Android native artifact) One token covers all three. If you don't already have one, ask your Coinme integration contact — this is not a self-serve credential. Throughout this guide, the token is referred to as `CLOUDSMITH_TEAM_TOKEN`. Export it as an environment variable before any build step: ``` export CLOUDSMITH_TEAM_TOKEN= ``` For persistence across shells, also add it to: - `~/.gradle/gradle.properties` (covers Gradle) - Your shell rc file (`/.zshrc`, `/.bashrc`, etc. — covers CocoaPods) **Do not commit the token to version control.** Use CI secrets for automated builds. ## Installation ### 1. Install the npm package The package is hosted on Coinme's private npm registry. Configure the scope before installing. **For npm / Yarn Classic**, add to `.npmrc` at your repo root: ```bash @coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/ //npm.coinme.com/coinme-security-wrapper/:_authToken=${CLOUDSMITH_TEAM_TOKEN} always-auth=true ``` **For Yarn Berry (v2+)**, add to `.yarnrc.yml`: ```bash nodeLinker: node-modules npmScopes: coinme-security: npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/' npmAuthToken: '${CLOUDSMITH_TEAM_TOKEN}' ``` Then install: ```bash export CLOUDSMITH_TEAM_TOKEN= yarn add @coinme-security/risk-sdk-react-native # or npm install @coinme-security/risk-sdk-react-native ``` Autolinking will discover this package automatically — you do not need to register the native module by hand on either platform. ### 2. iOS setup Three things to do in `ios/Podfile`: 1. **Add the Cloudsmith and CocoaPods CDN sources at the very top of the file.** Use double quotes so Ruby interpolates the env var: ```bash source "https://dl.cloudsmith.io/#{ENV['CLOUDSMITH_TEAM_TOKEN']}/coinme/coinme-sdk-mobile/cocoapods/index.git" source "https://cdn.cocoapods.org/" ``` 1. **Set the iOS deployment target.** `CoinmeRiskSDK` requires iOS 16+ and RN's default is lower: ```bash platform :ios, '16.0' ``` 1. **Disable the New Architecture** by passing `new_arch_enabled: false` to `use_react_native!` (or set `RCT_NEW_ARCH_ENABLED=0` at install time). Inside the main `target '' do` block, confirm `use_frameworks! :linkage => :static` is present (most modern RN templates include this). Then install: ```bash export CLOUDSMITH_TEAM_TOKEN= cd ios && pod install ``` Autolinking picks up the package's podspec automatically. You do **not** add a `pod '...'` line yourself. ### 3. Android setup **Step 1 — Add Coinme's Cloudsmith Maven repo.** In `android/settings.gradle` (or `.kts`), add a `dependencyResolutionManagement` block. Read the token from the environment rather than committing it: ```kotlin def cloudsmithToken = System.getenv('CLOUDSMITH_TEAM_TOKEN') ?: '' dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) repositories { google() mavenCentral() maven { name = "CoinmeSDK" url = uri("https://dl.cloudsmith.io/${cloudsmithToken}/coinme/coinme-sdk-mobile/maven/") } } } ``` > If your template uses `allprojects { repositories { … } }` in the root `build.gradle` instead of `dependencyResolutionManagement` (common on RN 0.72–0.75), add the same Maven block there. **Step 2 — Force Kotlin 2.3.0.** `risk-sdk-android` is compiled with Kotlin 2.3.0. React Native's Gradle plugin pins an older version, which causes this build failure: > Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 2.3.0, expected version is 2.1.x. In `android/build.gradle`, set `kotlinVersion` to `2.3.0`, pin the plugin explicitly, and add resolution strategies in **both** `buildscript` and `allprojects`: ```kotlin buildscript { ext { buildToolsVersion = "35.0.0" minSdkVersion = 24 compileSdkVersion = 35 targetSdkVersion = 35 ndkVersion = "27.1.12297006" kotlinVersion = "2.3.0" // ← must be 2.3.0 } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}") } // Force Kotlin 2.3.0 for classpath dependencies configurations.classpath { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'org.jetbrains.kotlin') { details.useVersion kotlinVersion } } } } // Force Kotlin stdlib 2.3.0 for all subprojects allprojects { configurations.all { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'org.jetbrains.kotlin' && details.requested.name.startsWith('kotlin-stdlib')) { details.useVersion rootProject.ext.kotlinVersion } } } } apply plugin: "com.facebook.react.rootproject" ``` > `allprojects` must be at the **root level** of `build.gradle`, not nested inside `buildscript`. **Step 3 — Disable the New Architecture.** In `android/gradle.properties`: ```kotlin newArchEnabled=false ``` **Step 4 — Build.** ```bash export CLOUDSMITH_TEAM_TOKEN= cd android && ./gradlew clean ``` Autolinking links the module; you do **not** add an `implementation("com.coinme:...")` line yourself. ## Platform configuration ### 1. Android permissions Add these to `AndroidManifest.xml`: ```markup ``` **Usage reference:** | Permission | Usage | | --- | --- | | `INTERNET` | Network communication for fraud detection | | `ACCESS_COARSE_LOCATION` / `ACCESS_FINE_LOCATION` | Location signals for fraud detection | | `ACCESS_WIFI_STATE` | WiFi name and status | | `ACCESS_NETWORK_STATE` | Network information and state | | `READ_PHONE_STATE` | Phone/network info (MNC, MCC, IMEI, phone number, phone type, SIM number) | | `USE_BIOMETRIC` / `USE_FINGERPRINT` | Biometric authentication settings (Face / Fingerprint) | | `WRITE_EXTERNAL_STORAGE` | Write data to check re-installation behavior | | `READ_EXTERNAL_STORAGE` | External storage status, total size, free size | | `READ_GSERVICES` | Device GSF ID (Google Services Framework ID) | > Location and phone-state permissions are **dangerous permissions** on Android 6.0+ and require runtime permission requests. Handle the flow in your app. ### 2. Android ProGuard / R8 If you use ProGuard or R8 for code obfuscation, add these rules to `proguard-rules.pro`: ```bash # Keep Google Play Services classes -keep class com.google.android.gms.** { *; } -keep class com.google.android.gms.tasks.** { *; } -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient { *; } # Keep Sardine SDK classes -keep class ai.sardine.** { *; } -keepclassmembers class ai.sardine.** { *; } ``` ### 3. Google Play Console requirements Before releasing your app with the Risk SDK: **Privacy Policy** — update your Play Store privacy policy with the following disclosure: > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, MAC Address, and SIM information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN, VPN apps with location spoofing, or other related tools. **Data Safety declaration** — in the Play Console, go to **App content → Data safety** and declare these collected data types: - **Location** (Approximate and Precise) - **Device or other IDs** (Device ID) - **App info and performance** (Crash logs, Diagnostics) - **Files and docs** (for storage-related fraud detection) > Add any other data types your app collects beyond what the SDK requires. Your Coinme integration contact may provide a Data Safety CSV you can import directly. ### 4. iOS Info.plist keys Location permissions are required. Add to `Info.plist`: ```swift NSLocationAlwaysAndWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. NSLocationWhenInUseUsageDescription We use your location to verify transactions and prevent fraud. ``` If you also want Face ID signal detection: ```swift NSFaceIDUsageDescription Face ID is used to verify your identity. ``` **Optional iOS capabilities** (added via Xcode → Signing & Capabilities): - **Access WiFi Information** — required for WiFi BSSID/SSID as an additional location signal. Requires location services to be enabled first. - **iCloud + CloudKit** — enables iCloud record ID (consistent across devices on the same Apple account). If you add this capability, you must set `setCloudEntitlements: true` in the setup options. **Do not enable** `setCloudEntitlements` **without adding the CloudKit capability — the underlying native SDK will crash.** ### 5. App Store Connect requirements Before releasing, update **App Store Connect → App Privacy**: 1. **Data Collection** — select "Yes, we collect data from this app" 2. **Location** — select Coarse and/or Precise Location. Purpose: App Functionality. Reason: "Required for fraud detection and prevention." 3. **Identifiers → Device ID** — Purpose: App Functionality. Check "Yes, device ID is linked to user identity." **Privacy Policy** — update your App Store privacy policy with the following disclosure: > For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, and location information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN or other location-spoofing tools. ## Quickstart The canonical flow: > `setupCoinmeRiskEngine` **→** `getPartnerSessionTag` **→** `updateCoinmeRiskEngine` **with the returned** `webSessionID` **→** `submitCoinmeRiskData` **→ your server call.** ```typescript import { getDeviceFingerprint, getPartnerSessionTag, setupCoinmeRiskEngine, submitCoinmeRiskData, updateCoinmeRiskEngine, } from '@coinme-security/risk-sdk-react-native'; // 1. Initialise the engine first — before any session-tag call. await setupCoinmeRiskEngine({ mode: 'prod', clientId: 'your-client-id', customerId: 'customer-123', }); // 2. Right before the payment-method or order call, fetch the session tag // (requires the engine to be initialised). Tags live 30 minutes. // Partner apps use getPartnerSessionTag; it takes no auth token. const { webSessionID } = await getPartnerSessionTag({ partnerId: 'your-partner-id', customerId: 'customer-123', rampId: 'optional-ramp-id', // From 1.1.0 fingerprint is optional: the shared device fingerprint is sent for you. }); // 3. Bind the session key to the running engine. await updateCoinmeRiskEngine({ sessionKey: webSessionID }); // 4. Flush signals before the transaction-initiating server call. await submitCoinmeRiskData(); // 5. Make the server call with the fingerprint every Coinme SDK sends. await fetch('https://api.coinme.com/transactions', { headers: { 'x-device-fingerprint': await getDeviceFingerprint() }, // ... }); ``` `getPartnerSessionTag` resolves its URL automatically from the `mode` you passed to `setupCoinmeRiskEngine`. It needs your partner ID and no token. > **The Risk SDK takes no auth token from your app.** > > In a partner app, always get the session tag with `getPartnerSessionTag`. Never pass your partner access token (from `POST /services/authorize`) or a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) to the Risk SDK. ## The fingerprint contract The fingerprint sent with `getPartnerSessionTag` **MUST be byte-identical** to the `x-device-fingerprint` header on every other Coinme call for the same user in the same launch of your app: the calls the other Coinme SDKs make and your own backend calls. It only has to match within a launch; it is not a permanent device ID. **Mismatched fingerprints get calls refused.** Adding a payment method and placing orders fail with `WEB_SESSION_ID_MISMATCH`. ### The SDK keeps the fingerprint for you From release 1.1.0 you don't have to generate or store a fingerprint, and `fingerprint` is optional. The SDK uses the value you pass; otherwise the one another Coinme SDK already shared in your app; otherwise it creates one and shares it. It keeps the value in native storage, so the same value survives relaunches. Import the Risk SDK at the top of your app's entry file (for example `index.js`), so it loads the stored value before the other Coinme SDKs need it: ```typescript // index.js import '@coinme-security/risk-sdk-react-native'; ``` If you already have a device ID of your own, such as `getUniqueId()` from `react-native-device-info`, you can keep passing it as `fingerprint`; it becomes the shared value. Pass it to the Risk SDK before the other Coinme SDKs make a call, or pass the same value to all of them. A `:` in it is replaced with `-`. With a release older than 1.1.0, `fingerprint` is required: pass one value to `getPartnerSessionTag` and send the same value as `x-device-fingerprint` on your other calls. ### Sending it on your own calls `getDeviceFingerprint()` returns a Promise of the shared value. Read it in the app and send it to your server with each request; route your HTTP client through it so the value never drifts: ```typescript // src/api/fetch.ts import { getDeviceFingerprint } from '@coinme-security/risk-sdk-react-native'; export const apiFetch = async (url: string, init: RequestInit = {}) => fetch(url, { ...init, headers: { ...(init.headers as Record), 'x-device-fingerprint': await getDeviceFingerprint(), }, }); ``` ## Lifecycle The three calls you need to think about: ``` App start ─▶ setupCoinmeRiskEngine ◀── no sessionKey needed yet │ ▼ getPartnerSessionTag (returns webSessionID) │ ▼ updateCoinmeRiskEngine ◀── sessionKey = webSessionID (also: customerId, flow, …) │ ▼ submitCoinmeRiskData ◀── before every transaction-initiating call │ ▼ your server call (x-device-fingerprint header) ``` 1. **Setup once per app session.** `sessionKey` is optional at setup — the native SDK auto-generates one if omitted. After calling `getPartnerSessionTag`, pass the returned `webSessionID` to `updateCoinmeRiskEngine`. Call `getPartnerSessionTag` again right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that. 2. **Update whenever context changes.** - User logs in → `updateCoinmeRiskEngine({ customerId })` - User starts a high-risk flow → `updateCoinmeRiskEngine({ flow: FlowType.CardTransaction })` Cached config is merged, not replaced. The underlying native SDK auto-submits on update. 1. **Submit before every transaction-initiating server call.** Forgetting this produces no error at the SDK layer — signals are collected but never flushed — and the downstream transaction will be rejected by Coinme's services. **On session rotation** (logout, account switch), call `clearSessionKey()` and start the cycle over with a fresh `getPartnerSessionTag`. ## Tracking user input ### `` — the recommended path A drop-in replacement for React Native's `TextInput`. Wires `onChangeText` / `onFocus` / `onBlur` to the native risk engine under a stable `riskIdentifier`, and forwards every other prop — including your own callbacks and refs — unchanged. ```typescript import { useState } from 'react'; import { CoinmeTrackedTextInput } from '@coinme-security/risk-sdk-react-native'; export const LoginForm = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); return ( <> ); }; ``` Works in both controlled and uncontrolled mode. Your own `onChangeText` / `onFocus` / `onBlur` are still invoked. ### Raw trackers (escape hatches) For custom components or imperative flows where `CoinmeTrackedTextInput` doesn't fit: ```typescript import { trackRiskFocusChange, trackRiskTextChange, } from '@coinme-security/risk-sdk-react-native'; await trackRiskTextChange('coupon_code', value); await trackRiskFocusChange('coupon_code', true); ``` **Rules:** - Use the same `riskIdentifier` for both the text and focus calls on a given field - Use descriptive, stable identifiers: `"email"`, `"password"`, `"cardNumber"` — not `"input1"` - Prefer `CoinmeTrackedTextInput` when you can — it handles the wiring for you > **No page tracking.** > > The iOS and Android SDKs don't expose a page-tracking primitive, and this package matches that. There is no `trackRiskPage` or `useTrackCoinmeRiskPage` export. ## When to submit data `submitCoinmeRiskData()` flushes the in-memory buffer of collected signals to the Risk Engine. It is what makes the signals available to Coinme's transaction services for evaluation. ### Call it before every transaction-initiating server call Examples of calls that require a preceding `submitCoinmeRiskData()`: - Payment and card charge endpoints - Wallet transfers and crypto transactions - Onboarding and KYC submissions - Adding or updating payment methods - Money transfers and withdrawals If you are unsure whether a given endpoint requires risk signals, assume it does. Transactions that reach Coinme's services without correlated risk data will be rejected. ### What gets submitted - Behavioral biometrics (typing patterns, interaction timing) - Sensor data (motion, orientation, device position) - Device context (clipboard, focus patterns, screen time) - All tracked field interactions ### Operational notes - **Safe to call multiple times** — the latest collected data is sent each time - **Always await it** before the server call it precedes - **Submit failures are not automatically retried** — if the call rejects, the subsequent transaction will not have correlated signals and will be rejected by Coinme's services ```typescript try { await submitCoinmeRiskData(); await processPayment(); } catch (err) { console.error('Risk subtumit failed', err); // The subsequent transaction will not have correlated signals — do not proceed. } ``` ## API reference All exports are named. There are no default exports. ### Functions | Export | Description | | --- | --- | | `setupCoinmeRiskEngine` | Initialize the native Risk Engine. `sessionKey` is optional — omit at setup, then pass the `webSessionID` from the session-tag call via `updateCoinmeRiskEngine`. | | `updateCoinmeRiskEngine` | Merge config updates (`customerId`, `flow`, `sessionKey`, …) into the cached session. Throws if called before setup. | | `getCoinmeRiskEngineConfig` | Returns the locally cached config. Never round-trips to native. | | `clearSessionKey` | Clears the in-memory session key. Use on logout / account switch. | | `submitCoinmeRiskData` | Flushes collected signals to the Risk Engine. Call before every transaction-initiating server request. | | `getPartnerSessionTag` | Calls Coinme's public partner session-tag endpoint. URL is auto-resolved from `mode`. | | `getDeviceFingerprint` | From 1.1.0. Returns a Promise of the device fingerprint the Coinme SDKs in your app share. | | `getWebSessionId` | From 1.1.0. Returns the session ID to send as `webSessionId`: the `webSessionID` from the last session-tag call, or `undefined`. | | `trackRiskTextChange` | Imperative text-change tracker. | | `trackRiskFocusChange` | Imperative focus / blur tracker. | ### Components | Export | Description | | --- | --- | | `CoinmeTrackedTextInput` | `TextInput` wrapper that tracks change / focus / blur by `riskIdentifier`. Forwards all other props unchanged. | ### Enums and types | Type | Description | | --- | --- | | `FlowType` | Enum — `Onboarding`, `CardTransaction`, `CardLinking`. | | `Mode` | `'test' \| 'prod'`. | | `AppRegion` | `'default' \| 'eu' \| 'ca' \| 'in' \| 'au'`. Mirrors the native SDKs. | | `RiskEngineSetupOptions` | Options for `setupCoinmeRiskEngine`: `mode`, `clientId`, `sessionKey?`, `flow?`, `customerId?`, `partnerId?`, `region?`, `enableBehaviorBiometrics?`, `enableClipboardTracking?`, `enableFieldTracking?`. | | `RiskEngineUpdateOptions` | Partial update shape: `sessionKey?`, `flow?`, `customerId?`, … | | `RiskEngineConfig` | Shape of the cached config returned from `getCoinmeRiskEngineConfig`. | | `GetPartnerSessionTagOptions` | Options for `getPartnerSessionTag`: `partnerId`, `customerId`, `fingerprint?`, `rampId?`, `timeout?`, `additionalHeaders?`. | | `SessionTagData` | `{ webSessionID: string; orgID?: string }`. | | `CoinmeTrackedTextInputProps` | Extends React Native's `TextInputProps` with a required `riskIdentifier: string`. | ### Setup options in detail | Option | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `mode` | `Mode` | Yes | — | `'test'` or `'prod'` | | `clientId` | `string` | Yes | — | Your Coinme-issued client ID | | `partnerId` | `string` | No | — | Partner identifier (distinct from `clientId`) | | `customerId` | `string` | No | — | Customer / user identifier | | `sessionKey` | `string` | No | auto | Session key — auto-generated if omitted | | `flow` | `FlowType` | No | — | `Onboarding`, `CardTransaction`, or `CardLinking` | | `region` | `AppRegion` | No | default | `default` (US), `eu`, `ca`, `au`, `in` | | `enableBehaviorBiometrics` | `boolean` | No | `true` | Enable behavioral biometrics collection | | `enableClipboardTracking` | `boolean` | No | `false` | Enable clipboard activity tracking | | `enableFieldTracking` | `boolean` | No | `true` | Enable automatic field tracking | > `clientId` and `partnerId` are **different values**. Do not use them interchangeably. ### Platform parity This package's public API mirrors the `CoinmeRiskEngine` surface of `risk-sdk-ios` and `risk-sdk-android` — the same lifecycle, the same option names, the same two session-tag variants. If you maintain a native iOS or Android app alongside an RN app, your integration code will look the same in all three. ## Privacy & compliance ### User consent for behavior biometrics If `enableBehaviorBiometrics` is `true` (the default), ensure users have agreed to your privacy policy **before** collecting any biometric data. This is required for GDPR, CCPA, and equivalent privacy regulations. One way to handle this is to defer `setupCoinmeRiskEngine` until consent is recorded on first launch, or to initialise with `enableBehaviorBiometrics: false` and flip it later via `updateCoinmeRiskEngine`. The right approach depends on your app's consent flow — check with your legal and compliance teams. ### Privacy policy disclosures Update your app's privacy policy to disclose data collection for fraud protection. The required disclosure text is in section 7.3 (Android) and section 7.5 (iOS). ### Store-listing requirements - **Google Play** — declare data types in the Data Safety section (see section 7.3) - **App Store** — declare data types in App Privacy (see section 7.5) Your Coinme integration contact may provide pre-filled CSV imports for both. ## Expo support Step-by-step instructions for adding `@coinme-security/risk-sdk-react-native` to an existing Expo app (managed workflow with `expo prebuild`). ### Prerequisites - Expo SDK 51+ - iOS deployment target 16.0+ (set automatically by the plugin) - Android `minSdkVersion` 24+ - `CLOUDSMITH_TEAM_TOKEN` — the Cloudsmith entitlement token provided by Coinme during onboarding. Ask your Coinme integration contact if you don't have it. ### Before you begin — export your token Export `CLOUDSMITH_TEAM_TOKEN` once at the start of your terminal session. All subsequent commands in this guide (package install, `pod install`, Gradle build) will pick it up automatically. ```bash export CLOUDSMITH_TEAM_TOKEN= ``` ### 1. Install the JS package The package is hosted on a private Cloudsmith npm registry. Configure the scope before installing by adding the registry to your project's config file at the repo root. `.npmrc` (npm / Yarn Classic): ```bash @coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/ //npm.coinme.com/coinme-security-wrapper/:_authToken=${CLOUDSMITH_TEAM_TOKEN} ``` `.yarnrc.yml` (Yarn Berry v2+): ```yaml nodeLinker: node-modules npmScopes: coinme-security: npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/' npmAuthToken: '${CLOUDSMITH_TEAM_TOKEN}' ``` Then install: ```bash yarn add @coinme-security/risk-sdk-react-native ``` ### 2. Add the config plugin Add the plugin to your Expo config. No options are required — native credentials are resolved from `CLOUDSMITH_TEAM_TOKEN` at build time, not stored in the config. `app.json`: ```json { "expo": { "plugins": [ "@coinme-security/risk-sdk-react-native" ] } } ``` `app.config.js` (if you use a dynamic config): ```javascript export default { // ... plugins: [ '@coinme-security/risk-sdk-react-native', ], }; ``` ### 3. Build and run The plugin applies all native changes automatically during prebuild. You do not need to manually edit any native files. | Platform | What the plugin configures | | --- | --- | | iOS `Podfile` | Adds Cloudsmith CocoaPods source (token read at `pod install` time via `ENV.fetch`) | | iOS `Podfile` | Sets deployment target to `16.0` | | Android `build.gradle` | Adds Cloudsmith Maven repository (token read at build time via `System.getenv`) | | Android `build.gradle` | Forces Kotlin 2.3.0 and adds resolution strategies | **iOS:** ```bash npx expo run:ios ``` **Android:** ```bash npx expo run:android ``` These commands run `expo prebuild` (if needed), `pod install` / Gradle build, and launch on device. Because `CLOUDSMITH_TEAM_TOKEN` is already exported, no extra steps are required. > To regenerate native directories from scratch, run `expo prebuild --clean` before `npx expo run:ios` / `npx expo run:android`. ### 4. JS integration #### 4a. Initialization sequence The native engine must be initialized **before** calling `getPartnerSessionTag`. Use `setupCoinmeRiskEngine` first, then fetch the session tag and update the engine with it: ```typescript import { setupCoinmeRiskEngine, getPartnerSessionTag, updateCoinmeRiskEngine, FlowType, } from '@coinme-security/risk-sdk-react-native'; // Step 1 — initialize the native engine await setupCoinmeRiskEngine({ mode: 'test', // 'test' | 'prod' clientId: CLIENT_ID, partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, flow: FlowType.Onboarding, enableFieldTracking: true, enableBehaviorBiometrics: true, }); // Step 2 — right before each add-payment-method call and each order, get the // session tag (requires the engine to be initialized). Tags live 30 minutes. const tag = await getPartnerSessionTag({ partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, }); // Step 3 — bind the session key to the running engine await updateCoinmeRiskEngine({ sessionKey: tag.webSessionID }); ``` > `CLIENT_ID` and `CAAS_PARTNER_ID` are **different values**. Do not use them interchangeably. #### 4b. Tracked input fields Replace standard `TextInput` components with `CoinmeTrackedTextInput` to forward keystrokes and focus events to the native SDK: ```typescript import { CoinmeTrackedTextInput } from '@coinme-security/risk-sdk-react-native'; ``` `riskIdentifier` is a stable string label that the SDK uses to associate events with a specific field. ### 5. Complete integration skeleton Minimal end-to-end example — SDK calls only, no UI boilerplate. Replace the `REPLACE_ME_*` constants with your real values. ```typescript import { CoinmeTrackedTextInput, FlowType, getPartnerSessionTag, setupCoinmeRiskEngine, updateCoinmeRiskEngine, } from '@coinme-security/risk-sdk-react-native'; const CLIENT_ID = 'REPLACE_ME_CLIENT_ID'; const CAAS_PARTNER_ID = 'REPLACE_ME_CAAS_PARTNER_ID'; // distinct from CLIENT_ID const CUSTOMER_ID = 'REPLACE_ME_CUSTOMER_ID'; // Step 1 — initialize the native engine const handleInit = async () => { await setupCoinmeRiskEngine({ mode: 'test', // 'test' | 'prod' clientId: CLIENT_ID, partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, flow: FlowType.Onboarding, enableFieldTracking: true, enableBehaviorBiometrics: true, }); }; // Step 2 — right before each add-payment-method call and each order, fetch a // session tag and bind it to the engine. Tags live 30 minutes. const handleGetSessionTag = async () => { const tag = await getPartnerSessionTag({ partnerId: CAAS_PARTNER_ID, customerId: CUSTOMER_ID, }); await updateCoinmeRiskEngine({ sessionKey: tag.webSessionID }); }; // Step 3 — tracked input fields (call after step 2) const TrackedForm = () => ( <> ); ``` ### 6. Required values | Value | Description | | --- | --- | | `CLOUDSMITH_TEAM_TOKEN` | Pulls native `CoinmeRiskSDK` binaries during pod install and Gradle sync | | `CLIENT_ID` | Identifies your app to the Risk Engine | | `CAAS_PARTNER_ID` | Partner identifier — distinct from `CLIENT_ID` | ## Troubleshooting ### `Native module CoinmeRiskEngine not linked` The JS layer couldn't find `NativeModules.CoinmeRiskEngine` at runtime. **Likely causes:** - **You added the package but didn't rebuild the native app.** ```bash cd ios && pod install cd .. && yarn ios # and yarn android ``` - **Cloudsmith auth failing.** Check the `pod install` / Gradle sync logs. If CocoaPods or Gradle can't reach Coinme's Cloudsmith, the native module won't link. Verify `CLOUDSMITH_TEAM_TOKEN` is exported in the shell you're building from, or set in `~/.gradle/gradle.properties` for Gradle persistence. - **New Architecture enabled.** The module is registered on the legacy bridge only. If Fabric / TurboModules is on, the runtime won't see it. Confirm `new_arch_enabled: false` in `Podfile` and `newArchEnabled=false` in `android/gradle.properties`. - **Metro cache.** After a successful rebuild, clear Metro with `yarn start --reset-cache`. ### `Module was compiled with an incompatible version of Kotlin` (Android) The native `risk-sdk-android` artifact is compiled with Kotlin 2.3.0, but React Native 0.81's Gradle plugin pins an older Kotlin. Force Kotlin 2.3.0 across all subprojects via `resolutionStrategy` — see section 6.3, Step 2 for the full copy-pasteable block. **Expo:** If the error persists after applying the resolution strategy, re-run prebuild from scratch and verify the plugin ran: ```bash expo prebuild --clean npx expo run:android ``` Check that `android/build.gradle` contains `classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.0")` and the `// @coinme-risk-sdk:kotlin-version` marker. If those are missing, the plugin didn't run — verify `@coinme-security/risk-sdk-react-native` is listed under `plugins` in your Expo config. ### `Could not find com.coinme:risk-sdk-android` `CLOUDSMITH_TEAM_TOKEN` is missing or wrong. Export it before building: ```bash export CLOUDSMITH_TEAM_TOKEN= ``` Also verify the Maven block in `android/settings.gradle` reads from the same env var. **Expo:** Re-export and retry with: ```bash export CLOUDSMITH_TEAM_TOKEN= npx expo run:android ``` ### `pod install` fails with `401 Authentication required` Token is wrong or expired. Re-export `CLOUDSMITH_TEAM_TOKEN` and run `pod install` again. If you have a stale cache from a previous failed attempt: ```bash rm -rf ~/Library/Caches/CocoaPods ~/.cocoapods/repos ``` **Expo:** Re-export and retry with: ```bash export CLOUDSMITH_TEAM_TOKEN= npx expo run:ios ``` ### `KeyError: key not found: CLOUDSMITH_TEAM_TOKEN` (Expo) `CLOUDSMITH_TEAM_TOKEN` was not set when `expo prebuild` triggered `pod install`. Export it and re-run: ```bash export CLOUDSMITH_TEAM_TOKEN= npx expo run:ios ``` ### `NativeModules.CoinmeRiskEngine is undefined` (Expo) The native module didn't link during prebuild. Clean and rebuild: ```bash # iOS expo prebuild --clean && npx expo run:ios # Android expo prebuild --clean && npx expo run:android ``` ### `RiskEngine is not initialized. Call setupCoinmeRiskEngine() first.` `getPartnerSessionTag` / `updateCoinmeRiskEngine` was called before `setupCoinmeRiskEngine` completed. Always `await setupCoinmeRiskEngine(...)` first. ### My integration looks fine but transactions are being rejected **Most common cause:** you're not calling `submitCoinmeRiskData` before your server requests. This produces no error at the SDK layer — the SDK collects signals and never flushes them — but without correlated signals, Coinme's transaction services will reject the downstream request. **Checklist:** 1. `await submitCoinmeRiskData()` immediately before any transaction-initiating server call (checkout, payment-method link, onboarding submit, etc.) 2. Confirm every Coinme SDK and your backend calls send the same `x-device-fingerprint` (read it with `getDeviceFingerprint()`) — see section 9 3. Confirm `mode` is `'prod'` in production builds. A mismatched `mode` / `clientId` routes data to the wrong environment 4. Confirm `setupCoinmeRiskEngine` has completed (await it) before any `updateCoinmeRiskEngine` call. Parallel setup/update races can lead to overridden config ### `updateCoinmeRiskEngine` throws before I've called setup By design. If no `sessionKey` has ever been set (via `setupCoinmeRiskEngine` or `getPartnerSessionTag`), `updateCoinmeRiskEngine` will throw. Call setup first. ## Support For issues, questions, or feature requests, ask your Coinme integration contact. ## 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 Risk Engine initialises without an error, that a session tag is obtained with the headers the guide names right before each add-payment-method call and each order, that the submit call (where the SDK has one) completes right before a transaction call, and that no client ID or token is in a committed file. Hand back the privacy and store-listing items the guide requires. ### Reading the result **Done when:** Setup completes and a session tag comes back for the customer on this device. **Stop and ask the human when** the client ID is refused, or the partner is unknown (`143-404-317-704`). 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 Risk SDK](https://platformdocs.coinme.com/docs/coinme-risk-sdk.md) - [Coinme Risk SDK for React Native](https://platformdocs.coinme.com/docs/coinme-risk-sdk-for-react-native.md) - [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)