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

# Verify location for compliance

> Run verified location checks for sportsbooks, casinos, fantasy, sweepstakes, and predictions, validate the geolocation token on your backend, and act on the pass or fail result.

By the end of this guide, your app will run a verified location check for the signed-in user and the selected product, and your backend will perform a restricted action, such as a wager, a contest entry, or a withdrawal, only when the geolocation token it verified has `passed` set to `true`. Sportsbooks, casinos, fantasy, sweepstakes, and predictions generally follow the same implementation pattern: configure allowed locations, run a check, validate the token on your backend, and act on `passed`. How often you check and re-check can differ by product and market.

## Complete example

This is the whole client side of one check on each platform.

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

final class LocationCheck: NSObject, CLLocationManagerDelegate {
  private let locationManager = CLLocationManager()

  func start() {
    Radar.initialize(publishableKey: "prj_test_pk_...")
    Radar.setUserId("user-123")
    Radar.setProduct("sportsbook")

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
  }

  func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
    let status = manager.authorizationStatus
    if status == .authorizedWhenInUse || status == .authorizedAlways {
      check(reason: "login")
    }
  }

  func check(reason: String) {
    Radar.trackVerified(
      beacons: false,
      desiredAccuracy: .medium,
      reason: reason,
      transactionId: nil
    ) { (status, token) in
      guard status == .success, let token = token, let jwt = token.token else {
        showCheckError(status)
        return
      }

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

```kotlin Kotlin theme={null}
import android.Manifest
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import io.radar.sdk.Radar
import io.radar.sdk.RadarInitializeOptions

class MainActivity : AppCompatActivity() {
  private val requestLocation =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants ->
      if (grants.values.any { it }) check("login")
    }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    Radar.initialize(
      context = this,
      publishableKey = "prj_test_pk_...",
      options = RadarInitializeOptions(fraud = true)
    )
    Radar.setUserId("user-123")
    Radar.setProduct("sportsbook")

    requestLocation.launch(
      arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION
      )
    )
  }

  private fun check(reason: String) {
    Radar.trackVerified(reason = reason) { status, token ->
      if (status != Radar.RadarStatus.SUCCESS || token == null) {
        showCheckError(status)
        return@trackVerified
      }

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

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

Radar.registerPlugin(createFraudPlugin());
Radar.initialize('prj_test_pk_...');
Radar.setUserId('user-123');
Radar.setProduct('sportsbook');

// false uses the Radar Verify app. true verifies in the browser without it.
const skipVerifyApp = false;

async function check(reason) {
  try {
    const result = await Radar.fraud.trackVerified({ skipVerifyApp, reason });

    if (result.passed) {
      await sendTokenToBackend(result.token);
    } else {
      showFailure(result.failureReasons);
    }
  } catch (err) {
    if (err instanceof Radar.fraud.errors.RadarVerifyAppError) {
      promptToOpenVerifyApp();
    } else {
      showCheckError(err.status);
    }
  }
}

check('login');
```

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

Radar.initialize('prj_test_pk_...', true);
Radar.setUserId('user-123');
Radar.setProduct('sportsbook');

async function check(reason) {
  const permission = await Radar.requestPermissions(false);
  if (permission !== 'GRANTED_FOREGROUND' && permission !== 'GRANTED_BACKGROUND') {
    showPermissionNeeded();
    return;
  }

  try {
    const { token } = await Radar.trackVerified({ reason });

    if (token?.passed) {
      await sendTokenToBackend(token.token);
    } else {
      showFailure();
    }
  } catch (err) {
    showCheckError(err);
  }
}

check('login');
```

```swift macOS theme={null}
import RadarVerifySDK

// Call once at launch. Requests location permission and warms up location services.
func start() {
  RadarVerify.setup()
}

func check(reason: String) async {
  let result = await RadarVerify.trackVerified(
    publishableKey: "prj_test_pk_...",
    userId: "user-123",
    product: "sportsbook",
    reason: reason
  )

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

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

```csharp Windows theme={null}
using System.Threading.Tasks;
using RadarVerify;

public static class LocationCheck
{
    // Call once at startup. Checks location permission and warms up location services.
    public static Task<RadarStatus> Start() => Radar.Setup();

    public static async Task Check(string reason)
    {
        var (status, token) = await Radar.TrackVerified(
            publishableKey: "prj_test_pk_...",
            userId: "user-123",
            product: "sportsbook",
            reason: reason);

        if (status != RadarStatus.Success || token == null)
        {
            ShowCheckError(status);
            return;
        }

        if (token.Passed)
        {
            await SendTokenToBackend(token.Token);
        }
        else
        {
            ShowFailure(token.FailureReasons);
        }
    }
}
```

The backend verifies the token and reads `passed`:

```javascript Node.js theme={null}
import express from 'express';
import { jwtVerify } from 'jose';
import { requireSession } from './auth.js';

const secret = new TextEncoder().encode(process.env.RADAR_JWT_SECRET_KEY);
const app = express();
app.use(express.json());

app.post('/api/wagers', requireSession, async (req, res) => {
  let payload;
  try {
    ({ payload } = await jwtVerify(req.body.geolocationToken, secret, {
      algorithms: ['HS256'],
    }));
  } catch (err) {
    return res.status(401).json({ error: 'invalid_geolocation_token' });
  }

  if (payload.user?.userId !== req.session.userId || payload.product !== 'sportsbook') {
    return res.status(401).json({ error: 'invalid_geolocation_token' });
  }

  if (payload.passed !== true) {
    return res.status(403).json({ passed: false, failureReasons: payload.failureReasons });
  }

  // Place the wager.
  res.status(201).json({ placed: true });
});
```

```python Python theme={null}
import os

import jwt  # PyJWT
from flask import Flask, jsonify, request, session

app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET_KEY"]
SECRET = os.environ["RADAR_JWT_SECRET_KEY"]


@app.post("/api/wagers")
def place_wager():
    if "user_id" not in session:
        return jsonify(error="not_signed_in"), 401

    body = request.get_json(silent=True) or {}
    try:
        payload = jwt.decode(body.get("geolocationToken", ""), SECRET, algorithms=["HS256"])
    except jwt.InvalidTokenError:
        return jsonify(error="invalid_geolocation_token"), 401

    user_id = (payload.get("user") or {}).get("userId")
    if user_id != session["user_id"] or payload.get("product") != "sportsbook":
        return jsonify(error="invalid_geolocation_token"), 401

    if payload.get("passed") is not True:
        return jsonify(passed=False, failureReasons=payload.get("failureReasons", [])), 403

    # Place the wager.
    return jsonify(placed=True), 201
```

## Prerequisites

* Fraud is enabled for your project under **Fraud** on the [Settings](https://dashboard.radar.com/settings#fraud-settings) page of the Radar dashboard.
* The Radar SDK and fraud plugin are installed, and device attestation is configured. See [Fraud plugin setup](https://docs.radar.com/sdk/fraud.md).
* A Test publishable key for your app, and your project's JWT secret key for your backend. See [Choose the right API key](https://docs.radar.com/fundamentals/authentication-and-access.md#choose-the-right-api-key).
* Foreground location permission on the device. See [Understand foreground and background location permissions](https://docs.radar.com/fundamentals/location-permissions.md).

## Configure allowed locations

Allowed countries and states are set in the **Fraud** section of the [Settings](https://dashboard.radar.com/settings#fraud-settings) page, once for the project and once for each product. Each list is an allowlist or a blocklist, and an empty list allows every country or state. A product setting overrides the project setting with the same name. Changes apply to checks made after you save, and tokens already issued keep their result until they expire.

## Choose manual or automatic checks

Call `Radar.setUserId()` with the ID your backend uses for the signed-in user, so that your backend can compare the token to the session. See [Handle login, logout, and user switching](https://docs.radar.com/fundamentals/authentication-and-access.md#handle-login-logout-and-user-switching).

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

| | Manual checks | Automatic checks |
| - | - | - |
| Who starts each check | Your app, with `Radar.trackVerified()` | The SDK, after one `Radar.startTrackingVerified()` call |
| 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 |
| Before a restricted action | Reuse your last token until it expires, then run a check | Call `Radar.getVerifiedLocationToken()`, which returns the last token if it is still valid and runs a check if not |
| `reason` and `transactionId` | You pass them on each check | Not passed on the checks the SDK starts |

The rest of this guide uses manual checks, as the [complete example](#complete-example) does. Choose automatic checks when you want a valid token ready for the whole session without scheduling checks yourself.

You can combine the two: run automatic checks for the session, and call `Radar.trackVerified()` with a `reason` and a `transactionId` before a single-use action, such as a withdrawal.

### Run automatic checks

Start automatic checks at login, after the user grants location permission, and stop them at logout. The SDK passes the token from each check to a listener, so that your app can send it to your backend. `sendTokenToBackend` is a function you write.

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

final class VerifiedSession: NSObject, RadarVerifiedDelegate {
  // At login.
  func start() {
    Radar.setVerifiedDelegate(self)
    Radar.startTrackingVerified(interval: 1200, beacons: false)
  }

  // Called after each check.
  func didUpdateToken(_ token: RadarVerifiedLocationToken) {
    if let jwt = token.token {
      sendTokenToBackend(jwt)
    }
  }

  // Before a restricted action.
  func currentToken(completion: @escaping (String?) -> Void) {
    Radar.getVerifiedLocationToken { (status, token) in
      guard status == .success, let token = token, token.passed else {
        completion(nil)
        return
      }
      completion(token.token)
    }
  }

  // When the user changes product.
  func changeProduct(_ product: String) {
    Radar.setProduct(product)
    Radar.clearVerifiedLocationToken()
  }

  // At logout.
  func stop() {
    Radar.stopTrackingVerified()
  }
}
```

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

class VerifiedSession {
  // At login.
  fun start() {
    Radar.setVerifiedReceiver(object : RadarVerifiedReceiver() {
      // Called after each check.
      override fun onTokenUpdated(context: Context, token: RadarVerifiedLocationToken) {
        sendTokenToBackend(token.token)
      }
    })
    Radar.startTrackingVerified(interval = 1200, beacons = false)
  }

  // Before a restricted action.
  fun currentToken(callback: (String?) -> Unit) {
    Radar.getVerifiedLocationToken { status, token ->
      if (status == Radar.RadarStatus.SUCCESS && token != null && token.passed) {
        callback(token.token)
      } else {
        callback(null)
      }
    }
  }

  // When the user changes product.
  fun changeProduct(product: String) {
    Radar.setProduct(product)
    Radar.clearVerifiedLocationToken()
  }

  // At logout.
  fun stop() {
    Radar.stopTrackingVerified()
  }
}
```

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

// At login. Called after each check.
Radar.fraud.onTokenUpdated((result) => {
  sendTokenToBackend(result.token);
});
Radar.fraud.startTrackingVerified({ interval: 1200, ipChanges: true });

// Before a restricted action.
async function currentToken() {
  const result = await Radar.fraud.getVerifiedLocationToken();
  return result && result.passed ? result.token : null;
}

// When the user changes product.
function changeProduct(product) {
  Radar.setProduct(product);
  Radar.fraud.clearVerifiedLocationToken();
}

// At logout.
function stop() {
  Radar.fraud.stopTrackingVerified();
}
```

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

// At login. Called after each check.
Radar.onTokenUpdated((token) => {
  sendTokenToBackend(token.token);
});
Radar.startTrackingVerified({ interval: 1200, beacons: false });

// Before a restricted action.
async function currentToken() {
  const { token } = await Radar.getVerifiedLocationToken();
  return token && token.passed ? token.token : null;
}

// When the user changes product.
function changeProduct(product) {
  Radar.setProduct(product);
  Radar.clearVerifiedLocationToken();
}

// At logout.
function stop() {
  Radar.stopTrackingVerified();
}
```

On web, automatic checks respond to IP address changes only when you pass `ipChanges: true`, and they use the companion app unless you pass `skipVerifyApp: true`. See [Choose the companion app or the no-download path](#choose-the-companion-app-or-the-no-download-path).

For every option, see [Manual and automatic checks](https://docs.radar.com/sdk/fraud.md#manual-and-automatic-checks) and the verified location section of the [iOS](https://docs.radar.com/sdk/ios.md#verified-location) or [Android](https://docs.radar.com/sdk/android.md#verified-location) SDK reference.

## Validate the response on the backend

Your backend decides, not your app. The `passed` value your app reads is for your UI. The backend block in the complete example is the minimum: verify the `HS256` signature and expiry with your project's JWT secret key, compare `user.userId` to the session user and `product` to the product of the action, then read `passed`. In production, also require `user.live` to be `true`, so that a Test environment token isn't accepted.

> [!WARNING]
>
> Always verify the token on your backend before a restricted action. Don't rely on a `passed` value from the client, and keep the JWT secret key out of client code.

For every validation step, see [Validate a token](https://docs.radar.com/api/geolocation-tokens.md#validate-a-token). If your project uses [encrypted responses](https://docs.radar.com/api/geolocation-tokens.md#encrypted-responses), decrypt the token before you verify it.

## Select the product

A product is a named configuration inside a project, such as `sportsbook`, `casino`, or `fantasy`, with its own allowed countries and states. You configure products in the **Fraud** section of the [Settings](https://dashboard.radar.com/settings#fraud-settings) page. Call `Radar.setProduct()` before the check with the product the user is using. `passed` in the token is the result for that product, so when the user switches product, set the new product and run a new check.

If you have one offering with one set of allowed locations, you don't need products. Leave out `Radar.setProduct()`.

To narrow a check to the jurisdiction of the user's session, call `Radar.setExpectedJurisdiction()` with a country code and a state code before the check (`Radar.fraud.setExpectedJurisdiction()` on web).

## Run checks at the right time

With manual checks, your app decides when each check runs. With [automatic checks](#run-automatic-checks), the SDK handles expiry and IP changes, and you clear the token when the user changes product.

Run the first check at login, before you show restricted features. After that, reuse the token until one of these happens:

* **The token expires.** Each token carries its own expiry in `expiresAt`, and tokens issued close to a border expire sooner. Compare the current time to `expiresAt` before each restricted action. Don't hardcode an interval. See [Expiry](https://docs.radar.com/api/geolocation-tokens.md#expiry).
* **The user changes product.** Call `Radar.setProduct()` with the new product, then run a check.
* **The SDK reports an IP change.** Implement `didChangeIP()` on your `RadarVerifiedDelegate` on iOS, override `onIpChanged()` on your `RadarVerifiedReceiver` on Android, or register a callback with `Radar.fraud.onIpChanged()` on web. In the callback, discard the last token and run a check.

Run one check at a time.

For a single-use action, such as a withdrawal, generate a `transactionId` on your backend, pass it to the check, and compare it to `transactionId` in the verified token.

Pass a `reason` on every check, such as `login`, `wager`, or `withdrawal`. Radar returns it in the token as `reason`, so use a small fixed set of values.

## Choose the companion app or the no-download path

On web, a check runs one of two ways. Choose the path for your product and market with your legal and compliance team:

* **Radar Verify companion app**: The user installs it once, and each check runs through the app.
* **No-download path**: The check runs in the browser and the user installs nothing.

| | Companion app | No-download |
| - | - | - |
| How it runs | The page talks to the Radar Verify app running on the user's computer. | The check runs in the browser. |
| What the user installs | [Radar Verify for Mac](https://app.radar-verify.com/mac/latest) or [Radar Verify for Windows](https://app.radar-verify.com/windows/latest) | Nothing |
| Signals | Adds remote desktop detection for the `sharing` flag, more advanced `mocked` and `proxy` detection, and more stable device IDs. | Browser signals only. |
| How to select it | Default. `skipVerifyApp` is `false`. | Pass `skipVerifyApp: true`. |
| When the app is missing | The call fails with `ERROR_VERIFY_APP` (`RadarVerifyAppError`). | Not applicable |

Pass `skipVerifyApp` to `Radar.fraud.trackVerified()`, `Radar.fraud.startTrackingVerified()`, and `Radar.fraud.getVerifiedLocationToken()`. Use the same value in all three.

With the companion app, tell the user to open or install Radar Verify when a check fails with `ERROR_VERIFY_APP`, then run the check again.

## Verify from a native desktop app

If your product is a native macOS or Windows app instead of a web page, the app runs the check itself with the Mac or Windows SDK, with no companion app. See the macOS and Windows tabs of the [complete example](#complete-example). The Mac and Windows SDKs are available on request. See [Desktop apps](https://docs.radar.com/sdk/fraud.md#desktop-apps).

## Handle results and errors

A failed check is a token with `passed` set to `false`. An error is a status other than success, with no token.

| Result or error | What it means | What to do |
| - | - | - |
| `passed` is `true` | The jurisdiction and fraud checks passed. | Send the token to your backend. |
| `passed` is `false` with a jurisdiction reason, such as `state_not_allowed` | The product isn't allowed at this location. | Say the product isn't available here. |
| `passed` is `false` with a fraud reason, such as `fraud_proxy_known_proxy_ip` | A device or network signal failed. | Say what to change, such as disconnecting from a VPN. |
| `ERROR_PERMISSIONS` | Location permission isn't granted. | Explain how to grant location access. |
| `ERROR_LOCATION` | The device couldn't determine a location. | Ask the user to turn on location services and Wi-Fi. |
| `ERROR_NETWORK`, `ERROR_SERVER` | The check didn't complete. | Run a new check after a short delay. |
| `ERROR_VERIFY_APP` | Web only. Radar Verify isn't running or isn't installed. | Prompt the user to open or install the app. |

For every reason and status, see [Failure and warning reasons](https://docs.radar.com/api/geolocation-tokens.md#failure-and-warning-reasons) and [Handle a technical error](https://docs.radar.com/api/geolocation-tokens.md#handle-a-technical-error).

## Test the integration

Use the Test environment and a named test user.

* **Passing case**: Sign in as the test user from an allowed state. Confirm that the token has `passed` set to `true` and that your backend performs the action.
* **Failing case**: On the **Block rules** page, create a rule that blocks the test user ID, then run a new check. Confirm that the token has `passed` set to `false` with `fraud_blocked_user_id`, and that your backend rejects the action. Remove the rule when you finish.

Bypass rules are for internal testing only. See [Force a pass or a fail](https://docs.radar.com/fundamentals/testing-and-launch.md#force-a-pass-or-a-fail).

## Production checklist

* [ ] Each product's country and state lists match your written list, and no list that is meant to restrict is empty.
* [ ] `Radar.setUserId()` and `Radar.setProduct()` are set before every check, and a product change triggers a new check.
* [ ] A token is reused only until its returned expiry, and one check runs at a time.
* [ ] Every restricted endpoint verifies the token's signature, expiry, user, product, and `user.live`, then reads `passed`. None reads a client-supplied `passed`.
* [ ] No JWT secret key in any client, and no bypass rule or test block rule in the Live environment.

## Build with an agent

Copy this prompt into a coding agent that has access to your repository.

```text theme={null}
Implement Radar verified location checks in this repository.
Read https://docs.radar.com/geo-compliance/verify-location.md, https://docs.radar.com/sdk/fraud.md,
and https://docs.radar.com/api/geolocation-tokens.md first, and follow them exactly.
Client: set the user ID and, if I use products, the product, then call
Radar.trackVerified() with a reason at login, on product change, on token expiry, and
when the SDK reports an IP change.
On web, ask me whether to use the Radar Verify companion app or the no-download path
(skipVerifyApp: true). Don't choose for me.
Backend: verify the HS256 token with the JWT secret key from an environment variable,
check expiry, user.userId, product, and user.live, then read passed.
Never act on a client-supplied passed value. Don't invent methods, fields, or defaults.
Add backend tests: passed true, passed false, tampered, expired, wrong user, wrong product.
```

## See also

* [Geolocation token schema](https://docs.radar.com/api/geolocation-tokens.md)
* [Fraud plugin setup](https://docs.radar.com/sdk/fraud.md)
* [Assess risk and verify location](https://docs.radar.com/fraud/assess-risk.md): includes verifying that a user is at a store, workplace, or address.


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