# Add identity verification to your mobile app

> Verify a person's ID document and selfie inside your iOS, Android, React Native or Flutter app with the Instance API and the hosted capture page in a WebView. Follow the four steps exactly.

Canonical URL: https://www.screenlyyid.com/docs/guides/identity-verification-mobile/

> **Agent rules (must follow)**
>
> - MUST create the instance on your **server** with `POST /api/v1/instance/create`, and MUST store the `CorrelationId` against the user.
> - MUST NOT put the API key in the app, and MUST NOT call the result APIs from the app. Only your back end calls `GET /api/v1/document/data` and `GET /api/v1/document/result`.
> - MUST open the returned `webEnrolmentUrl` in a WebView, and MUST use the exact event names `IDV_SESSION_COMPLETE` and `ERROR` with the `{ eventName, isError, error }` format.
> - MUST treat `ERROR` as a failure the user can restart.
> - MUST NOT build a custom camera, upload, liveness or face-match flow.
> - MUST NOT call the direct identity verification endpoints (enrolment, liveness, face match, `data/{sessionId}/...`), even if the developer asks. They are reference only. Identity verification always goes through the Instance API and the hosted `webEnrolmentUrl`.
> - MUST NOT call the result endpoints before `IDV_SESSION_COMPLETE`, and MUST NOT poll.
> - The canonical human page for this flow is [Mobile app](https://www.screenlyyid.com/docs/integrations/mobile-app/). If this guide and that page ever differ, tell the developer and follow that page.

## Summary

The mobile integration hands document and selfie capture to ScreenlyyID from a WebView inside your app, so users never leave your app. Your server creates an instance, the app opens the hosted capture page, the page tells the app when it is finished, and your server reads the decision. It works on any mobile platform that has a WebView.

## When to use it / when not to

**Use it for** verifying a person's identity document, face match and liveness inside a native or cross-platform mobile app.

**Do not use it for:**

- A web app: use [Identity verification (web)](https://www.screenlyyid.com/docs/guides/identity-verification-web/).
- Checks that need no document or selfie (BIN, phone, email, address, IP, eIDV, AML): see the [guides index](https://www.screenlyyid.com/docs/guides/).

## Before you start

- **API key:** `SCREENLYYID_API_KEY` on your **back end only**. `test_` for the sandbox, `prod_` for live. Never in the app. See [Get a test key](https://www.screenlyyid.com/docs/ai-quickstart/#get-a-test-key).
- **Base URL:** `https://api.screenlyyid.com`. The capture page is served over HTTPS only (`https://app.screenlyyid.com`).
- **Product:** `idv` goes in `GlobalScreening` in the instance call, and must be activated on the account.
- **A back end you control.** Mobile apps cannot hold the key. The [iOS sample app](https://github.com/ScreenlyyID/ios-sdk-example) has a small `backend/` for this; so do the [Express](https://www.screenlyyid.com/docs/recipes/express/) and [FastAPI](https://www.screenlyyid.com/docs/recipes/fastapi/) recipes (the same two routes).
- **A real device.** The camera does not work in the iOS simulator.

```bash
curl --request POST --url 'https://api.screenlyyid.com/api/v1/instance/create' \
  --header "x-api-key: $SCREENLYYID_API_KEY" --header 'Content-Type: application/json' \
  --data '{"GlobalScreening": ["idv"], "CustomerIntelligence": []}'
# { "CorrelationId": "...", "webEnrolmentUrl": "https://app.screenlyyid.com/idv/..." }
```

## Use it on its own or stacked

Identity verification can run on its own (`GlobalScreening: ["idv"]`) or in the same instance as other checks for the same customer, for example `["idv", "aml", "eidv1"]` for client onboarding. The capture flow below does not change: the other checks are server calls that send the same `CorrelationId`. See [Run several checks in one session](https://www.screenlyyid.com/docs/guides/stacking-checks/).

Document and selfie identity verification only goes through the Instance API and the hosted flow. The direct identity verification endpoints are reference only.

## Implementation steps

These are the four steps of the [Mobile app](https://www.screenlyyid.com/docs/integrations/mobile-app/) page, in the same order.

### Step 1: Create an instance (server)

Call `POST /api/v1/instance/create` from your back end. Save the `CorrelationId` against the user. Send only a verification id and the `webEnrolmentUrl` to the app. The response is `200` and the property names are exactly `CorrelationId` and `webEnrolmentUrl`.

```javascript
// back end route: POST /api/verifications  (Node 18+)
const r = await fetch("https://api.screenlyyid.com/api/v1/instance/create", {
  method: "POST",
  headers: { "x-api-key": process.env.SCREENLYYID_API_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({ GlobalScreening: ["idv"], CustomerIntelligence: [] }),
});
if (!r.ok) throw new Error(`instance/create failed (HTTP ${r.status})`);
const { CorrelationId, webEnrolmentUrl } = await r.json();
// save CorrelationId against the user; return { verificationId, webEnrolmentUrl } to the app
```

### Step 2: Open the WebView (app)

Ask for camera permission **before** loading the page, then load `webEnrolmentUrl` in a WebView. Add `?skipIntro=true` to skip the intro screen and go straight to capture. The page needs: JavaScript enabled, camera (and microphone) access, inline media playback, and HTTPS.

### Step 3: Listen for events (app)

The hosted page sends its events with `window.parent.postMessage({ eventName, isError, error }, "*")`. Inside a WebView there is no outer page, so the event arrives as a `message` event **inside the page**. The page sends it only this way: it has no iOS-, Android-, React Native- or Flutter-specific call. `iosListener`, `AndroidListener` and `FlutterListener` are names your app registers for its own bridge, and `ReactNativeWebView` is the object that `react-native-webview` provides; the script you inject forwards each `message` event to it. Every platform therefore does the same two things: inject a small script that listens for `message` events, and pass each event to the app. The names in the platform sections below are the names the samples register.

| Event | Meaning | What to do |
|---|---|---|
| `IDV_SESSION_COMPLETE` | The document and selfie have been processed and the results are stored. | Close the WebView and ask your back end for the result (Step 4). |
| `ERROR` (`isError` is `true`) | A fatal error while processing the images. `error` describes it. | Offer to restart: create a new instance and open the new `webEnrolmentUrl`. |

Act once: ignore further events after the first terminal event.

### Step 4: Get the result (back end)

When the app reports `IDV_SESSION_COMPLETE`, it calls **your** back end, which calls both endpoints once with `x-api-key` and the stored `x-correlation-id`:

```javascript
const headers = { "x-api-key": process.env.SCREENLYYID_API_KEY, "x-correlation-id": correlationId };
const [data, result] = await Promise.all([
  fetch("https://api.screenlyyid.com/api/v1/document/data", { headers }).then((r) => r.json()),
  fetch("https://api.screenlyyid.com/api/v1/document/result", { headers }).then((r) => r.json()),
]);
```

The `500 internal_error` response means the capture has not finished: you called too early. If you only call after `IDV_SESSION_COMPLETE` you will not see it.

## Platform code

All four platforms need the same things. Replace `webEnrolmentUrl` with the value from Step 1.

### iOS (Swift, WKWebView)

From the [iOS sample app](https://github.com/ScreenlyyID/ios-sdk-example) (`DemoCamera/ViewController.swift`, `HomeViewController.swift`, `Info.plist`).

`Info.plist`: `NSCameraUsageDescription` (and `NSMicrophoneUsageDescription`) with text that tells the user why.

```swift
import AVFoundation
import WebKit

// Before loading the page: AVCaptureDevice.authorizationStatus(for: .video)
//  .notDetermined -> AVCaptureDevice.requestAccess(for: .video), load only if granted
//  .denied / .restricted -> do not load; explain and offer to open Settings

class VerifyViewController: UIViewController, WKScriptMessageHandler {
    var webView: WKWebView!
    var url: URL!                // the webEnrolmentUrl
    private var finished = false

    override func viewDidLoad() {
        super.viewDidLoad()
        let config = WKWebViewConfiguration()
        config.preferences.javaScriptEnabled = true
        config.allowsInlineMediaPlayback = true      // the camera preview plays inside the page

        // forward the page's message events to the app
        let source = "window.addEventListener('message', function(e) { window.webkit.messageHandlers.iosListener.postMessage(JSON.stringify(e.data)) })"
        config.userContentController.addUserScript(WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false))
        config.userContentController.add(self, name: "iosListener")

        webView = WKWebView(frame: view.bounds, configuration: config)
        view.addSubview(webView)
        webView.load(URLRequest(url: url))
    }

    func userContentController(_ c: WKUserContentController, didReceive message: WKScriptMessage) {
        guard !finished, let body = message.body as? String,
              let event = try? JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any],
              let name = event["eventName"] as? String else { return }
        let isError = (event["isError"] as? Bool) ?? false
        if name == "IDV_SESSION_COMPLETE" && !isError {
            finished = true      // close the WebView, then ask YOUR back end for the result
        } else if name == "ERROR" {
            finished = true      // show event["error"], offer to restart with a new instance
        }
    }
}
```

### Android (Kotlin, WebView)

Manifest: `<uses-permission android:name="android.permission.CAMERA" />` (and `android.permission.INTERNET`). Request `CAMERA` at runtime before loading the page.

```kotlin
import android.webkit.*

class VerifyActivity : AppCompatActivity() {
    private lateinit var webView: WebView
    private var finished = false

    // exposed to the page's JavaScript as window.AndroidListener
    inner class Bridge {
        @JavascriptInterface
        fun onMessage(json: String) {
            runOnUiThread {
                if (finished) return@runOnUiThread
                val event = org.json.JSONObject(json)
                val isError = event.optBoolean("isError", false)
                when (event.optString("eventName")) {
                    "IDV_SESSION_COMPLETE" -> if (!isError) { finished = true /* close, ask YOUR back end for the result */ }
                    "ERROR" -> { finished = true /* show event.optString("error"), offer to restart */ }
                }
            }
        }
    }

    fun load(webEnrolmentUrl: String) {
        webView = findViewById(R.id.webview)
        webView.settings.javaScriptEnabled = true
        webView.settings.mediaPlaybackRequiresUserGesture = false
        webView.addJavascriptInterface(Bridge(), "AndroidListener")
        webView.webChromeClient = object : WebChromeClient() {
            override fun onPermissionRequest(request: PermissionRequest) {
                // grant the page's camera request once the app itself has the CAMERA permission
                runOnUiThread { request.grant(request.resources) }
            }
        }
        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                view.evaluateJavascript(
                    "window.addEventListener('message', function(e) { AndroidListener.onMessage(JSON.stringify(e.data)) })", null)
            }
        }
        webView.loadUrl(webEnrolmentUrl)
    }
}
```

### React Native (react-native-webview)

`npm install react-native-webview`. iOS: add `NSCameraUsageDescription` to `Info.plist`. Android: add the `CAMERA` permission to the manifest and request it with `PermissionsAndroid` before rendering the WebView.

```javascript
import { WebView } from "react-native-webview";

const forwardMessages = `
  window.addEventListener('message', function (e) {
    window.ReactNativeWebView.postMessage(JSON.stringify(e.data));
  });
  true;
`;

export function VerifyScreen({ webEnrolmentUrl, onComplete, onError }) {
  const done = React.useRef(false);
  return (
    <WebView
      source={{ uri: webEnrolmentUrl }}
      javaScriptEnabled
      allowsInlineMediaPlayback
      mediaPlaybackRequiresUserAction={false}
      mediaCapturePermissionGrantType="grant"
      injectedJavaScriptBeforeContentLoaded={forwardMessages}
      onMessage={(e) => {
        if (done.current) return;
        const event = JSON.parse(e.nativeEvent.data);
        if (event.eventName === "IDV_SESSION_COMPLETE" && !event.isError) { done.current = true; onComplete(); } // then ask YOUR back end for the result
        else if (event.eventName === "ERROR") { done.current = true; onError(event.error); }                      // offer to restart
      }}
    />
  );
}
```

### Flutter (webview_flutter)

`flutter pub add webview_flutter permission_handler`. iOS: `NSCameraUsageDescription` in `Info.plist`. Android: the `CAMERA` permission in the manifest. Request camera permission with `permission_handler` before creating the controller.

```dart
import 'dart:convert';
import 'package:webview_flutter/webview_flutter.dart';

late final WebViewController controller;
bool finished = false;

void startVerification(String webEnrolmentUrl, void Function() onComplete, void Function(String) onError) {
  controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..addJavaScriptChannel('FlutterListener', onMessageReceived: (JavaScriptMessage m) {
      if (finished) return;
      final event = jsonDecode(m.message) as Map<String, dynamic>;
      final isError = event['isError'] == true;
      if (event['eventName'] == 'IDV_SESSION_COMPLETE' && !isError) { finished = true; onComplete(); } // then ask YOUR back end for the result
      else if (event['eventName'] == 'ERROR') { finished = true; onError('${event['error']}'); }       // offer to restart
    })
    ..setNavigationDelegate(NavigationDelegate(onPageFinished: (_) {
      controller.runJavaScript(
          "window.addEventListener('message', function(e) { FlutterListener.postMessage(JSON.stringify(e.data)) })");
    }))
    ..loadRequest(Uri.parse(webEnrolmentUrl));
}
// Render it with WebViewWidget(controller: controller).
// For inline camera on Android, grant the page's request with AndroidWebViewController.setOnPlatformPermissionRequest.
```

## Reading the result

`GET /api/v1/document/result` returns the decision. The fields to use (see [Understanding results](https://www.screenlyyid.com/docs/data/understanding-results/)):

| Field | Type | Meaning |
|---|---|---|
| `Decision.Level` | string | ★ The overall confidence: `HIGH` (passed), `MEDIUM` (suspicious, additional checks recommended), `LOW` (not passed). |
| `LivenessResult.Result` | string | ★ `Live` or `Not Live`. |
| `FaceMatchResult.IsMatch` | boolean | ★ Whether the selfie matches the ID photo. |
| `Verifications.*` | object | Each data point (`DateOfExpiration`, `DocumentLiveness`, `FaceVerification`, `MrzOcrCrossCheck`, `OverallOcrFieldsConfidence`, `PassiveLiveness`) has a `Score` and a `Level` (`HIGH`, `MEDIUM`, `LOW`, `UNKNOWN`). |

`GET /api/v1/document/data` returns the data read from the document: `Country`, `DocumentType`, `DocumentVisualResults[]` (`Name`, `Value`, `Confidence`, `PageSide`), `DocumentMrzResults[]` and `AvailableImages`. It holds personal data: keep it on the server.

### Decision logic
```javascript
function nextStep(result) {
  const level = result.Decision.Level;                       // HIGH | MEDIUM | LOW
  const live = result.LivenessResult.Result === "Live";
  const match = result.FaceMatchResult.IsMatch;
  if (level === "HIGH" && live && match) return "approved";   // let the user continue
  if (level === "LOW" || !live || !match) return "rejected";  // not passed: offer a retry or a manual route
  return "needs_review";                                       // MEDIUM: additional checks or a person reviews
}
```

`MEDIUM` means "suspicious, additional checks recommended". What those checks are is your business decision.

## Errors and limits

| Status | When | Body |
|---|---|---|
| `400` | `instance/create`: a product code that does not exist or is not activated. Result endpoints: no `x-correlation-id` header. | Problem-details JSON, or `{"error": "correlation_id_required"}` |
| `401` | Missing or invalid `x-api-key` | Problem-details JSON |
| `500` | Result endpoints before the capture finished, or an unknown `CorrelationId` | `{"error": "internal_error", "message": "An unexpected error occurred"}` |

Event `ERROR`: restart with a new instance. No rate limit is documented for these calls.

## Test it

Use a `test_` key. **A real capture needs a camera and an ID document**, so complete it on a real device. The test is the four steps: instance created on the server, page opens and asks for the camera, the app receives `IDV_SESSION_COMPLETE` and your back end reads `document/result` once.

## Done when

- [ ] The instance is created on the server, the `CorrelationId` is stored per user, and the API key is nowhere in the app
- [ ] The app asks for camera permission before loading the page and handles a refusal
- [ ] The `webEnrolmentUrl` opens in a WebView with JavaScript, inline media and camera access working
- [ ] The app receives `IDV_SESSION_COMPLETE` and `ERROR` (exact names) and acts once
- [ ] On `IDV_SESSION_COMPLETE` the back end (not the app) calls `document/data` and `document/result` once with `x-api-key` and `x-correlation-id`
- [ ] `HIGH`, `MEDIUM` and `LOW` lead to approved, review and rejected, and `ERROR` restarts the flow
- [ ] Verified on a real device with a `test_` key

## Related

- [Mobile app](https://www.screenlyyid.com/docs/integrations/mobile-app/) (canonical human page) and the [iOS sample app](https://github.com/ScreenlyyID/ios-sdk-example)
- [Identity verification (web)](https://www.screenlyyid.com/docs/guides/identity-verification-web/)
- [Get hosted SDK document data](https://www.screenlyyid.com/docs/api-reference/hosted-sdk-data/get-document-data/), [Get hosted SDK decision result](https://www.screenlyyid.com/docs/api-reference/hosted-sdk-data/get-decision-result/)
- [Instance API](https://www.screenlyyid.com/docs/authentication/create-instance/), [Understanding results](https://www.screenlyyid.com/docs/data/understanding-results/), [Run several checks in one session](https://www.screenlyyid.com/docs/guides/stacking-checks/)
