> ## Documentation Index
> Fetch the complete documentation index at: https://docs.radar.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Fraud plugin setup

> Install and configure the Radar fraud plugin on iOS, Android, web, and React Native so that verified location checks and device risk checks can run.

Verified location checks (`Radar.trackVerified()`) and device risk checks (`Radar.revealRisk()`) need a fraud plugin in addition to the core SDK. By the end of this page, the plugin will be installed for your platform, device attestation will be configured, and a verified location check will return a token instead of `ERROR_PLUGIN`.

> [!NOTE]
>
> Fraud detection and verified location checks are available on the [Enterprise plan](https://radar.com/pricing).

Before you test, enable Fraud for your project under **Fraud** on the [Settings](https://dashboard.radar.com/settings#fraud-settings) page of the Radar dashboard.

## Compatibility

Use a core SDK version and a plugin version from the same row. A missing or incompatible plugin makes `Radar.trackVerified()` return `ERROR_PLUGIN`. The iOS plugin requires iOS 15 or later.

| Platform | Core SDK | Fraud plugin |
| - | - | - |
| iOS | `RadarSDK` 3.44.0 to 3.46.x | `RadarSDKFraud` 1.6.x |
| Android | `io.radar:sdk` 3.39.0 to 4.3.x | `io.radar:sdk-fraud` 1.3.x |
| Web | `radar-sdk-js` 5.1.0 or later | `@radarlabs/plugin-fraud` 1.6.x |
| React Native | `react-native-radar` 4.x | Bundled iOS plugin. Android plugin from the Android row. |

What each platform supports:

| Capability | iOS | Android | Web | React Native |
| - | - | - | - | - |
| Verified location checks | Yes | Yes | Yes | Yes |
| Device risk checks with `revealRisk()` | Yes | Yes | Yes | Yes |
| Device attestation | Yes, with App Attest | Yes, with the Play Integrity API | No | Yes, per platform |
| Companion app path | No | No | Yes, with Radar Verify for Mac and Windows | No |

The Cordova plugin (3.9.1) and the .NET MAUI package (`RadarIO.Xamarin` 3.9.3) pair with the 3.9 native SDKs, which predate the fraud plugins on this page. They expose the `trackVerified()`, `trackVerifiedToken()`, and `startTrackingVerified()` methods of those SDKs, and they don't expose `revealRisk()`. See the verified location section of the [Cordova SDK](https://docs.radar.com/sdk/cordova.md#verified-location) or [.NET MAUI SDK](https://docs.radar.com/sdk/maui.md#verified-location) reference.

The Capacitor plugin (`capacitor-radar` 4.1.1) includes its own fraud plugins for iOS and Android, so you don't install the plugins on this page. Their versions are outside the ranges in the compatibility table. See the verified location section of the [Capacitor SDK](https://docs.radar.com/sdk/capacitor.md#verified-location) reference.

## iOS

### Install the iOS plugin

Add both packages with Swift Package Manager. In Xcode, add a package dependency for each repository URL, or declare them in `Package.swift`:

```swift Package.swift theme={null}
.package(url: "https://github.com/radarlabs/radar-sdk-ios-spm.git", "3.46.0"..<"3.47.0"),
.package(url: "https://github.com/radarlabs/radar-sdk-ios-fraud-spm.git", "1.6.0"..<"1.7.0"),
```

Starting with iOS SDK 3.44.0, verified requests encrypt the complete request body, and the core SDK and plugin must be updated together. If payload preparation or encryption fails, the request stops and isn't sent unencrypted.

### Initialize the SDK on iOS

Initialize the core SDK as usual. The plugin needs no separate initialization.

```swift theme={null}
import RadarSDK

Radar.initialize(publishableKey: "prj_test_pk_...")
```

Starting with iOS SDK 3.45.0, `Radar.trackVerified()` retries against a secondary host when the primary host doesn't return a response from Radar. To turn this off, set `trackVerifiedAutoFailover` to `false`:

```swift theme={null}
let options = RadarInitializeOptions()
options.trackVerifiedAutoFailover = false
Radar.initialize(publishableKey: "prj_test_pk_...", options: options)
```

In earlier versions the default is `false`, and you set it to `true` to turn failover on.

### Configure App Attest

App Attest supports the `compromised` flag on iOS.

1. Enable [App Attest](https://developer.apple.com/documentation/devicecheck/preparing-to-use-the-app-attest-service) for your app.
2. Under **Fraud** on the [Settings](https://dashboard.radar.com/settings#fraud-settings) page, enter your valid App IDs as a comma-separated list, for example `A1B2C3D4E5.com.example.app1,A1B2C3D4E5.com.example.app2`.

If App Attest indicates that the device or app is compromised, `user.fraud.compromised` is `true`. If `Radar.trackVerified()` returns `ERROR_FORBIDDEN`, check the SDK logs.

### Configure SSL pinning on iOS

To pin the certificates for Radar's verified hosts, add the following to your `Info.plist`. Include the `api-verified.radar.com` entry when automatic failover is on.

```xml Info.plist theme={null}
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <false/>
    <key>NSPinnedDomains</key>
    <dict>
        <key>api-verified.radar.io</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSPinnedLeafIdentities</key>
            <array>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>15ktYXSSU2llpy7YyCgeqUKDBkjcimK/weUcec960sI=</string>
                </dict>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>15ktYXSSU2llpy7YyCgeqUKDBkjcimK/weUcec960sI=</string>
                </dict>
            </array>
        </dict>
        <key>api-verified.radar.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSPinnedCAIdentities</key>
            <array>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>++MBgDH5WGvL9Bcn5Be30cRcL0f5O+NyoXuWtQdX1aI=</string>
                </dict>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>f0KW/FtqTjs108NpYj42SrGvOB2PpxIVM8nWxjPqJGE=</string>
                </dict>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>NqvDJlas/GRcYbcWE8S/IceH9cq77kg0jVhZeAPXq8k=</string>
                </dict>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>9+ze1cZgR9KO1kZrVDxA4HQ6voHRCSVNz4RdTCx4U8U=</string>
                </dict>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>KwccWaCgrnaw6tsrrSO61FgLacNgG2MMLq8GE6+oP5I=</string>
                </dict>
            </array>
        </dict>
    </dict>
</dict>
```

See [identity pinning on iOS](https://developer.apple.com/news/?id=g9ejcf8y).

## Android

### Install the Android plugin

Add the core SDK, the plugin, and the Play Integrity API to the `dependencies` section of your app's `build.gradle` file:

```gradle build.gradle theme={null}
dependencies {
  implementation 'io.radar:sdk:4.3.+'
  implementation 'io.radar:sdk-fraud:1.3.1'
  implementation 'com.google.android.play:integrity:1.6.0'
}
```

The plugin compiles against the Play Integrity API and doesn't bundle it, so add that dependency before you call `Radar.trackVerified()`.

### Initialize the SDK on Android

Pass `fraud = true` in `RadarInitializeOptions`. This is required for the `sharing` flag on Android.

```kotlin theme={null}
import io.radar.sdk.Radar
import io.radar.sdk.RadarInitializeOptions

// In Application.onCreate()
Radar.initialize(
  context = this,
  publishableKey = "prj_test_pk_...",
  options = RadarInitializeOptions(fraud = true)
)
```

Starting with Android SDK 4.2.0, `Radar.trackVerified()` retries against a secondary host when the primary host doesn't return a response from Radar. To turn this off, pass `trackVerifiedAutoFailover = false` in `RadarInitializeOptions`. In earlier versions, pass `trackVerifiedAutoFailover = true` to turn failover on.

### Configure the Play Integrity API

The Play Integrity API supports the `compromised` flag on Android. Enable the [Play Integrity API](https://developer.android.com/google/play/integrity) under **Fraud** on the [Settings](https://dashboard.radar.com/settings#fraud-settings) page.

If the device or app doesn't meet [basic integrity checks](https://developer.android.com/google/play/integrity/verdict#device-integrity-field), `user.fraud.compromised` is `true`. If `Radar.trackVerified()` returns `ERROR_FORBIDDEN`, check the SDK logs. The Google Play services version on the device may be out of date.

### Configure SSL pinning on Android

To pin the certificates for Radar's verified hosts, add a `res/xml/network_security_config.xml` file. Include the `api-verified.radar.com` entry when automatic failover is on.

```xml network_security_config.xml theme={null}
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">api-verified.radar.io</domain>
        <pin-set>
            <pin digest="SHA-256">15ktYXSSU2llpy7YyCgeqUKDBkjcimK/weUcec960sI=</pin>
            <pin digest="SHA-256">15ktYXSSU2llpy7YyCgeqUKDBkjcimK/weUcec960sI=</pin>
        </pin-set>
    </domain-config>

    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">api-verified.radar.com</domain>
        <pin-set>
            <pin digest="SHA-256">++MBgDH5WGvL9Bcn5Be30cRcL0f5O+NyoXuWtQdX1aI=</pin>
            <pin digest="SHA-256">f0KW/FtqTjs108NpYj42SrGvOB2PpxIVM8nWxjPqJGE=</pin>
            <pin digest="SHA-256">NqvDJlas/GRcYbcWE8S/IceH9cq77kg0jVhZeAPXq8k=</pin>
            <pin digest="SHA-256">9+ze1cZgR9KO1kZrVDxA4HQ6voHRCSVNz4RdTCx4U8U=</pin>
            <pin digest="SHA-256">KwccWaCgrnaw6tsrrSO61FgLacNgG2MMLq8GE6+oP5I=</pin>
        </pin-set>
    </domain-config>
</network-security-config>
```

Then reference the file from the `application` element in your manifest:

```xml AndroidManifest.xml theme={null}
<application
    android:networkSecurityConfig="@xml/network_security_config">
</application>
```

If your debug builds load JavaScript from a local development server, as React Native does, add a separate `domain-config` that permits cleartext traffic to `localhost`. See [Network Security Configuration on Android](https://developer.android.com/training/articles/security-config).

## Web

### Install the web plugin

With npm, install the core SDK and the plugin:

```bash theme={null}
npm install radar-sdk-js @radarlabs/plugin-fraud
```

Then register the plugin before you initialize:

```javascript theme={null}
import Radar from 'radar-sdk-js';
import { createFraudPlugin } from '@radarlabs/plugin-fraud';

Radar.registerPlugin(createFraudPlugin());
Radar.initialize('prj_test_pk_...');
```

With script tags, load the plugin after the core SDK. The plugin bundle registers itself.

```html theme={null}
<script src="https://js.radar.com/v5.3.0/radar.min.js"></script>
<script src="https://js.radar.com/fraud/v1.6.1/radar-fraud.min.js"></script>
```

The plugin's methods are on `Radar.fraud`, for example `Radar.fraud.trackVerified()`. The same methods on `Radar`, such as `Radar.trackVerified()`, still work and are deprecated.

### Companion app and no-download paths

By default, the web plugin runs a check through the Radar Verify companion app on the user's computer. Pass `skipVerifyApp: true` to run the check in the browser instead, with nothing for the user to install. To decide which path fits your product, and for download links, see [Choose the companion app or the no-download path](https://docs.radar.com/geo-compliance/verify-location.md#choose-the-companion-app-or-the-no-download-path).

To customize the Radar Verify installer or branding, contact your Radar account team.

### Web plugin methods

The plugin adds these methods on `Radar.fraud`. The sections below give the parameters and defaults of each verified location method.

| Method | Returns | Description |
| - | - | - |
| `Radar.fraud.trackVerified(params?)` | `Promise<RadarTrackVerifiedResponse>` | Runs one verified location check. |
| `Radar.fraud.startTrackingVerified(params)` | Nothing | Starts automatic checks. |
| `Radar.fraud.stopTrackingVerified()` | Nothing | Stops automatic checks. |
| `Radar.fraud.getVerifiedLocationToken(params?)` | `Promise<RadarTrackVerifiedResponse \| null>` | Returns the last token if it is still valid, or runs a new check if not. |
| `Radar.fraud.clearVerifiedLocationToken()` | Nothing | Clears the last token. |
| `Radar.fraud.onTokenUpdated(callback)` | Nothing | Registers a callback that receives the result of each check. |
| `Radar.fraud.onIpChanged(callback)` | Nothing | Registers a callback for IP address changes. |
| `Radar.fraud.setExpectedJurisdiction(countryCode?, stateCode?)` | Nothing | Sets the user's expected country and state for jurisdiction checks. |
| `Radar.fraud.setExpectedAddress(address?)` | Nothing | Sets the user's expected address. |
| `Radar.fraud.setUserLanguage(language)` | Nothing | Sets the user's preferred language as a BCP 47 language tag, such as `"en"` or `"es-PR"`. Pass `null` to clear it. |
| `Radar.fraud.revealRisk()` | `Promise<RadarRevealRiskResponse>` | Runs a device risk check without location. See [Fraud overview and quickstart](https://docs.radar.com/fraud/overview.md). |
| `Radar.fraud.clearRevealRiskId()` | Nothing | Clears the ID of the last device risk check, which the next verified location check would otherwise send. |

`Radar.fraud.errors` holds the plugin's error classes, such as `Radar.fraud.errors.RadarVerifyAppError`.

The deprecated aliases on `Radar` cover `trackVerified()`, `startTrackingVerified()`, `stopTrackingVerified()`, `getVerifiedLocationToken()`, `clearVerifiedLocationToken()`, `setExpectedJurisdiction()`, and `onTokenUpdated()`. The other methods are on `Radar.fraud` only.

#### `Radar.fraud.trackVerified()`

Runs one verified location check and resolves with the geolocation token and the client result.

```typescript theme={null}
Radar.fraud.trackVerified(params?: RadarTrackVerifiedParams): Promise<RadarTrackVerifiedResponse>
```

| Option | Type | Default | Description |
| - | - | - | - |
| `skipVerifyApp` | boolean | `false` | `false` runs the check through the Radar Verify companion app. `true` runs the check in the browser. See [Choose the companion app or the no-download path](https://docs.radar.com/geo-compliance/verify-location.md#choose-the-companion-app-or-the-no-download-path). |
| `reason` | string | None | A label for why you ran the check. See [Request parameters](#request-parameters). |
| `transactionId` | string | None | Your identifier for the action the check protects. See [Request parameters](#request-parameters). |
| `userId` | string | The value set with `Radar.setUserId()` | A stable unique ID for the user. A value you pass here is saved as the user ID for later calls. |
| `description` | string | The value set with `Radar.setDescription()` | A description for the user. |
| `metadata` | object | The value set with `Radar.setMetadata()` | Custom key-value pairs for the user. |

The check also sends the product set with `Radar.setProduct()` and the values set with `Radar.fraud.setExpectedJurisdiction()` and `Radar.fraud.setExpectedAddress()`.

The promise resolves with these fields:

| Field | Type | Description |
| - | - | - |
| `token` | string | The signed geolocation token. Send it to your backend and validate it there. See [Geolocation token schema](https://docs.radar.com/api/geolocation-tokens.md). |
| `passed` | boolean | Whether the user passed all jurisdiction and fraud checks. |
| `failureReasons` | array of string | Why the check didn't pass. See [Failure and warning reasons](https://docs.radar.com/api/geolocation-tokens.md#failure-and-warning-reasons). |
| `expiresAt` | `Date` | When the token expires. |
| `expiresIn` | number | Seconds until the token expires. |
| `_id` | string | The Radar ID of the check. |
| `user` | object | The user. |
| `events` | array of object | The events generated, if any. |
| `location` | object | The `latitude`, `longitude`, and `accuracy` used for the check. |

When the check can't complete, the promise rejects and there is no token. The error's `status` has the reason. On the companion app path, the error is a `RadarVerifyAppError` with the status `ERROR_VERIFY_APP` when the app isn't running.

Each completed check becomes the last token that `Radar.fraud.getVerifiedLocationToken()` returns, and is passed to the callback registered with `Radar.fraud.onTokenUpdated()`.

This example runs a check in the browser and sends a passing token to your backend. `sendTokenToBackend`, `showFailure`, and `showCheckError` are functions you write.

```javascript theme={null}
try {
  const result = await Radar.fraud.trackVerified({ skipVerifyApp: true, reason: 'login' });

  if (result.passed) {
    await sendTokenToBackend(result.token);
  } else {
    showFailure(result.failureReasons);
  }
} catch (err) {
  showCheckError(err.status);
}
```

#### `Radar.fraud.startTrackingVerified()`

Starts automatic checks. If the last token is still valid, the first check is scheduled from it. Otherwise a check runs immediately.

```typescript theme={null}
Radar.fraud.startTrackingVerified(params: RadarStartTrackingVerifiedParams): void
```

| Option | Type | Default | Description |
| - | - | - | - |
| `interval` | number | `300` | The longest time between checks, in seconds. |
| `skipVerifyApp` | boolean | `false` | The path each automatic check uses, as for `Radar.fraud.trackVerified()`. |
| `ipChanges` | boolean | `false` | When `true`, the plugin checks the device IP address every 30 seconds and runs a new check when it changes. |

The next check runs 10 seconds before the interval ends or the last token expires, whichever is sooner, and never less than 10 seconds after the previous one. Automatic checks don't send a `reason` or a `transactionId`. A check that fails with an error is logged, not thrown, and the next check is still scheduled.

To stop automatic checks, call `Radar.fraud.stopTrackingVerified()`.

#### `Radar.fraud.onTokenUpdated()`

Registers one callback that receives the result of every completed check, whether you ran it with `Radar.fraud.trackVerified()` or the plugin ran it automatically. The argument has the same fields as the `Radar.fraud.trackVerified()` result. Registering a second callback replaces the first.

```javascript theme={null}
Radar.fraud.onTokenUpdated((result) => {
  sendTokenToBackend(result.token);
});

Radar.fraud.startTrackingVerified({ interval: 1200, skipVerifyApp: true, ipChanges: true });
```

#### `Radar.fraud.getVerifiedLocationToken()`

Returns the last token when it passed and hasn't expired. Otherwise it runs a new check with `Radar.fraud.trackVerified()` and returns that result, so it rejects with the same errors. It takes the same options as `Radar.fraud.trackVerified()`, which apply only when a new check runs.

```javascript theme={null}
const result = await Radar.fraud.getVerifiedLocationToken({ skipVerifyApp: true });
```

#### `Radar.fraud.clearVerifiedLocationToken()`

Clears the last token, so that the next `Radar.fraud.getVerifiedLocationToken()` call runs a new check. Call it after you change the product with `Radar.setProduct()` or the expected jurisdiction, because the last token was issued for the earlier values.

#### `Radar.fraud.onIpChanged()`

Registers a callback, with no arguments, that the plugin calls when the device IP address changes. While a callback is registered, the plugin checks the IP address every 30 seconds. When the address changes, the plugin clears the last token and then calls the callback. Pass `null` to remove the callback.

```javascript theme={null}
Radar.fraud.onIpChanged(() => {
  checkLocation('ip_change');
});
```

#### `Radar.fraud.setExpectedJurisdiction()`

Sets the country code and state code you expect the user to be in. Later checks send both values, and a check in a different jurisdiction fails with `country_not_expected` or `state_not_expected`. See [Failure and warning reasons](https://docs.radar.com/api/geolocation-tokens.md#failure-and-warning-reasons). Call it with no arguments to clear both values.

```javascript theme={null}
Radar.fraud.setExpectedJurisdiction('US', 'NJ');
```

#### `Radar.fraud.setExpectedAddress()`

Sets the address you expect the user to be at, as a string. Later checks send it, and the token reports the result in the [expected address fields](https://docs.radar.com/api/geolocation-tokens.md#expected-address-fields). Call it with no arguments to clear it.

```javascript theme={null}
Radar.fraud.setExpectedAddress('841 Broadway, New York, NY 10003');
```

## Desktop

For desktop web apps, use the web plugin with the Radar Verify companion app described in [Web](#web).

For native desktop apps, a Mac SDK (macOS 12.4 or later), a Windows SDK (Windows 10 or later with .NET 8 or later), and an Electron plugin are available on request. Contact your Radar account team for access. For how their calls differ from the mobile and web SDKs, see [Desktop apps](#desktop-apps).

## React Native

### Install the React Native plugin

`react-native-radar` bundles a compatible iOS plugin. On Android, add the plugin version from the [compatibility table](#compatibility).

> [tab] Expo
>
> Set `iosFraud` and `androidFraud` in the `react-native-radar` plugin options in `app.json`, then run `npx expo prebuild --clean`.
>
> ```json app.json theme={null}
> {
>   "expo": {
>     "plugins": [
>       [
>         "react-native-radar",
>         {
>           "iosFraud": true,
>           "androidFraud": true
>         }
>       ]
>     ]
>   }
> }
> ```
>
> The Expo plugin adds `io.radar:sdk-fraud` and the Play Integrity API dependency to `android/app/build.gradle` only when they aren't already there, and it configures SSL pinning for `api-verified.radar.io` only. It doesn't add the `api-verified.radar.com` entry used for automatic failover. After prebuild, open `android/app/build.gradle` and confirm that the `io.radar:sdk-fraud` version matches the [compatibility table](#compatibility). Update it if it is older.

> [tab] Without Expo
>
> Add the iOS plugin to the app target in `ios/Podfile`, then run `pod install`:
>
> ```ruby Podfile theme={null}
> pod 'RadarSDKFraud', :path => '../node_modules/react-native-radar'
> ```
>
> Add the Android plugin and the Play Integrity API to the `dependencies` section of `android/app/build.gradle`:
>
> ```gradle build.gradle theme={null}
> dependencies {
>   implementation 'io.radar:sdk-fraud:1.3.1'
>   implementation 'com.google.android.play:integrity:1.6.0'
> }
> ```
>
> Configure SSL pinning as described in the [iOS](#configure-ssl-pinning-on-ios) and [Android](#configure-ssl-pinning-on-android) sections.

### Initialize the SDK on React Native

Pass `true` as the second argument to `Radar.initialize()` to turn on fraud detection. This is required for the `sharing` flag on Android.

```javascript theme={null}
import Radar from 'react-native-radar';

Radar.initialize('prj_test_pk_...', true);
```

To set automatic failover explicitly, pass `trackVerifiedAutoFailover` in the options argument (React Native SDK 4.38.0 or later):

```javascript theme={null}
Radar.initialize('prj_test_pk_...', true, {
  trackVerifiedAutoFailover: true,
});
```

Complete the [App Attest](#configure-app-attest) and [Play Integrity API](#configure-the-play-integrity-api) steps for the native platforms.

## Authenticate the SDK with auth tokens

> [!NOTE]
>
> Auth tokens must be enabled for your project. Contact your Radar account team.

Instead of a publishable key, you can initialize the SDK with a short-lived auth token. An auth token is a JSON Web Token (JWT) that your backend signs with a private key that only you hold. Radar verifies each request against the matching public key, which you register in the dashboard. For who can manage public keys, see [Use auth tokens instead of a publishable key](https://docs.radar.com/fundamentals/authentication-and-access.md#use-auth-tokens-instead-of-a-publishable-key).

Auth tokens need iOS SDK 3.28.0 or later, Android SDK 3.27.0 or later, or web SDK 5.1.0 or later.

**1. Create a key pair**

On your backend, create an EC P-256 key pair:

```bash theme={null}
openssl ecparam -genkey -name prime256v1 -noout -out private-key.pem
openssl ec -in private-key.pem -pubout -out public-key.pem
```

Store `private-key.pem` in your secret manager. Radar also accepts an RSA public key of 2048 bits or more, and tokens for that key are signed with RS256.

**2. Register the public key**

On the [Settings](https://dashboard.radar.com/settings) page, under **Auth tokens**, click **Add**. Enter a **Name**, select the **Environment** (**Test** or **Live**), paste the full contents of `public-key.pem` into **Public key**, including the `BEGIN` and `END` lines, and click **Add**.

The key appears in the list with the status **Enabled**. Copy its **Key ID**. Tokens signed for this key authenticate to the environment you selected.

**3. Sign a token on your backend**

Sign a JWT with the private key, and put the Key ID in the `kid` header. This Node.js example uses the [`jose`](https://github.com/panva/jose) package and reads the private key PEM and the Key ID from environment variables:

```javascript Node.js theme={null}
import { createPrivateKey } from 'node:crypto';
import { SignJWT } from 'jose';

const privateKey = createPrivateKey(process.env.RADAR_AUTH_TOKEN_PRIVATE_KEY);
const keyId = process.env.RADAR_AUTH_TOKEN_KEY_ID;

export async function createRadarAuthToken(userId) {
  return new SignJWT({ constraints: { userId } })
    .setProtectedHeader({ alg: 'ES256', typ: 'JWT', kid: keyId })
    .setIssuedAt()
    .setExpirationTime('10m')
    .sign(privateKey);
}
```

Return the token to your app from an endpoint that requires your own user session.

**4. Initialize the SDK with the token**

Pass the token in place of the publishable key:

```swift Swift theme={null}
Radar.initialize(authToken: authToken)
```

```kotlin Kotlin theme={null}
Radar.initialize(context, RadarInitializeOptions(authToken = authToken, fraud = true))
```

```javascript JavaScript theme={null}
Radar.initialize({ authToken });
```

```javascript React Native theme={null}
Radar.initializeWithAuthToken(authToken, true);
```

To check the setup, call `Radar.trackVerified()` (`Radar.fraud.trackVerified()` on web) and confirm that it returns a success status.

### Token format

| Field | Location | Required | Description |
| - | - | - | - |
| `alg` | Header | Yes | `ES256` for an EC P-256 key, or `RS256` for an RSA key. It must match the registered public key. |
| `typ` | Header | Yes | `JWT`. |
| `kid` | Header | Yes | The Key ID of the registered public key. |
| `iat` | Payload | Yes | Issue time, in seconds since the Unix epoch. Radar rejects a token more than 24 hours after `iat`. |
| `exp` | Payload | Yes | Expiration time, in seconds since the Unix epoch. |
| `constraints` | Payload | No | An object that limits what the token can be used for. See the next table. |

Each constraint you set must match the value the SDK sends with a location update:

| Constraint | Type | Must match |
| - | - | - |
| `userId` | string | The user ID set with `Radar.setUserId()`. |
| `expectedCountryCode` | string | The country code set with `Radar.setExpectedJurisdiction()`. |
| `expectedStateCode` | string | The state code set with `Radar.setExpectedJurisdiction()`. |
| `product` | string | The product name set with `Radar.setProduct()`. |
| `metadata` | object | Every key and value in the constraint must be present in the metadata set with `Radar.setMetadata()`. |

### Auth token errors

| Code | Meaning | What to do |
| - | - | - |
| `ERROR_UNAUTHORIZED` | The token is malformed or expired, its signature or header is invalid, the public key is disabled or not found, or auth tokens aren't enabled for the project. | Check the `alg`, `typ`, and `kid` headers and your backend's clock. When a token expires, get a new one from your backend and initialize the SDK again. |
| `ERROR_FORBIDDEN` | A constraint in the token doesn't match the request. | Set the user ID, expected jurisdiction, product, or metadata in the SDK to the values in the token before you call `Radar.trackVerified()`. |

## Verify the setup

1. Build and run the app on a physical device, or open the page in a browser, using a test publishable key.
2. Grant location permission.
3. Call `Radar.trackVerified()` (`Radar.fraud.trackVerified()` on web).
4. Confirm that the call returns a success status and a token whose `token` field is a non-empty string.

| Result | Likely cause |
| - | - |
| `ERROR_PLUGIN` | The plugin is missing, or its version isn't compatible with the core SDK. Check the [compatibility table](#compatibility). |
| `ERROR_FORBIDDEN` | Device attestation couldn't run. Check the SDK logs, the OS version, and Google Play services. |
| `ERROR_VERIFY_APP` | Web companion app path: Radar Verify isn't installed or not running. |

## Supported clients

These clients can run a verified location check. The method column gives the form that takes every option.

| Client | Method | `reason` and `transactionId` |
| - | - | - |
| iOS SDK | `Radar.trackVerified(beacons:desiredAccuracy:reason:transactionId:completionHandler:)` | Yes |
| Android SDK | `Radar.trackVerified(beacons, desiredAccuracy, reason, transactionId, callback)` | Yes |
| Web SDK with `@radarlabs/plugin-fraud` | `Radar.fraud.trackVerified({ skipVerifyApp, reason, transactionId })` | Yes |
| React Native SDK | `Radar.trackVerified({ beacons, desiredAccuracy, reason, transactionId })` | Yes |
| Capacitor SDK | `Radar.trackVerified({ beacons, desiredAccuracy, reason, transactionId })` | Yes |
| Mac SDK | `RadarVerify.trackVerified(publishableKey:userId:expectedCountryCode:expectedStateCode:product:reason:transactionId:metadata:)` | Yes |
| Windows SDK | `Radar.TrackVerified(publishableKey, userId, expectedCountryCode, expectedStateCode, product, reason, transactionId, metadata)` | Yes |
| Flutter SDK | `Radar.trackVerified({bool? beacons})` | No |
| Cordova SDK | `Radar.trackVerifiedToken(options?, callback)` | No |
| .NET MAUI SDK | `Radar.TrackVerifiedToken(bool beacons = false)` | No |

The Flutter, Cordova, and .NET MAUI SDKs expose earlier verified location methods that don't accept `reason` or `transactionId`. See the verified location section of the [Flutter SDK](https://docs.radar.com/sdk/flutter.md#verified-location), [Cordova SDK](https://docs.radar.com/sdk/cordova.md#verified-location), or [.NET MAUI SDK](https://docs.radar.com/sdk/maui.md#verified-location) reference.

The Capacitor SDK includes its own fraud plugins, as described in [Compatibility](#compatibility). The Mac and Windows SDKs are covered in [Desktop apps](#desktop-apps).

For every native method signature, the token object, and the delegate or receiver, see the verified location section of the [iOS SDK](https://docs.radar.com/sdk/ios.md#verified-location), [Android SDK](https://docs.radar.com/sdk/android.md#verified-location), [React Native SDK](https://docs.radar.com/sdk/react-native.md#verified-location), or [Capacitor SDK](https://docs.radar.com/sdk/capacitor.md#verified-location) reference. For web, see [Web plugin methods](#web-plugin-methods).

## Request parameters

A verified location check takes these parameters. All of them are optional.

| Parameter | Type | Required | Description |
| - | - | - | - |
| `reason` | string | No | A label for why you ran the check, such as `login` or `withdrawal`. Radar returns it in the token as `reason` and shows it in the Radar dashboard and reports. The value is a free-form string that you choose. Use a small, fixed set of values so that checks are easy to filter. |
| `transactionId` | string | No | Your identifier for the action the check protects. Radar returns it in the token as `transactionId`. Radar doesn't check it for uniqueness. Your backend compares it to the action it is authorizing. |
| `beacons` | boolean | No | Mobile SDKs only. Ranges nearby beacons and includes them in the check. Defaults to `false`. See [Zones and beacons](#zones-and-beacons). |
| `desiredAccuracy` | string | No | iOS, Android, React Native, and Capacitor. Location accuracy for the check: high, medium, or low. Defaults to medium. On iOS and Android the value is a `RadarTrackingOptionsDesiredAccuracy` enum case. |
| `skipVerifyApp` | boolean | No | Web only. `false` (the default) runs the check through the Radar Verify companion app on the user's computer. `true` runs the check in the browser without the app. |

On web, `Radar.fraud.trackVerified()` also accepts `userId`, `description`, and `metadata`. See [Web plugin methods](#web-plugin-methods).

The user, product, and expected location aren't parameters of the check on mobile and web. Set them before the check:

| Value | Set with | In the token |
| - | - | - |
| User ID | `Radar.setUserId()` | `user.userId` |
| Product | `Radar.setProduct()`, for example `sportsbook`, when your project has more than one product configured | `product` |
| Expected jurisdiction | `Radar.setExpectedJurisdiction()` (`Radar.fraud.setExpectedJurisdiction()` on web) | Failure reasons `country_not_expected` and `state_not_expected` |
| Expected address | `Radar.setExpectedAddress()` (`Radar.fraud.setExpectedAddress()` on web) | `user.expectedAddress` |

The Mac and Windows SDKs take the publishable key, user ID, product, and expected jurisdiction as parameters of each call. See [Desktop apps](#desktop-apps).

## Manual and automatic checks

There are two ways to run checks. Backend validation is the same for both.

| | Manual checks | Automatic checks |
| - | - | - |
| Method | `Radar.trackVerified()` | `Radar.startTrackingVerified()`, then `Radar.getVerifiedLocationToken()` |
| Who starts each check | Your app | The SDK |
| When checks run | When you call the method | When tracking starts, then at your interval, sooner when the last token expires before the interval, and when the device IP address changes |
| Token delivery | The completion handler or promise of your call | `RadarVerifiedDelegate.didUpdateToken()` on iOS, `RadarVerifiedReceiver.onTokenUpdated()` on Android, `Radar.fraud.onTokenUpdated()` on web, and the result of `getVerifiedLocationToken()` |
| `reason` | You pass a reason on every check | On iOS and Android, the SDK sets the reason on the checks it starts: `interval`, `ip_change`, or `last_token_invalid`. On web, no reason is sent. |
| `transactionId` | Supported | Not sent on checks the SDK starts |
| Last token | You keep the last token and reuse it until it expires | `getVerifiedLocationToken()` returns the last token if it is still valid, and requests a new one if not |

On web, these methods are on `Radar.fraud`, and automatic checks respond to IP address changes only when you pass `ipChanges: true`. You can combine the two modes: run automatic checks for the session, and call `Radar.trackVerified()` with a `reason` and a `transactionId` before a single-use action.

With automatic checks, call `Radar.clearVerifiedLocationToken()` (`Radar.fraud.clearVerifiedLocationToken()` on web) after you change the product with `Radar.setProduct()`, so that the next call returns a token for the new product.

A manual integration follows three rules:

* **Reuse the token until it expires**: Each token carries its own expiry in `expiresAt`, and tokens issued close to a border expire sooner. Compare the current time to `expiresAt` instead of using a fixed interval. See [Expiry](https://docs.radar.com/api/geolocation-tokens.md#expiry).
* **Check again on expiry or IP change**: Run a new check when the token has expired or the SDK reports that the device IP address changed.
* **Run one check at a time**: If a check is in progress when another is triggered, wait for the first result instead of starting a second request.

The SDK reports an IP address change through a callback:

| Platform | How to receive the change | When the SDK monitors |
| - | - | - |
| iOS | Set a `RadarVerifiedDelegate` with `Radar.setVerifiedDelegate()` and implement `didChangeIP()`. | While a verified delegate is set or automatic checks are running. |
| Android | Set a `RadarVerifiedReceiver` with `Radar.setVerifiedReceiver()` and override `onIpChanged(context)`. | While a verified receiver is set or automatic checks are running. |
| Web | Register a callback with `Radar.fraud.onIpChanged()`. Pass `null` to remove it. | While a callback is registered, or automatic checks are running with `ipChanges: true`. |
| React Native | Register the `onIpChanged` listener. See [React Native SDK](https://docs.radar.com/sdk/react-native.md). | As on the native platform. |

There is no separate callback for a location change. Movement toward a border is handled by the shorter expiry on the token.

These examples apply the three rules in one function, `checkLocation`, that you call before each restricted action and when the app returns to the foreground. `sendTokenToBackend`, `showFailure`, and `showCheckError` are functions you write.

```swift Swift theme={null}
import RadarSDK

final class LocationChecker: NSObject, RadarVerifiedDelegate {
  private var lastToken: RadarVerifiedLocationToken?
  private var isChecking = false

  override init() {
    super.init()
    Radar.setVerifiedDelegate(self)
  }

  func checkLocation(reason: String) {
    // Reuse the last token until it expires.
    if let last = lastToken, last.passed, let expiresAt = last.expiresAt, expiresAt > Date() { return }

    // One check at a time.
    guard !isChecking else { return }
    isChecking = true

    Radar.trackVerified(
      beacons: false,
      desiredAccuracy: .medium,
      reason: reason,
      transactionId: nil
    ) { (status, token) in
      self.isChecking = false

      guard status == .success, let token = token, let jwt = token.token else {
        showCheckError(status)
        return
      }

      self.lastToken = token
      if token.passed {
        sendTokenToBackend(jwt)
      } else {
        showFailure(token.failureReasons ?? [])
      }
    }
  }

  func didChangeIP() {
    lastToken = nil
    checkLocation(reason: "ip_change")
  }
}
```

```kotlin Kotlin theme={null}
import android.content.Context
import io.radar.sdk.Radar
import io.radar.sdk.RadarVerifiedReceiver
import io.radar.sdk.model.RadarVerifiedLocationToken
import java.util.Date

object LocationChecker : RadarVerifiedReceiver() {
  private var lastToken: RadarVerifiedLocationToken? = null
  private var isChecking = false

  // Call once after Radar.initialize().
  fun start() = Radar.setVerifiedReceiver(this)

  fun checkLocation(reason: String) {
    // Reuse the last token until it expires.
    val last = lastToken
    if (last != null && last.passed && last.expiresAt.after(Date())) return

    // One check at a time.
    if (isChecking) return
    isChecking = true

    Radar.trackVerified(reason = reason) { status, token ->
      isChecking = false

      if (status != Radar.RadarStatus.SUCCESS || token == null) {
        showCheckError(status)
        return@trackVerified
      }

      lastToken = token
      if (token.passed) {
        sendTokenToBackend(token.token)
      } else {
        showFailure(token.failureReasons)
      }
    }
  }

  override fun onTokenUpdated(context: Context, token: RadarVerifiedLocationToken) {}

  override fun onIpChanged(context: Context) {
    lastToken = null
    checkLocation("ip_change")
  }
}
```

```javascript JavaScript theme={null}
import Radar from 'radar-sdk-js';

let lastResult = null;
let inFlight = null;

export function checkLocation(reason) {
  // Reuse the last token until it expires.
  if (lastResult?.passed && lastResult.expiresAt > new Date()) {
    return Promise.resolve(lastResult);
  }

  // One check at a time. Callers share the check that is running.
  inFlight ??= Radar.fraud
    .trackVerified({ reason })
    .then(async (result) => {
      lastResult = result;
      if (result.passed) {
        await sendTokenToBackend(result.token);
      } else {
        showFailure(result.failureReasons);
      }
      return result;
    })
    .finally(() => {
      inFlight = null;
    });

  return inFlight;
}

Radar.fraud.onIpChanged(() => {
  lastResult = null;
  checkLocation('ip_change').catch(showCheckError);
});
```

For a single-use action such as a withdrawal, call `Radar.trackVerified()` directly with a `transactionId` instead of reusing the last token. Your backend enforces the expiry on every restricted request. See [Validate a token](https://docs.radar.com/api/geolocation-tokens.md#validate-a-token).

## Zones and beacons

Radar evaluates the location against your allowed countries and states, and against the zones below. Each zone result is in the token's [country and state fields](https://docs.radar.com/api/geolocation-tokens.md#country-and-state-fields), and a failed zone test adds a value to `failureReasons`. See [Failure and warning reasons](https://docs.radar.com/api/geolocation-tokens.md#failure-and-warning-reasons).

> [!NOTE]
>
> Buffer zones and exclusion zones must be enabled for your project. Contact your Radar account team.

* **Buffer zones**: A buffer zone fails a check that is too close to a border, based on a jurisdiction threshold or the accuracy reported by the device. The token sets `user.state.inBufferZone` and `user.state.distanceToBorder`, and the failure reason is `state_in_buffer_zone`.
* **Exclusion zones**: An exclusion zone fails a check inside a zone within an otherwise allowed state. Exclusion zones can be turned on for all states or for specific states, under **Fraud** on the [Settings](https://dashboard.radar.com/settings#fraud-settings) page. The token sets `user.state.inExclusionZone`, and the failure reason is `state_in_exclusion_zone`.
* **Inclusion zones**: An inclusion zone lets a check inside it pass the allowed-state test. The token sets `user.state.inInclusionZone`.
* **Custom geofence zones**: To fail or pass checks inside a property, create a custom geofence on the [Geofences](https://dashboard.radar.com/geofencing/geofences) page and set its fraud zone type to a state exclusion zone or a state inclusion zone. The geofence takes effect for checks made after you save it, and it appears in `user.geofences`. Geofences without a zone type don't change `passed`.

A state check passes when the state matches the expected jurisdiction if you set one, the location isn't in an exclusion zone, the location isn't in a buffer zone, and the state is allowed or the location is in an inclusion zone.

On iOS and Android, a check can also range nearby beacons. Pass `beacons: true` to `Radar.trackVerified()`. When beacons are enabled for your project, the beacons in range are returned with the user in the verified payload. A beacon doesn't change `passed`, so if your rule depends on being near a beacon, apply it on your backend after you validate the token. For beacon setup and ranging, see [Track indoor location with beacons](https://docs.radar.com/geofencing/beacons.md).

## Desktop apps

A native macOS or Windows app runs the check itself with the Mac or Windows SDK, without the web SDK or the companion app. The desktop SDKs differ from the mobile and web SDKs in three ways:

* **Call setup first**: Call `RadarVerify.setup()` on macOS, or `Radar.Setup()` on Windows (`using RadarVerify;`), once at launch before the first check. On macOS it requests location permission, on Windows it checks it, and on both it warms up location services.
* **Pass identity on each call**: There is no separate initialize, `setUserId()`, or `setProduct()` call. Pass the publishable key, user ID, and product to each `RadarVerify.trackVerified(...)` call on macOS, or `Radar.TrackVerified()` call on Windows.
* **Read a status and a token**: The result is a status and a token. The token has `token`, `passed`, `failureReasons`, `expiresAt`, and `expiresIn`. A status other than success means the check didn't complete and there is no token.

Both SDKs take the same parameters:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `publishableKey` | string | Yes | Your publishable key. |
| `userId` | string | No | The ID of the authenticated user. Your backend compares it to the session user when it validates the token. |
| `product` | string | No | The product name, when your project has more than one product configured. |
| `reason` | string | No | A label for why you ran the check. See [Request parameters](#request-parameters). |
| `transactionId` | string | No | Your identifier for the action the check protects. See [Request parameters](#request-parameters). |
| `expectedCountryCode` | string | No | The country code you expect the user to be in. |
| `expectedStateCode` | string | No | The state code you expect the user to be in. |
| `metadata` | object | No | Custom key-value pairs for the user. |

Your backend validates a desktop token the same way as any other. For the complete macOS and Windows examples, see [Verify from a native desktop app](https://docs.radar.com/geo-compliance/verify-location.md#verify-from-a-native-desktop-app).

## See also

* [Geo-compliance overview and quickstart](https://docs.radar.com/geo-compliance/overview.md)
* [Fraud overview and quickstart](https://docs.radar.com/fraud/overview.md)
* [Geolocation token schema](https://docs.radar.com/api/geolocation-tokens.md)
* [iOS SDK](https://docs.radar.com/sdk/ios.md), [Android SDK](https://docs.radar.com/sdk/android.md), [Web SDK](https://docs.radar.com/sdk/web.md), [React Native SDK](https://docs.radar.com/sdk/react-native.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.