---
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=<YOUR_ENTITLEMENT_TOKEN>
```

Replace `<YOUR_ENTITLEMENT_TOKEN>` 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
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

#### Optional permissions

`AndroidManifest.xml`

```markup
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
```

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 `<queries>` 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<String, String>` | 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)
