---
title: WIDTH Identity — Developer Documentation
lang: en
type: developer-guide
source: https://www.width.com/developer/
description: Developer integration documentation for WIDTH Identity, an identity verification (KYC/KYB) and AML transaction screening platform: server-side OpenAPI, Web/iOS/Android/Flutter SDKs, and outbound webhooks.
updatedAt: 2026-10-13
---

# WIDTH Identity Developer Documentation — Version 1.0 · Last Updated 2026-10-13

WIDTH Identity provides a complete identity verification and compliance platform supporting KYC, KYB, transaction screening, and continuous monitoring workflows. This guide covers all integration methods available to client developers.

### Integration Paths

#### Web SDK

Drop-in verification flow for web apps. Import one package, configure it with a fluent chain, and call `launch()` — the SDK presents its own modal or new tab and reports results through events. No DOM container required.

- Self-hosted modal — no DOM container
- KYC and KYB workflows
- ESM build, TypeScript types
- Event-driven results (GREEN / RED)

#### Mobile SDK (iOS / Android / Flutter)

Drop-in UI for mobile apps. The SDK handles the entire verification flow — document capture, liveness, OTP — and returns a result.

- Managed UI — minimal code
- KYC and KYB workflows
- Customizable themes
- Resume & lifecycle support
- Flutter plugin available

#### OpenAPI (Server-to-Server)

Backend integration via HTTPS REST API. Your server submits customer data step-by-step and receives workflow results.

- Full control over UX
- KYC, KYB, Transaction Screening
- Continuous Monitoring
- HMAC-SHA256 authentication

> **Which path to choose?**
>
> Use the **Web SDK** for a drop-in verification flow in the browser, or the **Mobile SDK** for the same turnkey experience in your mobile app with minimal development effort. Use the **OpenAPI** if you already collect customer data on your own forms and want full backend control. Both paths can be used together — e.g., SDK for frontend, OpenAPI for server-side polling and transaction screening. Workflows can also push results to your server via [Webhooks](#webhook-overview).

### Environments

| Resource | Staging | Production |
| --- | --- | --- |
| API Gateway | `https://api-gateway-platform.width.com/gateway` | `https://api-gateway.width.com/gateway` |
| Storage Service | `https://api-gateway-platform.width.com/storage` | `https://api-gateway.width.com/storage` |
| One Platform Console | `https://platform.width.com` | `https://app.width.com` |

### Credentials

Two types of credentials are issued from the One Platform Console under **API & Integration**:

| Credential Type | Used By | Fields |
| --- | --- | --- |
| **OPENAPI** | Server-to-server API | `apiKey` (`ak_`) + `apiSecret` (`sk_`) |
| **SDK** | Mobile SDK | `App Key` + `SDK Token` The SDK is initialized with the `sdkToken` only. |

#### How to Obtain Credentials

1. Log in to the One Platform Console → **API & Integration** Staging: `https://platform.width.com/saas/integration/api-keys` Production: `https://app.width.com/saas/integration/api-keys`
  - Staging: `https://platform.width.com/saas/integration/api-keys`
  - Production: `https://app.width.com/saas/integration/api-keys`
2. Click **Generate**
3. Note down the credentials: **OPENAPI** — `apiKey` (prefixed `ak_`) + `apiSecret` (prefixed `sk_`) **SDK** — `App Key` + `SDK Token`
  - **OPENAPI** — `apiKey` (prefixed `ak_`) + `apiSecret` (prefixed `sk_`)
  - **SDK** — `App Key` + `SDK Token`

> **Security**
>
> Never hard-code `apiSecret` in source code. Use environment variables or a secrets manager. Avoid passing secrets via command-line arguments (they may be recorded in shell history). The SDK Token is a public client identifier and is safe to ship in your app binary.

---

==================== GETTING STARTED ====================

## Getting Started

This section takes a technical integrator from zero to a first verification result: what to set up in the One Platform Console, the end-to-end path of a verification, how a workflow reaches a decision, and where to check your usage. Each step links to the detailed reference chapter below.

### Prerequisites (in the One Platform Console)

Before writing any code, set up the following in the [One Platform Console](#environments) for your target environment (Staging or Production):

1. **Sign in to the Console.** Use the Staging console to test and the Production console to go live (URLs in [Environments](#environments)).
2. **Confirm or create a Domain (Business Unit).** A Domain isolates one business line or region — its own workflows, members, and data. A new tenant ships with a `DEFAULT` domain; create more under **Admin Console → Domains / Business Units** if you need to separate environments or lines of business.
3. **Generate credentials.** Under **API & Integration**, generate the set for your path — `apiKey` + `apiSecret` for OpenAPI, or the SDK credential set for the Mobile SDK (see [Credentials](#environments)).
4. **Configure and publish your workflow.** In the Console, build the workflow you need (KYC, KYB, Transaction Screening, Web3, or Continuous Monitoring) and publish it. Each workflow corresponds to an `eventType` your integration references (see the [Event Types](#appendix-events) appendix).

### Your First Verification

1. **Choose an integration path.** Web SDK, Mobile SDK, or OpenAPI — see [Integration Paths](#integration-paths) for how to decide.
2. **Set the environment and credentials.** Point your client at the right base URLs and load the credentials from the prerequisites above (see [Environments](#environments)).
3. **Start a verification.** SDK path — initialize and launch ([Web](#web-quickstart), [iOS](#ios-quickstart), [Android](#android-quickstart), [Flutter](#flutter-quickstart)). OpenAPI path — register the applicant, submit node data, then poll for the result ([OpenAPI Reference](#api-getting-started), [KYC Flow](#api-kyc-flow)).
4. **Receive the result.** Poll `workflow.execution.status` (see [Workflow Lifecycle API](#api-workflow) for the pure server-side path), or have the workflow push results to your server with a [Webhook](#webhook-overview).
5. **Check the decision and your usage.** The final decision is recorded in the Admin Console; see [Workflows & the Decision Model](#workflow-decision) for how it is reached and [Usage & Quota](#usage-quota) for what each run consumes.

### Workflows & the Decision Model

A workflow is a sequence of nodes you arrange in the Console: data collection (document, liveness, applicant details) → checks (screening, rules) → decision. Knowing how a flow reaches its verdict tells you where to read intermediate results and where to intervene.

Workflows are selected automatically. WIDTH routes each request to the right workflow based on its `eventType` and the **source channel** it arrives on (Web SDK, iOS, Android, or OpenAPI) — you do not pass a workflow ID. For **KYC** and **KYB**, each source maps to exactly one active workflow (exclusive). **Transaction screening** is not exclusive — multiple workflows can coexist for the same event type.

- **The decision step runs last.** After the last user-input node, the workflow enters automatic processing — screening, rule evaluation, and the final decision — and lands in a terminal state: `COMPLETED` (decision recorded), `WAITING` (routed to manual review, then `COMPLETED`), or `FAILED`/`TIMEOUT`/`CANCELLED`. See the status table in [KYC Flow](#api-kyc-flow).
- **Read an intermediate result with a Webhook.** Add a **Webhook Action node** as a step in the flow to call out with that step's output — see [Webhook Concept](#webhook-concept).
- **Act on the decision.** Use the [Decision Webhook](#webhook-decision) to receive the final decision (action, code, reason, tags) and gate your downstream process on it.
- **Failure handling is set at the workflow level.** A failed or non-passing check stops the whole workflow according to the workflow's fault-tolerance setting: **Strict** (default — any node failure fails the workflow), **Lenient** (only a failure on a critical node fails it), or **Fully tolerant** (the flow continues regardless). This is a workflow-level setting, not per-node.

### Usage & Quota

Track consumption on the **Admin Console → Billing** page: your current **Plan** and **Usage Statistics** — API Calls, Cases Processed, Workflows, and Team Members — for the current billing cycle.

- Screening operations consume quota in the **Staging** environment as well, not only in Production.
- When you exceed your limit, the API Gateway returns `999501 REQUEST_API_EXCEED_LIMIT` — contact support to raise it (see [gateway error codes](#api-getting-started)).

---

==================== SDK - WEB ====================

## Web SDK Integration Guide

### Overview

The **Width Web SDK** provides a drop-in identity verification flow for web apps. It supports KYC and KYB workflows including document capture, liveness detection, and review. The SDK is self-hosted: you import one package, configure it with a fluent chain, and call `launch()` — the SDK presents its own modal or new tab and reports the outcome through events. No DOM container is required. It ships as an ESM build with full TypeScript types and no peer dependencies.

#### Requirements

| Requirement | Minimum |
| --- | --- |
| Module format | ESM (import) |
| TypeScript | Types included (optional) |
| Peer dependencies | None |
| Backend | Must issue a session token via `sdk.credentials` |

Web: get credentials

### Step 1: Get a session token (backend)

The Web SDK starts from a one-time session token (the `sdkToken`). Your server requests it from Width's `sdk.credentials` endpoint, then hands it to the browser. The public `apiKey` and `domainId` are configured in the next steps; the secret signing happens only on your server.

```
// Server-side request to Width (signed with your secret)
POST {WIDTH_GATEWAY_URL}/gateway?api=sdk.credentials&apiVersion=1.0.0&apiKey={your_apiKey}&sign=...
Content-Type: application/json

{}
```

```
// Response — read sdkToken and the domains[] list
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "data": {
      "sdkToken": "eyJhbGciOi...",
      "domains": [
        { "code": "DEFAULT", "name": "Default", "id": "dom_xxxxxxxx" }
      ]
    }
  }
}
```

Expose a small backend route (for example `/your-backend/sdk-token`) that returns the `sdkToken` and the `domainId` to your frontend. Pass the chosen `domainId` from `domains[]` into the SDK config in Step 3.

> **Each token is single-use**
>
> Each `sdkToken` is single-use. Reissue a new token whenever a user starts a new verification — do not cache or reuse it.

> The `sdk.credentials` call uses the same gateway base URL and HMAC signing as the rest of the API — see the **OpenAPI** section above for the endpoint, environments, and signature details.

Web Installation

### Step 2: Install the SDK

Install from npm. After install, import by the package name `@width-com/web-sdk` — ESM build, TypeScript types included, no peer dependencies. The tag you install also **selects the environment the SDK connects to**: as of this update, the default (latest) release targets **production** and the `@beta` tag targets the **platform** (testing) environment. Install the tag that matches the environment your `apiKey` belongs to, and confirm which address your installed build opens before you ship (see the note below).

```
# Production (正式环境)
npm install @width-com/web-sdk
# or
pnpm add @width-com/web-sdk
# or
yarn add @width-com/web-sdk

# Testing / beta (测试环境)
npm install @width-com/web-sdk@beta
# or
pnpm add @width-com/web-sdk@beta
# or
yarn add @width-com/web-sdk@beta
```

> **The tag selects the environment — a mismatch shows `Invalid apiKey`**
>
> The verification page address is compiled into each published version, so the environment is fixed at install time and `withConf` carries no field that changes it. As of this update, the default (latest) release opens `https://identity.width.com/sdk-page` (production) and `@beta` opens `https://identity-platform.width.com/sdk-page` (platform) — that pairing reflects the builds the two tags point at today, not a fixed rule, so check which host your installed build opens before you ship. If the tag does not match the environment your `apiKey` belongs to, that page renders `Invalid apiKey` and the flow stops there — backend OpenAPI calls made with the same key are unaffected, so the key itself is not the problem. Choose the tag by environment, not by version number. One key covers both sides: `withConf` declares a single key field, `apiKey`, and it is the same key you sign `sdk.credentials` with — the TypeScript declarations shipped inside the package list every field it accepts. For reference, `@beta` currently resolves to `1.0.0-beta.3` (published 2026-08-05) and the default to `1.0.1`; both carry `eventType` and `language`.

Web Quick Start

### Step 3: Initialize (Quick Start)

Build the verification with a fluent chain: `init` the session token, `withConf` the configuration, subscribe to events with `on` / `onMessage`, then `build().launch()`. `launch()` presents the self-hosted modal or new tab — you do not pass a DOM container.

```javascript
import { widthWebSdk } from '@width-com/web-sdk';

// Get the session token from your backend (sdkToken from sdk.credentials)
const { sdkToken, domainId } =
  await fetch('/your-backend/sdk-token').then(r => r.json());

widthWebSdk
  .init(sdkToken)
  .withConf({
    apiKey:     'ak_your_public_api_key', // required
    domainId,                             // required
    email:      'enduser@example.com',    // required
    customerId: 'cust_internal_id',       // required
    mode:       'modal',                  // 'modal' (default) | 'newtab'
    // eventType: 'KYC_EVENT',            // optional — 'KYC_EVENT' | 'KYB_EVENT'; omit for default routing
  })
  .on('idCheck.onApplicantVerificationCompleted', (payload) => {
    // payload.reviewResult.reviewAnswer: 'GREEN' (approved) | 'RED' (not approved)
  })
  .on('idCheck.onApplicantSubmitted', (payload) => {
    // Submitted; async review in progress
  })
  .on('idCheck.onError', (payload) => {
    // payload.code / payload.error
  })
  .onMessage((type, payload) => {
    if (type === 'width.onCancelled') {
      // User closed the flow
    }
  })
  .build()
  .launch();   // self-hosted modal / new tab — no DOM container needed
```

> **`eventType` and `language` require `1.0.1` or later**
>
> Both fields are available from `1.0.1` (released 2026-08-20), the current default (`latest`) release, and from `1.0.0-beta.3`, which the `@beta` tag currently resolves to — so both environments have them, and you still pick the tag by environment (see Step 2). Stable releases up to `1.0.0` do not contain them: a TypeScript project fails to compile, and a plain JavaScript project ignores them without any error. `eventType` accepts `KYC_EVENT` or `KYB_EVENT`, `language` accepts `en` or `zh`; both are optional, and omitting them keeps the default behaviour.

Web Configuration

### Configuration (withConf)

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `apiKey` | string | Yes | Public Width API Key (`ak_...`) |
| `domainId` | string | Yes | Business domain GID, from `domains[]` in `sdk.credentials` |
| `email` | string | Yes | End-user email |
| `customerId` | string | Yes | Your internal user ID |
| `mode` | `'modal' \| 'newtab'` | No | Presentation, default `'modal'` |
| `language` | `'en' \| 'zh'` | No | Interface language. Omit it and the interface is English; the browser language is not detected automatically. Available from `1.0.1`. |
| `eventType` | `'KYC_EVENT' \| 'KYB_EVENT'` | No | Which flow to run — individual verification (`KYC_EVENT`) or corporate verification (`KYB_EVENT`). Omit the field to keep the default routing (see [Workflows & the Decision Model](#workflow-decision)). Available from `1.0.1`. |
| `zIndex` | number | No | Modal stacking order |

Web Results

### Step 4: Handle the result

Branch on the events you subscribed to. The final verdict is carried by `reviewResult.reviewAnswer`. It takes exactly two values: `GREEN` when the outcome is approved, and `RED` for every other outcome.

```javascript
.on('idCheck.onApplicantVerificationCompleted', (payload) => {
  const { reviewResult, executionId } = payload;
  if (reviewResult.reviewAnswer === 'GREEN') {
    grantAccess(executionId);
  } else {
    handleNotApproved(executionId);
  }
})
```

Each event maps to a branch of your handling logic:

| Event | Handle |
| --- | --- |
| `idCheck.onApplicantVerificationCompleted` | Final verdict available — read `reviewAnswer` |
| `idCheck.onApplicantSubmitted` | Submitted; enters async review |
| `idCheck.onError` | Report the failure |
| `width.onCancelled` (via `onMessage`) | User closed the flow |

> **Reconciliation**
>
> `executionId` is the handle for matching against your backend / OpenAPI. Persist it on `idCheck.onApplicantSubmitted` (async review) so your server can poll the final status later.

#### Verification result reference

The final verdict is carried by `reviewResult.reviewAnswer`:

| `reviewAnswer` | Meaning |
| --- | --- |
| `GREEN` | Approved |
| `RED` | Not approved. The SDK maps every outcome other than an approval to `RED` — a rejection lands here, and so does any other non-approved result. Before treating `RED` as a rejection, read the case status (`caseStatus` from [`workflow.execution.status`](#api-workflow), or the case in the Console). |

> **Two values only**
>
> As of `1.0.1` (and `1.0.0-beta.3`), the Web SDK reduces the decision to these two values; there is no third value. Branch on `GREEN` for approval, and treat `RED` as “not approved” rather than “rejected” unless the case status confirms a rejection.

Web Methods

### Methods

| Call | Returns | Purpose |
| --- | --- | --- |
| `widthWebSdk.init(accessToken)` | builder | Start the chain with the session token |
| `.withConf(conf)` | builder | Provide configuration (see Configuration) |
| `.on(eventName, callback)` | builder | Subscribe to a single event |
| `.onMessage((type, payload) => {})` | builder | Receive all events with one handler |
| `.build()` | instance | Finish building |
| `instance.launch(container?)` | `string` | Start verification; returns the full verification-page URL for this session — of the form `https://identity.width.com/sdk-page?sdkMode=1&sdkSession=<session id>&apiKey=<your apiKey>&theme=light`, with the host taken from the build you installed (see Step 2) — and `''` when the launch fails. The URL addresses this one verification session; the session token behind it is single-use (see Step 1). `container` is ignored |
| `instance.close()` | `void` | Programmatically close the verification window |

Web Events

### Events

Subscribe to a single event with `.on(eventName, callback)`, or receive all with `.onMessage((type, payload) => {})`.

| Event | When | Payload |
| --- | --- | --- |
| `idCheck.onApplicantVerificationCompleted` | Flow complete, has a verdict | `{ reviewStatus: 'completed', reviewResult: { reviewAnswer: 'GREEN' \| 'RED' }, executionId }` |
| `idCheck.onApplicantStatusChanged` | Fires together with Completed | same as above |
| `idCheck.onApplicantSubmitted` | Submitted, async review | `{ executionId }` |
| `idCheck.onError` | Failure | `{ code, error, executionId? }` |
| `width.onCancelled` | User closed (via `onMessage` only) | `{}` |

> **Errors**
>
> Validation failures and runtime errors are all delivered via `idCheck.onError` — the SDK does not throw to your code.

Web Error Codes

### Error Codes

On `idCheck.onError`, `payload.code` is one of:

| Code | Meaning | Retryable |
| --- | --- | --- |
| `INVALID_INPUT` | Launch parameter missing or invalid | No |
| `SDK_ERROR` | Network, timeout, or internal error | Yes |
| `WORKFLOW_FAILED` | Flow ended in a non-success state | No |

Web Browser Support

### Browser Support

The Web SDK relies on `crypto.randomUUID`, ES2020 syntax, and a modern `fetch` / `postMessage`. The versions below are the earliest that carry all three; anything older is not supported.

| Browser | Minimum version |
| --- | --- |
| Chrome / Edge (desktop) | 92+ |
| Firefox | 95+ |
| Safari (macOS and iOS) | 15.4+ |
| Chrome (Android) | 92+ |

Web Troubleshooting

### Troubleshooting

| Symptom | Cause | Resolution |
| --- | --- | --- |
| `onError { INVALID_INPUT, "apiKey is required." }` | `apiKey` missing or empty | Pass the public API Key |
| `onError { INVALID_INPUT, "accessToken is required." }` | Backend didn't return `sdkToken` | Check the `sdk.credentials` integration |
| `onError { INVALID_INPUT, "domainId is required." }` | `domainId` not passed in `withConf` | Pass the `id` of the domain you picked from `domains[]` in the `sdk.credentials` response |
| `onError { INVALID_INPUT, "email is required." }` | Missing `email` | Pass the end-user email |
| `onError { INVALID_INPUT, "customerId is required." }` | Missing `customerId` | Pass the internal user ID |
| `onError { INVALID_INPUT, "email format is invalid." }` | Invalid email format | Validate in your form first |
| `onError { INVALID_INPUT, "apiKey does not match SDK credentials." }` | `apiKey` and `accessToken` belong to different apps | Reissue the token with the same `apiKey` |
| `onError { SDK_ERROR }` | Network / connection issue | Rebuild the chain and `launch()` again |
| Modal won't appear / iframe blocked | Domain not allowlisted, or CSP `frame-src` missing the origin | Add the origin under **API & Integration** in the Console (see the note below the table), then allow it in your CSP `frame-src` |
| Camera permission denied | Host `Permissions-Policy` is too strict | Update your policy headers (see note below) |
| No events fire | Session still ongoing, or callbacks not registered | Wait for completion; confirm your `.on()` callbacks |

> **Allowlist your site in the Console**
>
> The allowlist is yours to configure: add every origin that hosts the SDK under **API & Integration** in the Console. Each entry must start with `https://` or `http://`, carry no path, and use no wildcards, so list each host on its own line (for example `https://app.example.com` and `https://checkout.example.com`). If the button that generates a key is not on that page, the role on your account is missing the **manage API keys** permission — those controls render by permission, so they are hidden rather than greyed out; ask a tenant administrator to grant it.

> **CSP & Permissions-Policy**
>
> In `modal` mode the SDK inserts an iframe that loads the verification page into your own page, so if your page sets a Content-Security-Policy you must allow that origin under `frame-src`, and grant camera (plus the microphone / motion sensors used by liveness) to the same origin via `Permissions-Policy`. Which origin to write depends on the tag you installed (see Step 2): the default (`latest`, currently `1.0.1`) build loads `https://identity.width.com`, and the `@beta` build loads `https://identity-platform.width.com`. Send the block that matches the build you ship — if the origin is absent from `frame-src`, the browser blocks the iframe and the verification window stays blank.

```
# Default (latest) build / 默认（latest）版
Content-Security-Policy: frame-src https://identity.width.com;
Permissions-Policy: camera=(self "https://identity.width.com"),
                    microphone=(self "https://identity.width.com"),
                    accelerometer=(self "https://identity.width.com"),
                    gyroscope=(self "https://identity.width.com")

# @beta build / @beta 版
Content-Security-Policy: frame-src https://identity-platform.width.com;
Permissions-Policy: camera=(self "https://identity-platform.width.com"),
                    microphone=(self "https://identity-platform.width.com"),
                    accelerometer=(self "https://identity-platform.width.com"),
                    gyroscope=(self "https://identity-platform.width.com")
```

---

==================== iOS SDK ====================

## iOS SDK Integration Guide

### Overview

The **Width Identity SDK** provides a drop-in identity verification flow for iOS applications. It supports KYC and KYB workflows. You `import WidthIdentity` and call one entry point; the SDK presents the full capture / liveness / review UI and returns a single result. The public API uses Swift-native types (enums with associated values, structs, closures) and is consumed from Swift.

#### Requirements

| Requirement | Minimum |
| --- | --- |
| iOS | 16.0+ deployment target |
| Xcode | 16+ |
| Dependency manager | Swift Package Manager or CocoaPods |

iOS Installation

### Installation

#### Option A: Swift Package Manager (Recommended)

`WidthIdentity-iOS` is a **private** repository — until your GitHub account has been granted access to it, both Xcode and `git` report it as not found, so make sure that access is in place before you run the steps below.

In Xcode: **File > Add Package Dependencies…** and enter:

```
https://github.com/width-com/WidthIdentity-iOS.git
```

Or in `Package.swift`:

```
dependencies: [
    .package(url: "https://github.com/width-com/WidthIdentity-iOS.git", from: "1.0.11"),
],
targets: [
    .target(name: "MyApp", dependencies: [
        .product(name: "WidthIdentity", package: "WidthIdentity-iOS"),
    ]),
]
```

#### Option B: CocoaPods

`WidthIdentity` is published to Width's private Specs repo, so declare that source in your `Podfile`:

That Specs repo is private as well — `pod install` can only resolve it once your GitHub account has been granted access to it; without that access the source reads as not found.

```
source 'https://github.com/width-com/Specs.git'
source 'https://cdn.cocoapods.org/'   # default trunk, for any public pods

target 'YourApp' do
  pod 'WidthIdentity', '~> 1.0.11'
end
```

Then `pod install`.

#### Info.plist Permissions

The SDK token is no longer stored in `Info.plist`. It is passed at runtime via `CredentialsConfig.sdkToken` (see Quick Start). Declare the camera, microphone and speech-recognition usage descriptions — all three are required; the photo-library description is optional:

```xml
<!-- Required: document capture and liveness -->
<key>NSCameraUsageDescription</key>
<string>Used to capture identity documents and complete the liveness check.</string>

<!-- Required: document verification records background audio (anti-fraud) -->
<key>NSMicrophoneUsageDescription</key>
<string>Used to record background audio during document verification to help prevent fraud.</string>

<!-- Optional: only if you let users pick a document image from the photo
     library. The SDK uses the system PhotosPicker, which does not strictly
     require this key. -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Used to select identity document images.</string>

<!-- Required by App Store ingestion, never requested at runtime (see below) -->
<key>NSSpeechRecognitionUsageDescription</key>
<string>This app does not request speech recognition.</string>
```

`NSCameraUsageDescription` and `NSMicrophoneUsageDescription` are both mandatory: the document-scan flow records background audio as an anti-fraud measure, so the app **crashes at runtime without the microphone key**. There is no SDK environment Info.plist key.

`NSSpeechRecognitionUsageDescription` is mandatory for a different reason. The SDK never asks for speech recognition, but `AwsLiveness.xcframework` statically absorbs Amplify's Predictions plugin, which references `SFSpeechRecognizer`. App Store **ingestion** rejects the upload without the key (error `ITMS-90683`) — after the whole binary has transferred, and regardless of the API never being called. State plainly in the string that the app does not use it; nothing will ever display it, because the permission is never requested.

#### Bundled frameworks

The package ships eight xcframeworks — `WidthIdentity`, `SecCamera`, `onnxruntime`, `AwsLiveness`, `Veriff`, `DocumentReader`, `DocumentReaderCore` and `RegulaCommon` — and embeds all of them automatically. `AwsLiveness` is self-contained: you do not add any Amplify or AWS dependency of your own.

iOS Quick Start

### Quick Start

`import WidthIdentity` exposes two equivalent entry styles — use whichever you prefer. Both drive the identical verification UI.

#### Direct input (UIKit)

```
import UIKit
import WidthIdentity

final class ViewController: UIViewController {
    func startVerification() throws {
        let input = try VerificationInput(
            credentials: CredentialsConfig(
                domain:   "YOUR_DOMAIN",
                sdkToken: "YOUR_SDK_TOKEN"
            ),
            customer: CustomerConfig(
                // Both customerId and email are required and must be non-empty.
                customerId: "user-123",
                email:      "user@example.com"
            )
        )

        WIDTHVerification.present(from: self, input: input) { result in
            switch result {
            case .completed(let id, let decision):  // .approved / .rejected / .review
                print("done:", id, decision)
            case .waiting(let id):                  print("waiting:", id)
            case .dismissed(let id):                print("dismissed:", id ?? "(no execution)")
            case .cancelled(let id):                print("cancelled:", id)
            case .failed(let code, let message, _): print("failed:", code, message)
            }
        }
    }
}
```

#### Direct input (SwiftUI)

```
import SwiftUI
import WidthIdentity

struct ContentView: View {
    @State private var presenting = false
    @State private var customerId = ""
    @State private var email = ""

    var body: some View {
        Button("Verify") { presenting = true }
            .widthVerification(isPresented: $presenting, input: {
                // Lazy closure — built only when the cover is about to present.
                try VerificationInput(
                    credentials: CredentialsConfig(
                        domain: "YOUR_DOMAIN", sdkToken: "YOUR_SDK_TOKEN"
                    ),
                    customer: CustomerConfig(customerId: customerId, email: email)
                )
            }) { result in
                // If the input closure throws, you'll receive .failed(code: "W-INIT-410", ...) here.
            }
    }
}
```

#### Handler-style entry (alternative)

`WIDTHMobileSDK` is an alternative, object-based entry — construct it, set properties / handler closures, then `present`.

```
import WidthIdentity

let sdk = WIDTHMobileSDK(accessToken: "YOUR_SDK_TOKEN")   // RiskSec sdkToken
sdk.credentials = .init(domain: "YOUR_DOMAIN")   // appId/apiKey decoded from accessToken
sdk.applicant   = .init(customerId: "user-123", email: "user@example.com")
sdk.dayNightMode = .night                                 // optional; omit to follow the system
sdk.language     = .zh                                     // optional; .en (default) / .zh

sdk.verificationHandler { isApproved in
    print(isApproved ? "approved" : "finally rejected")
}
sdk.onStatusDidChange { sdk, _ in
    print("status:", sdk.status, "exec:", sdk.executionId ?? "-")
    if let fail = sdk.failReason { print("failed:", fail.code, fail.message) }
}
sdk.onEvent { _, event in /* INFO/WARN/ERROR lifecycle log */ }   // optional

sdk.present(from: self)
```

SwiftUI:

```
Button("Verify") { presenting = true }
    .widthMobileSDK(isPresented: $presenting) {
        let sdk = WIDTHMobileSDK(accessToken: "YOUR_SDK_TOKEN")
        sdk.credentials = .init(domain: "YOUR_DOMAIN")   // appId/apiKey decoded from accessToken
        sdk.applicant   = .init(customerId: customerId, email: email)
        sdk.verificationHandler { isApproved in /* ... */ }
        return sdk
    }
```

> `accessToken` carries the `sdkToken`; the other credentials are set on the client via `sdk.credentials` / `sdk.applicant`. Invalid configuration (missing credentials / applicant) surfaces as `sdk.status == .failed` with `sdk.failReason`.

#### Event logging (optional)

Direct-input entry takes an `SdkEventLogger` to receive SDK lifecycle events (INFO / WARN / ERROR) in your own pipeline (Crashlytics, DataDog, etc.); PII is redacted before the callback fires. The handler-style entry exposes the same stream via `sdk.onEvent`.

```
final class MyLogger: SdkEventLogger {
    func onEvent(level: SdkLogLevel, tag: String, message: String, error: Error?) {
        // forward to your logging backend
    }
}

let input = try VerificationInput(credentials: ..., customer: ..., eventLogger: MyLogger())
```

iOS Configuration

### Configuration Reference

Same input structure as Android: `VerificationInput`, `CredentialsConfig` (`domain` + `sdkToken`) and `CustomerConfig` (`customerId` + `email`, both required). See [Android Configuration Reference](#android-config) for field details. On iOS the `VerificationInput` initializer is `throws` and additionally accepts an optional `eventLogger`.

iOS-specific entry points and theme overrides:

| Symbol | Purpose |
| --- | --- |
| `WIDTHVerification.present(from:input:completion:)` | UIKit native entry point |
| `View.widthVerification(isPresented:input:onResult:)` | SwiftUI native entry point |
| `WIDTHMobileSDK(accessToken:)` + `credentials`/`applicant` + `present(from:)` | UIKit handler-style entry |
| `View.widthMobileSDK(isPresented:makeSDK:)` | SwiftUI handler-style entry |
| `ThemeConfig` / `ThemeMode` | Optional theme override |
| `UILanguage` | Optional UI language (`.en` default / `.zh`) |

iOS Results

### Handling Results

#### Direct-input `VerificationResult`

Five Swift enum cases (mirrors Android's five variants):

| Case | When |
| --- | --- |
| `.completed(executionId, .approved)` | Server approved |
| `.completed(executionId, .rejected)` | Server rejected |
| `.completed(executionId, .review)` | Submission is under manual review out-of-band |
| `.waiting(executionId)` | Await server notification for the final decision |
| `.dismissed(executionId?)` | User exited intending to return later (resumable); `executionId` is `nil` if the workflow had not started |
| `.cancelled(executionId)` | User explicitly discarded; execution destroyed, **not resumable** |
| `.failed(code, message, executionId?)` | Internal error |

> **Dismissed vs Cancelled**
>
> `.dismissed` means the user paused and can resume; `.cancelled` means the user discarded and the server execution is destroyed (not resumable). `executionId` may be `nil` if a failure occurred before an execution was created; when present, include it in support tickets for faster troubleshooting.

#### Handler-style entry

`verificationHandler { (isApproved: Bool) }` fires on the final approve/reject decision. `sdk.status` (`WIDTHStatus`): `.approved`, `.finallyRejected`, `.pending` (manual review), `.incomplete` (mid-flow exit / waiting, resumable), `.cancelled` (destroyed), `.failed`. `sdk.failReason` (`WIDTHException`) when `.failed`: one of `.initialization`, `.network`, `.api`, `.permission`, `.workflow`, `.unknown` — each exposing `code` and `message`.

iOS Theme

### Theme Customization

The verification UI follows the system appearance by default. Force a mode with `dayNightMode`; omit it to follow the system.

```
let sdk = WIDTHMobileSDK(accessToken: "YOUR_SDK_TOKEN")
sdk.dayNightMode = .night   // optional; omit to follow the system
```

iOS Lifecycle

### Resume & Lifecycle

Same behavior as Android. On iOS, the swipe-to-dismiss gesture on the presented sheet is disabled during an active workflow to prevent accidental progress loss.

| User Choice | Behavior | Result | Resumable? |
| --- | --- | --- | --- |
| Pause & Exit (keep progress) | Server execution kept alive | `.dismissed` | Yes |
| End Verification (discard) | Server cancel, execution destroyed | `.cancelled` | No |

To resume, present the verification again with the same `customerId`. The SDK auto-detects in-progress workflows.

iOS Permissions

### Permissions

| Permission | Info.plist Key | Required | Purpose |
| --- | --- | --- | --- |
| Camera | `NSCameraUsageDescription` | Yes | Document capture, liveness |
| Microphone | `NSMicrophoneUsageDescription` | Yes | The document-verification flow records background audio as an anti-fraud measure |
| Photo Library | `NSPhotoLibraryUsageDescription` | No | Only if users pick a document image from the photo library (system PhotosPicker does not strictly require it) |
| Speech recognition | `NSSpeechRecognitionUsageDescription` | Yes | Checked by App Store ingestion. The permission is never requested at runtime, so the user never sees this string |

> **Camera and microphone are both mandatory.** The document-scan step records background audio as an anti-fraud measure, so a missing `NSMicrophoneUsageDescription` causes a hard crash at launch. `NSSpeechRecognitionUsageDescription` is mandatory as well, but for App Store ingestion rather than at runtime (see Installation). There is no SDK environment Info.plist key (no location key, no token key). Network: HTTPS via URLSession, no `NSAppTransportSecurity` exceptions needed.

**App Thinning:** XCFramework supports App Thinning. Bitcode is not embedded (deprecated in Xcode 14). If you encounter issues with release builds, verify that **Strip Swift Symbols** (`STRIP_SWIFT_SYMBOLS`) is set to its default value (`YES`) in your app target.

iOS Troubleshooting

### Troubleshooting

| Issue | Solution |
| --- | --- |
| No such module 'WidthIdentity' | **SPM:** File > Packages > Resolve Package Versions. Confirm the `WidthIdentity` library product is added under **Target > General > Frameworks, Libraries, and Embedded Content**. **CocoaPods:** declare the private `source 'https://github.com/width-com/Specs.git'`, run `pod install`, and open `.xcworkspace` (not `.xcodeproj`). |
| `.failed` on launch (e.g. `W-INIT-410`) | The `VerificationInput` initializer throws on a blank `domain` / `sdkToken`, or a blank `customerId` / `email`; a thrown input closure surfaces as `.failed`. Verify all four are non-empty. |
| Camera not working | Ensure `NSCameraUsageDescription` is present in `Info.plist` with a non-empty description. If the user previously denied access, iOS will not re-prompt — the SDK detects this and shows a guidance screen directing the user to **Settings > YourApp > Camera**. |
| Theme colors not applied | Verify hex values, case-sensitive tokens, correct theme map |
| SwiftUI sheet not presenting | Attach `.widthVerification` / `.widthMobileSDK` to a view in the hierarchy, not conditionally |
| UIKit: "not in window hierarchy" | Present from a view controller after `viewDidAppear` |
| Liveness screen is in the wrong language | The AWS liveness screen follows the **device** language, not the SDK's `language` setting. The rest of the flow still honours `sdk.language`. |

> **Upgrading:** bump the version constraint (the SPM `from:` value or the Podfile version) and resolve packages.

---

==================== ANDROID SDK ====================

## Android SDK Integration Guide

### Overview

The **Width Identity SDK** provides a drop-in identity verification flow for Android applications. It supports KYC and KYB workflows including document capture, liveness detection, and review. The SDK runs in its own Activity; you add a single dependency and call one entry point, and the SDK returns a single result.

#### Requirements

| Requirement | Minimum |
| --- | --- |
| Android SDK | API 26 (Android 8.0)+ |
| compileSdk | 36 — the published SDK artifacts declare `minCompileSdk=36` in their AAR metadata, and the build tooling enforces it, so a lower value fails the build |
| Kotlin | 1.9+ |
| Gradle / AGP | 8.0+ |
| Java | 11 source/target |
| Host app | Jetpack Compose-based or View-based (the SDK runs in its own Activity) |

Android Installation

### Installation

#### Step 1: Add the Maven Repository

In `settings.gradle.kts`. The Width repo serves the SDK plus its Width-hosted transitive dependencies (`com.width.risksec`, `com.width.camera`); everything else (AndroidX / Kotlin / Ktor / CameraX) resolves from Google + Maven Central.

The document-capture engines bundled inside the SDK are vendor-hosted, not on Width's Maven, so add their repositories as well — they are required at build time even if a capture provider goes unused. Paste the two provider blocks below exactly as shown.

```
dependencyResolutionManagement {
    repositories {
        maven { url = uri("https://maven.width.com/repository/sdk-releases/") }
        google()
        mavenCentral()

        // Document-capture provider repository (bundled transitively; required to resolve)
        maven {
            url = uri("https://cdn.veriff.me/android/")
            content { includeGroup("com.veriff") }
        }
        // Document-reader provider repository (bundled transitively; required to resolve)
        maven {
            url = uri("https://maven-master.regulaforensics.com/RegulaDocumentReader/")
            content {
                includeGroup("com.regula.documentreader")
                includeGroup("com.regula.documentreader.core")
                includeGroup("com.regula.common")
            }
        }
    }
}
```

#### Step 2: Add the Dependency

In app-level `build.gradle.kts`. A single coordinate transitively pulls the camera, liveness, and supporting libraries — no BOM, no extra coordinates.

```
dependencies {
    implementation("com.width.identity:sdk-activity:1.0.11")
}
```

> **`minSdk` requirement:** the SDK requires `minSdk 26`.

#### Step 3: Required Build Settings

Two settings belong to **your** app module, not to the SDK. The build fails without them — neither touches your source code.

**Core library desugaring is required.** The bundled AWS Rekognition liveness engine ships Amplify AARs whose metadata declares `requires core library desugaring`, and AGP enforces that on the **app** side (`checkReleaseAarMetadata` / `checkDebugAarMetadata`) regardless of your `minSdk`. Add to your app module:

```
android {
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
}
```

**`android.uniquePackageNames=false` is required on AGP 9.** Two artifacts pulled in transitively by the AWS liveness engine (`com.google.ai.edge.litert:litert-support` and `litert-support-api`, both 1.4.1) declare the same library namespace `org.tensorflow.lite.support` — an upstream packaging bug. AGP 9's manifest merger validates namespace uniqueness and fails the build with `Validation failed, exiting`. Add to your project's `gradle.properties`:

```
# gradle.properties
android.uniquePackageNames=false
```

> **No more BOM or UI coordinate**
>
> Earlier integrations used a `sdk-bom` platform plus a separate `sdk-ui-width-modern` coordinate. These are no longer needed — `sdk-activity` aggregates everything.

> **SDK token moved**
>
> The SDK token is no longer registered via an `AndroidManifest.xml` `<meta-data>` entry / `strings.xml`. It is now passed at runtime as the `sdkToken` field inside `CredentialsConfig` (see Quick Start).

Android Quick Start

### Quick Start

The SDK exposes two equivalent entry styles — use whichever fits your call site. Both drive the identical verification UI and return a single result.

#### Direct input (ActivityResultContract)

```
import com.width.identity.activity.CredentialsConfig
import com.width.identity.activity.CustomerConfig
import com.width.identity.activity.ThemeConfig
import com.width.identity.activity.UILanguage
import com.width.identity.activity.Verification
import com.width.identity.activity.VerificationInput
import com.width.identity.activity.VerificationResult

class MainActivity : ComponentActivity() {

    private val launcher =
        registerForActivityResult(Verification()) { result ->
            when (result) {
                is VerificationResult.Completed ->   // .APPROVED / .REJECTED / .REVIEW
                    Log.i(TAG, "done: ${result.executionId} ${result.decision}")
                is VerificationResult.Waiting ->
                    Log.i(TAG, "waiting: ${result.executionId}")
                is VerificationResult.Dismissed ->
                    Log.i(TAG, "dismissed: ${result.executionId ?: "(no execution)"}")
                is VerificationResult.Cancelled ->
                    Log.i(TAG, "cancelled: ${result.executionId}")
                is VerificationResult.Failed ->
                    Log.w(TAG, "failed: ${result.code} ${result.message}")
            }
        }

    private fun startVerification() {
        val input = VerificationInput(
            credentials = CredentialsConfig(
                domain   = "YOUR_DOMAIN",
                sdkToken = "YOUR_SDK_TOKEN",
            ),
            customer = CustomerConfig(
                // Both customerId and email are required and must be non-blank.
                customerId = "user-123",
                email      = "user@example.com",
            ),
            theme = ThemeConfig(themeMode = "SYSTEM"),   // optional: "SYSTEM" / "LIGHT" / "DARK"
            eventType = "KYC_EVENT",   // optional: "KYC_EVENT" / "KYB_EVENT" to skip in-SDK selection; omit to let the user pick
            language = UILanguage.ZH,  // optional: UILanguage.EN (default) / .ZH; omit = English (does not follow device locale)
        )
        launcher.launch(input)
    }
}
```

#### Builder entry (Compose)

A fluent builder assembles the launch input in a single chain — supply the access token + credentials + applicant, set optional handlers, then build and launch. It delivers a single `WIDTHCompletionResult`. Register the launcher in composition with the `WIDTHVerification` contract, then build and launch at the call site.

```
import androidx.activity.compose.rememberLauncherForActivityResult
import com.width.identity.activity.WIDTHCompletionResult
import com.width.identity.activity.WIDTHDayNightMode
import com.width.identity.activity.WIDTHMobileSDK
import com.width.identity.activity.WIDTHVerification

@Composable
fun VerifyButton() {
    val launcher = rememberLauncherForActivityResult(WIDTHVerification()) { result ->
        when (result) {
            is WIDTHCompletionResult.SuccessTermination ->   // see status table
                Log.i(TAG, "done: ${result.status} ${result.executionId}")
            is WIDTHCompletionResult.AbnormalTermination ->
                Log.w(TAG, "failed: ${result.exception.code} ${result.exception.message}")
        }
    }

    Button(onClick = {
        WIDTHMobileSDK.Builder()
            .withAccessToken("YOUR_SDK_TOKEN")                 // RiskSec sdkToken (encodes appId/apiKey)
            .withCredentials(domain = "YOUR_DOMAIN")           // only domain is client-supplied
            .withApplicant(customerId = "user-123", email = "user@example.com")
            .withEventType("KYC_EVENT")                        // optional; "KYC_EVENT"/"KYB_EVENT" to skip in-SDK selection
            .withForcedDayNightMode(WIDTHDayNightMode.NIGHT)   // optional; omit to follow the system
            .withHandlers(onEvent = myLogger)                  // optional; see Event logging
            .withLauncher(launcher)
            .build()
            .launch()
    }) { Text("Verify") }
}
```

This is an **optional entry style**, not a separate launch path: the builder assembles a native `VerificationInput` and reuses the same flow underneath. The `withAccessToken` value is the `sdkToken`, which itself encodes the tenant `appId` / `apiKey` (decrypted on-device); only `domain` is client-supplied via `withCredentials`, and the applicant identity via `withApplicant`.

`withEventType` is optional (`"KYC_EVENT"` / `"KYB_EVENT"`) — set it to launch straight into that flow and skip the in-SDK selection screen; omit it to let the user pick.

> `VerificationInput(...)` throws `IllegalArgumentException` on a blank `domain` / `sdkToken`, a blank `customerId` / `email`, or an `eventType` that is a non-empty value other than `"KYC_EVENT"` / `"KYB_EVENT"`; `build()` throws if a required builder field was not set. Catch it at the call site.

#### Event logging (optional)

Register an `SdkEventLogger` to receive SDK lifecycle events (INFO / WARN / ERROR) in your own pipeline (Crashlytics, Timber, DataDog, etc.). Known PII is redacted before the callback fires. `SdkEventLogger` is a functional interface, so a lambda works anywhere one is expected.

```
import com.width.identity.activity.SdkLogLevel
import com.width.identity.activity.SdkLogging

SdkLogging.setLogger { level, tag, message, throwable ->
    when (level) {
        SdkLogLevel.INFO  -> Log.i(tag, message)
        SdkLogLevel.WARN  -> Log.w(tag, message, throwable)
        SdkLogLevel.ERROR -> Log.e(tag, message, throwable)
    }
}
```

The logger is global and optional; call `SdkLogging.setLogger(null)` to stop forwarding. You can also register the same logger inline on the builder via `withHandlers(onEvent = ...)`.

Android Configuration

### Configuration Reference

#### `VerificationInput`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `credentials` | `CredentialsConfig` | Yes | SDK authentication |
| `customer` | `CustomerConfig` | Yes | Customer identity |
| `theme` | `ThemeConfig` | No | UI theme customization |
| `eventType` | String | No | `"KYC_EVENT"` / `"KYB_EVENT"` to skip the in-SDK selection screen; omit to let the user pick |
| `language` | `UILanguage` | No | UI language: `UILanguage.EN` (default) / `.ZH` |

#### `CredentialsConfig`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `domain` | String | Yes | Tenant identifier for multi-tenant routing |
| `sdkToken` | String | Yes | SDK token (previously registered via manifest `<meta-data>`) |

#### `CustomerConfig`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `customerId` | String | Yes | Unique customer identifier (must be non-blank) |
| `email` | String | Yes | Customer email address (must be non-blank) |

> **Both fields now required**
>
> Both `customerId` and `email` must be provided and non-blank. If either is blank, construction throws `IllegalArgumentException`. (This tightens the earlier rule, which only required at least one of the two.)

#### Public API

`com.width.identity.activity` is the only customer-facing package — everything else is internal and produces a compile error if referenced from your app.

| Symbol | Purpose |
| --- | --- |
| `Verification` | `ActivityResultContract` entry point |
| `VerificationInput` / `CredentialsConfig` / `CustomerConfig` | Launch parameters |
| `VerificationResult` / `VerificationDecision` | Direct-input result |
| `WIDTHMobileSDK.Builder` + `WIDTHVerification` | Builder entry point (Compose) |
| `WIDTHCompletionResult` / `WIDTHStatus` / `WIDTHException` | Builder result types |
| `ThemeConfig` / `WIDTHDayNightMode` | Optional theme / day-night override |
| `UILanguage` | Optional UI language (`EN` default / `ZH`) |
| `SdkLogging` / `SdkEventLogger` / `SdkLogLevel` | Optional event log callback |

#### `UILanguage`

| Value | Description |
| --- | --- |
| `EN` | English (default) |
| `ZH` | Simplified Chinese |

Omitting `language` keeps English — the SDK does not follow the device locale. Third-party capture screens have limits: Veriff shows Chinese only when the device is online and the tenant integration enables it (English otherwise); Regula supports Simplified Chinese only.

Android Results

### Handling Results

#### Direct-input `VerificationResult`

`VerificationResult` is a sealed class with five variants:

| Result | Fields | Description |
| --- | --- | --- |
| `Completed` | `executionId`, `decision` | Server returned a decision: `APPROVED` / `REJECTED` / `REVIEW` (under manual review out-of-band) |
| `Waiting` | `executionId` | Await server notification for the final decision |
| `Dismissed` | `executionId?` | User exited intending to return later (X → keep progress, or pre-workflow exit). The server execution is kept alive so the next launch resumes; `executionId` is `null` if the workflow had not started. **Resumable.** |
| `Cancelled` | `executionId` | User explicitly discarded the verification (X → discard). The SDK awaited `workflow.execution.cancel` on the server, so the execution is destroyed and **cannot be resumed.** |
| `Failed` | `code`, `message`, `executionId?` | Internal error |

> **Dismissed vs Cancelled**
>
> The single old `Cancelled` case is now split: `Dismissed` means the user paused and can resume; `Cancelled` means the user discarded and the server execution is destroyed (not resumable).

#### Builder `WIDTHCompletionResult`

| Case | When |
| --- | --- |
| `SuccessTermination(status, executionId?)` | Flow ended normally; final state carried by `status` |
| `AbnormalTermination(exception, executionId?)` | Technical failure; `exception.code` / `exception.message` carry detail |

`status` is a `WIDTHStatus`: `Approved`, `FinallyRejected`, `Pending` (manual review), `Incomplete` (resumable / dismissed), `Cancelled` (destroyed). `exception` is a `WIDTHException`: one of `Init`, `Network`, `Api`, `Permission`, `Workflow`, `Unknown` — each exposing `code` and `message`.

Android Theme

### Theme Customization

#### ThemeMode

| ThemeMode | Behavior |
| --- | --- |
| `"SYSTEM"` | Follows device setting |
| `"LIGHT"` | Forces light theme |
| `"DARK"` | Forces dark theme |

Set the mode via `ThemeConfig`, or override day/night on the Builder entry point. Omit either to follow the system setting.

```
ThemeConfig(themeMode = "SYSTEM")   // "SYSTEM" / "LIGHT" / "DARK"

// On the Builder entry point — omit to follow the system:
.withForcedDayNightMode(WIDTHDayNightMode.NIGHT)
```

Android Lifecycle

### Resume & Lifecycle

| User Choice | Behavior | Result | Resumable? |
| --- | --- | --- | --- |
| Pause & Exit (keep progress) | Server execution kept alive | `Dismissed` | Yes |
| End Verification (discard) | Server cancel, execution destroyed | `Cancelled` | No |

To resume, call `launcher.launch(...)` with the same `customerId`. The SDK auto-detects in-progress workflows.

Android Permissions

### Permissions

The SDK and its bundled capture engines declare every permission they need, and they are merged into your app automatically — you do not declare or request them:

```xml
<!-- WIDTH identity SDK core -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Added transitively by the capture / liveness engine -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />

<!-- Added transitively by the document-reader engine -->
<uses-permission android:name="android.permission.FLASHLIGHT" />
```

| Permission | Type | Purpose / Source |
| --- | --- | --- |
| `CAMERA` | Runtime | Document capture, liveness (SDK core) |
| `INTERNET` | Install-time | API communication (SDK core) |
| `ACCESS_NETWORK_STATE` | Install-time | Connectivity checks (SDK core) |
| `RECORD_AUDIO` | Runtime | Merged by the capture / liveness engine |
| `NFC` | Install-time | Merged by the capture / liveness engine |
| `WAKE_LOCK` | Install-time | Merged by the capture / liveness engine |
| `VIBRATE` | Install-time | Merged by the capture / liveness engine |
| `FLASHLIGHT` | Install-time | Merged by the document-reader engine |

> The runtime (dangerous) permissions are `CAMERA` and `RECORD_AUDIO`; the SDK and its capture engines request them from inside their own Activities, so your app does not prompt for them. Every permission above appears in your app's permission listing and **must be reflected in your Google Play Data Safety disclosure**. The SDK requires no storage / media permission — picking a document image uses the system photo picker.

**ProGuard / R8:** The SDK ships with embedded consumer rules. No additional configuration needed.

Android Troubleshooting

### Troubleshooting

| Issue | Solution |
| --- | --- |
| Failed to resolve `com.width.identity:...` | Ensure the Width Maven repo is in `settings.gradle.kts` (not `build.gradle.kts`), and that you use the single coordinate `com.width.identity:sdk-activity:1.0.11` (no BOM). If the artifacts that fail to resolve are `com.veriff` or `com.regula.*`, the two provider repositories from Step 1 are missing. |
| `IllegalArgumentException` on launch | Check that `domain` / `sdkToken` and both `customerId` and `email` are non-blank. Also check `eventType`: if you pass it, the value must be exactly `"KYC_EVENT"` or `"KYB_EVENT"`. |
| Camera not working | Check the merged manifest for permission conflicts; the SDK auto-merges `CAMERA` from its library manifest. |
| Theme colors not applied | Verify hex values (no `#` prefix), case-sensitive token names |
| Build fails on `checkReleaseAarMetadata` / `checkDebugAarMetadata` with `requires core library desugaring` | Enable core library desugaring in your app module and add the `desugar_jdk_libs` dependency — see Installation, Step 3. This is enforced regardless of your `minSdk`. |
| Build fails on the same AAR metadata check because the module's `compileSdk` is lower than the SDK requires | The SDK's AARs declare `minCompileSdk=36` in their AAR metadata and the build tooling enforces it, so a module compiling against anything lower stops the build. Set `compileSdk = 36` in your app module — see Requirements. This is separate from `minSdk`, which stays 26. |
| Manifest merge fails with `Validation failed, exiting` on AGP 9 | Add `android.uniquePackageNames=false` to your project's `gradle.properties` — see Installation, Step 3. |

> **Upgrading:** bump the version string in your `build.gradle.kts`; Gradle fetches the new artifacts from `maven.width.com` on the next sync.

---

==================== SDK - FLUTTER ====================

## Flutter SDK Integration Guide

### Overview

The **WIDTH Identity SDK** ships as a drop-in Flutter plugin for the identity verification flow (KYC and KYB). You add one dependency and call one entry point; the native SDK presents the full capture / liveness / review UI full-screen and returns a single result. The plugin wraps the native iOS and Android SDKs — iOS and Android only (no web or desktop).

> Plugin `1.0.2` — pins iOS SDK `1.0.11` and Android SDK `1.0.11`. Upgrading the plugin upgrades the native SDKs together; do not override the native dependencies manually.

#### Requirements

| Requirement | Minimum |
| --- | --- |
| Flutter | 3.10+ |
| iOS | 16.0+ deployment target, Xcode 16+, CocoaPods |
| Android | minSdk 26 (Android 8.0), compileSdk 36, core library desugaring enabled (see Android below) |

> **Credentials must match the build environment**
>
> The native SDKs are **single-environment** — each published build talks to one WIDTH environment, baked in at build time. The versions pinned by this release are production builds, so the `domain` / `accessToken` WIDTH issues you must be production credentials too. A token from another environment never gets past the SDK's security init, surfacing as `W-RISK-102`.

Flutter Installation

### Installation

The plugin repository and the private Specs repo its iOS side pulls from both require your GitHub account to have been granted access first — until then `flutter pub get` and `pod install` report them as not found.

The plugin is distributed through WIDTH's private Git repository. Add it to your `pubspec.yaml`:

```
dependencies:
  flutter_width_identity_sdk_plugin:
    git:
      url: https://github.com/width-com/WidthIdentity-Flutter.git
      ref: 1.0.2
```

Then `flutter pub get`.

#### iOS

The native `WidthIdentity` pod resolves from WIDTH's private Specs repo. Declare both sources at the top of `ios/Podfile` and set the platform:

```
source 'https://github.com/width-com/Specs.git'
source 'https://cdn.cocoapods.org/'   # default trunk, for any public pods

platform :ios, '16.0'
```

Then `cd ios && pod install`.

#### Android

Set `minSdk 26` in `android/app/build.gradle`. The plugin registers the WIDTH Maven repository, the vendor capture repositories (Veriff, Regula), and the native dependency automatically.

Two build settings are required by the native SDK's bundled AWS liveness engine — both on **your app**, neither involves your source code:

```
// android/app/build.gradle.kts
android {
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
}
```

The engine's Amplify AARs declare "requires core library desugaring" in their metadata, and AGP enforces that on the app module regardless of your `minSdk`; without it the build fails outright.

```
# android/gradle.properties — AGP 9 only
android.uniquePackageNames=false
```

On AGP 9 the manifest merger validates library namespace uniqueness, and two artifacts the liveness engine pulls in transitively (`com.google.ai.edge.litert:litert-support` and `litert-support-api`) declare the same namespace `org.tensorflow.lite.support` — an upstream packaging bug. Without the flag the build fails with `Validation failed, exiting`.

If your project enforces `RepositoriesMode.FAIL_ON_PROJECT_REPOS`, declare the repositories in `android/settings.gradle` instead:

```
dependencyResolutionManagement {
    repositories {
        maven { url = uri("https://maven.width.com/repository/sdk-releases/") }
        google()
        mavenCentral()
        maven {
            url = uri("https://cdn.veriff.me/android/")
            content { includeGroup("com.veriff") }
        }
        maven {
            url = uri("https://maven-master.regulaforensics.com/RegulaDocumentReader/")
            content { includeGroupByRegex("com\\.regula.*") }
        }
    }
}
```

Flutter Permissions

### Permissions

**iOS** — add to `ios/Runner/Info.plist`. Camera, microphone and speech recognition are required; the photo library key is optional:

```xml
<!-- Required: document capture and liveness. -->
<key>NSCameraUsageDescription</key>
<string>Used to capture identity documents and complete the liveness check.</string>
<!-- Required: the document verification provider records background audio
     (anti-fraud) — the app crashes at runtime without this key. -->
<key>NSMicrophoneUsageDescription</key>
<string>Used by the document verification provider during video capture.</string>
<!-- Required by App Store ingestion; never requested at runtime (a linked but
     unreachable API inside the AWS liveness component). -->
<key>NSSpeechRecognitionUsageDescription</key>
<string>This app does not request speech recognition.</string>
<!-- Optional: only if your app also lets users pick a document image from the
     photo library. -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Used to select identity document images.</string>
```

**Android** — the native SDK's manifest merges its permissions automatically; you declare nothing. The runtime (dangerous) permissions are `CAMERA` and `RECORD_AUDIO` (the latter bundled by the capture / liveness engine), requested by the SDK inside its own Activity. See [the Android Permissions section](#android-permissions) for the full list, and reflect every permission in your Google Play Data Safety disclosure.

Flutter Quick Start

### Quick Start

Import the plugin, build the SDK with a fluent chain, and `await sdk.launch()`. The future resolves when the native flow closes.

```
import 'package:flutter_width_identity_sdk_plugin/flutter_width_identity_sdk_plugin.dart';

final sdk = WIDTHMobileSDK.init(sdkToken)
    .withCredentials(domain: domain) // tenant routing domain (appId/apiKey are inside the token)
    .withApplicant(customerId: 'C_abc123', email: 'user@example.com')
    .withEventType(WIDTHEventType.kyc)               // optional; omit → user picks KYC/KYB in-SDK
    .withForcedDayNightMode(WIDTHDayNightMode.night) // optional; omit → follows system
    .withLanguage(WIDTHLanguage.zh)                  // optional; omit → English (never the device locale)
    .withHandlers(
      onStatusChanged: (newStatus, prevStatus) { /* terminal status change */ },
      verificationHandler: (isApproved) { /* final approve / reject only */ },
    )
    .build();

final result = await sdk.launch(); // resolves when the native flow closes

switch (result.status) {
  case WIDTHStatus.approved:        // final decision: approved
  case WIDTHStatus.finallyRejected: // final decision: rejected
  case WIDTHStatus.pending:         // under manual review
  case WIDTHStatus.incomplete:      // mid-flow exit / waiting; resumable
  case WIDTHStatus.cancelled:       // discarded; not resumable
  case WIDTHStatus.failed:          // see result.exception
}
```

#### Event logging (optional)

Pass an `onEvent` handler to receive SDK lifecycle events (INFO / WARN / ERROR) in your own pipeline (Crashlytics, DataDog, etc.); PII is redacted before the callback fires.

```
.withHandlers(
  onEvent: (event) {
    // event.level / event.tag / event.message
  },
)
```

#### UI language (optional)

`withLanguage(WIDTHLanguage.zh)` switches the flow to Simplified Chinese — the SDK's own copy plus the backend's `{en, zh}` dynamic content. Omitting it keeps English: the native SDKs never follow the device locale, so existing integrations are unaffected.

The bundled third-party capture screens have their own limits: the document-scan provider shows Chinese only when the device is online and the tenant integration enables it (English otherwise), and the document reader supports Simplified Chinese only.

Flutter Results

### Handling Results

`launch()` always resolves; it never throws for SDK-level failures.

| `result.status` | When |
| --- | --- |
| `approved` | Server approved |
| `finallyRejected` | Server rejected |
| `pending` | Submission is under manual review out-of-band |
| `incomplete` | User exited mid-flow or decision still pending; resumable with the same `customerId` |
| `cancelled` | User explicitly discarded the verification; **not resumable** |
| `failed` | Internal error; see `result.exception` |

When `.failed`, `result.exception` (`WIDTHException`) carries a `type` — one of `initialization`, `network`, `api`, `permission`, `workflow`, `unknown` — with the original `code` (e.g. `W-LIV-499`) and `message` preserved. `result.executionId` identifies the run for support.

Flutter API Reference

### API Reference

| Symbol | Purpose |
| --- | --- |
| `WIDTHMobileSDK.init(accessToken)` | Entry point, returns the builder |
| `WIDTHMobileSDKBuilder` | `withCredentials` / `withApplicant` / `withEventType` / `withForcedDayNightMode` / `withLanguage` / `withHandlers` / `build()` |
| `WIDTHMobileSDK.launch()` | Presents the flow; resolves with the result |
| `WIDTHMobileSDKResult` | `status` / `success` / `exception` / `executionId` |
| `WIDTHStatus` / `WIDTHException` / `WIDTHExceptionType` | Status / error |
| `WIDTHSDKEvent` / `WIDTHLogLevel` | Event log |
| `WIDTHEventType` | Optional KYC/KYB flow pre-selection |
| `WIDTHDayNightMode` | Forced theme |
| `WIDTHLanguage` | Optional UI language (`en` default / `zh`) |

> **Upgrading:** bump the `ref` tag in `pubspec.yaml` and run `flutter pub get`. Each plugin release pins the native SDK versions it was verified against — do not override the native dependencies manually.

---

==================== OPENAPI REFERENCE ====================

## OpenAPI Reference

Server-to-server integration via HTTPS REST API. All requests are `HTTP POST` to the Gateway URL.

### Getting Started

#### Base URL

| Environment | Gateway URL |
| --- | --- |
| Staging | `https://api-gateway-platform.width.com/gateway` |
| Production | `https://api-gateway.width.com/gateway` |

#### Request Format

```http
POST {base_url}?api={apiName}&apiVersion=1.0.0&apiKey={apiKey}&sign={sign}
Content-Type: application/json
x-domain: {domainId}

{JSON body}
```

| Parameter | Location | Required | Description |
| --- | --- | --- | --- |
| `api` | Query | Yes | API name |
| `apiVersion` | Query | Yes | Varies per interface — `workflow.apply.submit` recommends `2.0.0`, others use `1.0.0` (see [Workflow Lifecycle API](#api-workflow-submit)) |
| `apiKey` | Query | Yes | Your API key |
| `sign` | Query | Yes | HMAC-SHA256 signature of request body |
| `x-domain` | Header | Yes | Your business domain ID |

#### Response Format

Success:

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": { ... }
}
```

Error:

```json
{
  "apiCode": 999001,
  "apiMsg": "SIGN_ERROR",
  "data": null
}
```

> **Two layers to read.** The HTTP status is transport-level — `4xx`/`5xx` means the gateway did not accept the request (no `data`). On HTTP `200`, read `apiCode` for the gateway result (`200` = OK). Some business endpoints then wrap their result in a second `{ code, data, msg }` layer under `data` — so the business payload is at `data.data` (see the Register Customer example below).

#### Error Codes

| apiCode | apiMsg | Description | Action |
| --- | --- | --- | --- |
| 200 | OK | Success | — |
| 999000 | GATEWAY_ERROR | General gateway error | Contact support |
| 999001 | SIGN_ERROR | Signature verification failed | See Authentication |
| 999301 | API_INVALID_REQUEST | Malformed or invalid request | Check request body |
| 999302 | API_NOT_FOUND | API name not found | Verify `api` parameter |
| 999303 | API_NON_AUTHORIZED | Not authorized for this API | Check apiKey permissions |
| 999304 | RATE_LIMIT_TRY_AGAIN | Rate limit exceeded | Wait and retry |
| 999401 | SERVICE_TIME_OUT | Backend service timeout | Retry with backoff |
| 999402 | SERVICE_INVOKE_ERROR | Backend invocation failed | Retry; contact support if persistent |
| 999403 | SERVICE_NOT_FOUND | Backend service unavailable | Contact support |
| 999404 | SERVICE_RESPONSE_FORMAT_ERROR | Unexpected response from backend | Contact support |
| 999501 | REQUEST_API_EXCEED_LIMIT | API call quota exceeded | Contact support to increase limits |

#### Idempotency

All node data submission APIs are **idempotent** based on `callbackKey`. Submitting the same `callbackKey` multiple times is safe — only the first successful submission takes effect. This allows safe retries on network timeouts.

#### Interaction Model

- **Client-Side (App/Web): Chain-Driven Flow.** Your frontend is driven by the `nextStep` object returned in each submission response. No global polling required. Only poll dedicated `.data` endpoints for async tasks like OCR.
- **Server-Side (Tenant Backend): Final Status Polling.** After the last user-input node, poll `workflow.execution.status` at relaxed intervals (1–5 min) until terminal state.

---

===== Authentication =====

### Authentication

#### Signature Computation

```
sign = HmacSHA256(apiSecret, requestBody)
```

Both key and body use **UTF-8** encoding. The result is a 64-character lowercase hex string. The signature must be computed on the **exact bytes** sent as the HTTP body.

#### Code Examples

**Java:**

```java
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(apiSecret.getBytes("UTF-8"), "HmacSHA256"));
byte[] hash = mac.doFinal(requestBody.getBytes("UTF-8"));
String sign = HexFormat.of().formatHex(hash); // Java 17+
```

**Python:**

```python
import hmac, hashlib

sign = hmac.new(
    api_secret.encode('utf-8'),
    request_body.encode('utf-8'),
    hashlib.sha256
).hexdigest()
```

**Node.js:**

```javascript
const crypto = require('crypto');
const sign = crypto.createHmac('sha256', apiSecret)
    .update(requestBody, 'utf8').digest('hex');
```

---

===== Configuration =====

### Configuration

Retrieve platform configuration data (country lists, document types, form templates, etc.) before starting a workflow.

**Endpoint:** `prepare.avira.config` `POST`

```json
{
  "keys": "particular,avira_ssic,avira_ssoc,avira_countries,avira_document_master,avira_document_default_rule,required-form,avira_phone_code,avira_entity_types,ownership_structure_layer,transaction_behaviour,product_service_complexity,source_of_wealth,avira_source_of_funds"
}
```

#### Configuration Keys

| Key | Description | Used By |
| --- | --- | --- |
| `particular` | Personal/corporate information field definitions | Particular nodes (KYC & KYB) |
| `required-form` | Form templates with validation rules | Required Forms nodes |
| `avira_countries` | Country list (ISO codes + names) | Nationality, residence, etc. |
| `avira_document_master` | Supported document types per country | OCR & document upload |
| `avira_document_default_rule` | Default document requirements | Required document nodes |
| `avira_ssic` | Industry classification codes | Industry field |
| `avira_ssoc` | Occupation classification codes | Occupation field |
| `avira_phone_code` | Country phone codes | Phone verification |
| `avira_entity_types` | Corporate entity types | KYB particular |
| `ownership_structure_layer` | Ownership structure depth settings | KYB workflows |
| `transaction_behaviour` | Transaction behaviour categories | KYB forms |
| `product_service_complexity` | Product/service complexity categories | KYB forms |
| `source_of_wealth` | Source of wealth options | KYC/KYB forms |
| `avira_source_of_funds` | Source of funds options | KYC/KYB forms |

> **Caching** — Configuration data changes infrequently. Cache it locally and refresh daily or on demand.

---

===== Workflow Lifecycle API =====

## Workflow Lifecycle API

The Workflow Lifecycle API is the pure server-side integration path: your backend submits an event, polls for the execution status and the Case decision, and — when a request is lost or retried — queries whether the customer already has an execution in flight. Three endpoints form one closed loop.

This differs from the node-driven SDK path documented under [KYC](#api-kyc) / [KYB](#api-kyb), where the client submits data node by node. Here the platform runs the entire published workflow end to end and you only submit and poll.

### Flow Overview

Submit

→

↻ Poll until caseStatus is terminal Poll Status

caseStatus ∈ {APPROVED, REJECTED, CLOSED}→

Case Decision

`workflow.apply.query` sits before this loop as a recovery path: call it when a `submit` may have already happened (timeout or upstream retry) to avoid submitting twice.

#### Billing

| API | Purpose | Billed |
| --- | --- | --- |
| `workflow.apply.submit` | Start a workflow execution | **Yes** — charged per eventType |
| `workflow.execution.status` | Read execution status + Case decision by executionId | No |
| `workflow.apply.query` | Check whether a customer already has an execution | No |

> All three endpoints use the same gateway base URL, the same query-string request envelope (`api` / `apiVersion` / `apiKey` / `sign`) plus the `x-domain` header, and the same HMAC-SHA256 request-body signing as every other OpenAPI call. See [**OpenAPI Reference → Getting Started**](#api-getting-started) for the base URL (Staging `api-gateway-platform.width.com/gateway` / Production `api-gateway.width.com/gateway`) and request format, and [**Authentication**](#api-authentication) for the full signing rules.

---- Submit ----

### Submit a Workflow

**Endpoint:** `workflow.apply.submit` `POST`

Routes to the currently published (PUBLISHED) workflow by `eventType + source` and starts an execution.

#### apiVersion

| apiVersion | Behaviour |
| --- | --- |
| `1.0.0` | Auto-routes by `eventType + source` |
| `2.0.0` | Everything in 1.0.0 plus an optional `workflowId` to name the published workflow explicitly; an empty `workflowId` behaves exactly like 1.0.0. **Recommended.** |

#### Request

```json
{
  "eventType": "KYC_EVENT",
  "source": "API",
  "data": {
    "customerId": "demo-customer-001",
    "fullName": "ZHANG SAN",
    "dateOfBirth": "1990-01-01",
    "nationality": "CN"
  },
  "workflowId": ""
}
```

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `eventType` | string | Yes | Event type: `KYC_EVENT` / `KYB_EVENT` / `TRANSACTION_EVENT` / `WEB3_TRANSACTION_EVENT` / `MANUAL_CASE_EVENT`, subject to the events enabled for your tenant. The Console labels the first two **KYC** and **KYB** — those are display names; the API expects `KYC_EVENT` and `KYB_EVENT`. `MANUAL_CASE_EVENT` submits a subject for [name screening](#api-name-screening); it appears as **Manual** in the Console. |
| `source` | string | Yes | Origin. Server-side integrations always send `API`. |
| `data` | object | Yes | Business payload. `customerId` is required and must stay stable for the same customer (`workflow.apply.query` relies on it for recovery); the remaining fields follow the field definitions of the workflow’s entry event. |
| `workflowId` | string | No | 2.0.0 only. Names a published workflow; empty means auto-route by event. |

#### Response

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "message": null,
    "executionId": "exec-7208f03b931e4897",
    "status": "EXECUTING",
    "requestId": "...",
    "sync": false
  }
}
```

| Field | Type | Description |
| --- | --- | --- |
| `executionId` | string | Execution instance ID. **Persist it** — you poll `workflow.execution.status` with it. |
| `status` | string | Initial status (`EXECUTING` / `SUBMITTED`). |
| `sync` | boolean | Whether the execution ran synchronously; in sync mode the output carries the decision directly. |
| `code` | int | `200` = OK; `403` = quota exhausted (billing blocked). |

> **Quota** — `submit` is the only billed endpoint. A `data.code` of `403` means the eventType’s quota is exhausted; do not retry blindly — ask an admin to top up or adjust the quota.

---- Status ----

### Status & Case Decision

**Endpoint:** `workflow.execution.status` `POST`

Read-only — it does not trigger execution and is not billed. `executionId` is checked against your tenant (and `x-domain`); it cannot be queried across tenants. Use `apiVersion 1.0.0`.

#### Request

```json
{ "executionId": "exec-7208f03b931e4897" }
```

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `executionId` | string | Yes | The execution instance ID returned by `workflow.apply.submit`. |

#### Response

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "executionId": "exec-7208f03b931e4897",
    "status": "COMPLETED",
    "caseNo": "C001443",
    "caseStatus": "REJECTED",
    "riskScore": 45.0,
    "resolvedAt": 1784714818000
  }
}
```

| Field | Type | Description |
| --- | --- | --- |
| `status` | string | Execution status: `RUNNING` / `WAITING` / `COMPLETED` / `FAILED` / `CANCELED`. |
| `caseNo` | string | Associated Case number (`C%06d`); empty until a Case is generated. |
| `caseStatus` | string | Case handling status: `UNASSIGNED` (queued, not yet assigned) / `UNDER_REVIEW` (being handled by a reviewer) / `RETURNED` (sent back for rework) / `OTHER_GROUP` (this group is done; the flow continues in another group/node) / `APPROVED` / `REJECTED` / `CLOSED` (finished, flow ended); empty when there is no Case. **Polling exit conditions key off this field.** |
| `riskScore` | number | Risk score (0–100); empty if none. |
| `resolvedAt` | long | Resolution time (epoch millis); empty until resolved. |
| `currentNode` etc. | object | SDK flow-control internals (`currentNode` / `output` / `pendingCallbackTask`); ignore them for server-side integration. |

> An empty `data` string means the `executionId` does not exist, or belongs to a different tenant/domain than the current `apiKey`.

#### Status Semantics

| `status` | `caseStatus` | Meaning |
| --- | --- | --- |
| `RUNNING` / `WAITING` | empty | Executing (including waiting on data collection); no Case yet. |
| `RUNNING` / `WAITING` | `UNASSIGNED` / `UNDER_REVIEW` / `RETURNED` | **Stopped at a review node awaiting manual handling** — keep polling. |
| `RUNNING` / `WAITING` | `OTHER_GROUP` | The current Case’s group is done; the flow continues in another group/node — keep polling. |
| `COMPLETED` / `CANCELED` | `APPROVED` / `REJECTED` / `CLOSED` | Decision reached, flow finished. |
| `FAILED` | — | Execution failed; contact support with the `executionId`. |

#### Response by Stage

**Stage 1 — automatic nodes running, no Case yet** (the brief window before the decision node):

```json
{ "apiCode": 200, "apiMsg": "OK",
  "data": { "executionId": "exec-xxxx", "status": "RUNNING" } }
```

No `caseStatus` field → no Case generated yet, keep polling.

**Stage 2 — Case generated, awaiting manual handling:**

```json
{ "apiCode": 200, "apiMsg": "OK",
  "data": { "executionId": "exec-xxxx", "status": "RUNNING",
            "caseNo": "C001286", "caseStatus": "UNASSIGNED", "riskScore": 49.17 } }
```

While being handled manually, `caseStatus` reflects progress: `UNASSIGNED` (queued) → `UNDER_REVIEW` (after a reviewer picks it up); `RETURNED` when sent back for rework.

**Stage 3 — decision reached (manual review or automatic decision):**

```json
{ "apiCode": 200, "apiMsg": "OK",
  "data": { "executionId": "exec-xxxx", "status": "COMPLETED",
            "caseNo": "C001443", "caseStatus": "REJECTED", "riskScore": 45.0,
            "resolvedAt": 1784714818000 } }
```

> In a multi-review-group flow, once the current Case’s group is done but the overall flow is still running in another group/node, `caseStatus` is `OTHER_GROUP` — keep polling until `caseStatus` reaches a terminal state (`APPROVED` / `REJECTED` / `CLOSED`).

#### Polling Exit Conditions

Every execution generates a Case once it reaches the decision node (manual review → `UNASSIGNED` / `UNDER_REVIEW`; automatic pass/reject/close → a terminal Case directly), so:

```
# exit / 退出条件
caseStatus ∈ {APPROVED, REJECTED, CLOSED}   # normal path, always reached / 正常路径，必然到达
     or status ∈ {FAILED, CANCELED}         # fallback: aborted before decision node / 异常兜底：在决策节点前中止
```

> **Polling cadence** — every 3–5 seconds; once in manual handling (`caseStatus` ∈ {`UNASSIGNED`, `UNDER_REVIEW`, `RETURNED`}) you can back off to 30–60 seconds.

---- Query ----

### Recovery Query (Dedup & Resume)

**Endpoint:** `workflow.apply.query` `POST`

Looks up whether a customer already has an execution by `eventType + source + customerId`. Read-only — it starts no new execution and is not billed. Use `apiVersion 1.0.0`.

- **Resume after a break** — if `submit` timed out or the process crashed before you got an `executionId`: query first; on a hit, recover the `executionId` and resume polling, avoiding a duplicate (billed) submit.
- **Deduplicate submits** — when an upstream retry may re-fire for the same customer: skip `submit` if the query returns `RUNNING` / `APPROVED`.

#### Request

```json
{
  "eventType": "KYC_EVENT",
  "source": "API",
  "customerId": "demo-customer-001"
}
```

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `eventType` | string | Yes | Same as at submit time. |
| `source` | string | Yes | Same as at submit time. |
| `customerId` | string | Yes | Same as `data.customerId` at submit time (must stay stable for the same customer). |

#### Response

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "executionId": "exec-7208f03b931e4897",
    "status": "RUNNING"
  }
}
```

| Match | `executionId` | `status` | Suggested action |
| --- | --- | --- | --- |
| Customer already approved | most recent COMPLETED execution | `APPROVED` | Do not submit again. |
| An execution is in flight | that execution | `RUNNING` | Switch to polling `workflow.execution.status`. |
| No match (rejected or no record) | empty | — | Call `submit` normally. |

> **customerId stability** — the `customerId` must exactly match the `data.customerId` used at submit time and stay stable for the same customer over time; otherwise the recovery query will never find a match.

---- Error codes ----

### Error Codes

| Layer | Code | Meaning | Action |
| --- | --- | --- | --- |
| Gateway `apiCode` | `200` | Success (check `data.code` for the business result) | — |
| Gateway `apiCode` | `999302` | API name error | Check `api` / `apiVersion` |
| Gateway `apiCode` | `999305` | `apiKey` invalid or disabled | Verify the API Key on the API & Integration page |
| Gateway `apiCode` | `999001` | Signature error | Check the `sign` computation (sign the raw body, no extra newlines) |
| Gateway `apiCode` | `999401` | Service timeout | Retry later; contact support if it persists |
| `data.code` | `400` | Missing parameter | Check the request body |
| `data.code` | `403` | Quota exhausted (submit only) | Ask an admin to top up / adjust the quota |
| empty `data` | — | Execution does not exist or belongs to another tenant/domain (status only) | Verify `executionId` against your `apiKey` / `x-domain`; always send the required `x-domain` header |

---- Code example ----

### Code Example

#### curl (full loop)

```
API_KEY="ak_xxx"
API_SECRET="sk_xxx"
DOMAIN_ID="{domainId}"
BASE_URL="https://api-gateway-platform.width.com/gateway"

# HMAC-SHA256 sign helper / 签名助手
sign() { printf "%s" "$1" | openssl dgst -sha256 -mac HMAC -macopt key:"$API_SECRET" | sed 's/^.* //'; }

# 0. (optional) recovery query — dedup before submit / 恢复查询防重
BODY='{"eventType":"KYC_EVENT","source":"API","customerId":"demo-customer-001"}'
curl -s -X POST "${BASE_URL}?api=workflow.apply.query&apiVersion=1.0.0&apiKey=${API_KEY}&sign=$(sign "$BODY")" \
  -H "Content-Type: application/json" -H "x-domain: ${DOMAIN_ID}" -d "$BODY"

# 1. submit / 发起工作流
BODY='{"eventType":"KYC_EVENT","source":"API","data":{"customerId":"demo-customer-001","fullName":"ZHANG SAN"},"workflowId":""}'
curl -s -X POST "${BASE_URL}?api=workflow.apply.submit&apiVersion=2.0.0&apiKey=${API_KEY}&sign=$(sign "$BODY")" \
  -H "Content-Type: application/json" -H "x-domain: ${DOMAIN_ID}" -d "$BODY"
# -> record data.executionId / 记下 data.executionId

# 2. poll status / 轮询执行状态
BODY='{"executionId":"exec-7208f03b931e4897"}'
curl -s -X POST "${BASE_URL}?api=workflow.execution.status&apiVersion=1.0.0&apiKey=${API_KEY}&sign=$(sign "$BODY")" \
  -H "Content-Type: application/json" -H "x-domain: ${DOMAIN_ID}" -d "$BODY"
```

#### Python (polling loop)

```python
import hashlib, hmac, json, time, requests

GATEWAY = "https://api-gateway-platform.width.com/gateway"
API_KEY, API_SECRET, DOMAIN_ID = "ak_xxx", "sk_xxx", "{domainId}"

def call(api, api_version, payload):
    body = json.dumps(payload, separators=(",", ":"))
    sign = hmac.new(API_SECRET.encode(), body.encode(), hashlib.sha256).hexdigest()
    resp = requests.post(
        GATEWAY,
        params={"api": api, "apiVersion": api_version, "apiKey": API_KEY, "sign": sign},
        headers={"Content-Type": "application/json", "x-domain": DOMAIN_ID},
        data=body, timeout=30)
    return resp.json()

# 1. submit / 发起
r = call("workflow.apply.submit", "2.0.0", {
    "eventType": "KYC_EVENT", "source": "API",
    "data": {"customerId": "demo-customer-001", "fullName": "ZHANG SAN"},
    "workflowId": ""})
execution_id = r["data"]["executionId"]

# 2. poll until a decision / 轮询直至出结论
while True:
    s = call("workflow.execution.status", "1.0.0", {"executionId": execution_id})["data"]
    if s.get("caseStatus") in ("APPROVED", "REJECTED", "CLOSED") or s.get("status") in ("FAILED", "CANCELED"):
        print(s); break
    time.sleep(30 if s.get("caseStatus") in ("UNASSIGNED", "UNDER_REVIEW", "RETURNED") else 5)
```

---- FAQ ----

### FAQ

> **Q: submit timed out and I’m not sure it started — what now?** Do not retry `submit` directly (you’d be billed twice). Call `workflow.apply.query` first: on a `RUNNING` / `APPROVED` hit, recover the `executionId` and resume polling; only re-submit if there is no match.

> **Q: status can’t find the execution I just submitted (empty `data`)?** Confirm you are using the same `apiKey` and `x-domain` as at submit time — the endpoint checks ownership by tenant and domain, and a cross-domain query returns empty data.

> **Q: is it a problem if an execution sits in RUNNING / WAITING for a long time?** Not necessarily. While stopped at a review node awaiting manual handling, the execution status stays non-terminal and `caseStatus` is `UNASSIGNED` / `UNDER_REVIEW` / `RETURNED`. Use `caseStatus` to track handling progress.

---

===== KYC Onboarding =====

## KYC Onboarding

Multi-step workflow for individual customer onboarding. Use `eventType: "KYC_EVENT"`.

### Flow Overview

Register Customer

→

Start Workflow

→

↻ Repeat per node until status = COMPLETED Poll Status → Submit Node Data

status = COMPLETED→

Get Final Decision

#### Step 1 — Register Customer

**Endpoint:** `workflow.applicant.register` `POST`

```json
{
  "customerId": "C_abc123",
  "email": "john@example.com"
}
```

> At least one of `customerId` or `email` is required. This API is **idempotent** — repeated calls return the existing customer.

**Response:**

```json
{
  "apiCode": 200,
  "data": {
    "code": 200,
    "data": { "customerId": "C_abc123", "isNew": true },
    "msg": "success"
  }
}
```

#### Step 2 — Start Workflow

**Endpoint:** `workflow.apply.submit` `POST`

```json
{
  "eventType": "KYC_EVENT",
  "source": "API",
  "data": {
    "customerId": "C_abc123",
    "referenceId": "onboarding-uuid-001"
  }
}
```

Store the returned `executionId` — it is required for all subsequent API calls. For `apiVersion 2.0.0` and the Case decision fields (`caseStatus` / `riskScore`) this workflow shares, see [Workflow Lifecycle API → Submit](#api-workflow-submit) and [Status & Case Decision](#api-workflow-status).

#### Step 3 — Poll Status

**Endpoint:** `workflow.execution.status` `POST`

> Wait approximately **2 seconds** after starting the workflow before the first poll. The system needs a moment to initialize nodes.

```json
{
  "executionId": "exec-abc123def456"
}
```

| Status | Meaning | Action |
| --- | --- | --- |
| `RUNNING` | Executing, no node waiting | Continue polling (2–5 sec) |
| `WAITING` | Node waiting for input | Read `currentNode` and submit data |
| `COMPLETED` | Workflow finished | Stop polling, read final result |
| `FAILED` | Execution failed | Stop polling, contact support |
| `TIMEOUT` | Exceeded time limit | Stop polling, contact support |
| `CANCELLED` | Execution cancelled | Stop polling |

Key fields when `status = WAITING`:

- `currentNode.nodeType` → determines which API to call
- `currentNode.callbackKey` → required when submitting data
- `currentNode.metadata` → node-specific configuration

#### Step 4 — Submit Node Data

Each submission response includes a `nextStep` object. Use it directly to proceed — **no need to poll between every submission**. Only poll when recovering a session or waiting for the final result.

#### Step 5 — Internal Processing & Completion

After the last user-input node, the response omits `nextStep`. The workflow has entered automatic processing (screening, rule evaluation, decision). Your backend should poll `workflow.execution.status` until terminal state.

| Status | Meaning |
| --- | --- |
| `COMPLETED` | Workflow finished. Decision is recorded and visible in Admin Console. |
| `WAITING` | Flagged for manual review. Will transition to `COMPLETED` after review. |
| `FAILED` | Execution failed. Contact support. |
| `TIMEOUT` | Exceeded configured time limit. |
| `CANCELLED` | Cancelled via `workflow.execution.cancel`. |

#### Cancel Execution

**Endpoint:** `workflow.execution.cancel` `POST`

```json
{
  "executionId": "exec-abc123def456"
}
```

> Cancellation is irreversible. A cancelled execution cannot be resumed.

#### Mid-Session Recovery

If your process is interrupted, call `workflow.execution.status` with the stored `executionId` to resume from the last pending node. No data is lost.

---

===== KYC Node Reference =====

### KYC Node API Reference

Typical node sequence:

OCR

→

Particular

→

Liveness

→

Email/Phone OTP

→

Required Documents

→

Required Forms

→

[Screen Check]

→

Decision

Nodes in brackets are automatic — no client action needed.

#### KYC Node Routing Table

| nodeType | API | Description |
| --- | --- | --- |
| `flow_action_identity_document` | `workflow.kyc.ocr` → `workflow.kyc.ocr.data` | Upload document images, retrieve OCR results |
| `flow_action_individual_particular` | `workflow.kyc.particular.data` | Submit personal information |
| `flow_action_liveness_test` | `workflow.kyc.liveness.data` | Submit PASS with a customer photo |
| `flow_action_validate_email` | `workflow.kyc.otp.send` + `workflow.kyc.otp.verify` | Email verification via OTP |
| `flow_action_validate_phone` | `workflow.kyc.otp.send` + `workflow.kyc.otp.verify` | Phone verification via OTP |
| `flow_action_individual_required_document` | `workflow.kyc.required.doc` + `.submit` | Upload supporting documents |
| `flow_action_individual_nonrequired_document` | `workflow.kyc.non.required.doc` + `.submit` | Optional documents (can skip) |
| `flow_action_individual_required_forms` | `workflow.kyc.required.form` + `.submit` | Submit form/questionnaire answers |
| `flow_action_screen_check` | *(automatic)* | AML/sanctions screening — no action needed |

OCR

#### Identity Document (OCR)

Two-step: submit images, then poll results.

**Step 1 — Submit:** `workflow.kyc.ocr` `POST`

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `provider` | String | Yes | `WIDTH` / `REGULA` / `VERIFF` |
| `frontImage` | String | Yes | S3 URI of document front image |
| `backImage` | String | No | S3 URI of document back image |
| `documentType` | String | Yes | `NATIONAL_ID` / `INTERNATIONAL_PASSPORT` / `DRIVING_LICENCE` / `RESIDENCE_PERMIT` |
| `region` | String | Yes | ISO 2-letter country code |
| `executionId` | String | Yes | Execution ID |
| `callbackKey` | String | Yes | From `currentNode.callbackKey` |
| `referenceId` | String | Yes | Your tracking ID |
| `includeDocverCheck` | Boolean | No | Enable document verification |

> Upload images first via the [File Upload API](#api-upload) to obtain S3 URIs.

**Step 2 — Poll Results:** `workflow.kyc.ocr.data` `POST`

Poll after 2–5 seconds. OCR typically completes within 5–15 seconds.

Particular

#### Particular

**Endpoint:** `workflow.kyc.particular.data` `POST`

```json
{
  "executionId": "exec-abc123def456",
  "callbackKey": "kyc:particular:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001",
  "personData": "{\"name\":\"John Smith\",\"dateOfBirth\":\"1990-01-15\",\"nationality\":\"SG\",\"sex\":\"MALE\",\"countryOfResidence\":\"SG\",\"address\":\"123 Main St\"}"
}
```

> **Important:** `personData` is a **JSON-encoded string**, not a nested object. You must `JSON.stringify()` the data before placing it in the request body.

Liveness

#### Liveness

For OpenAPI, liveness is a data submission step — not an interactive check. Submit `status: "PASS"` with a customer photo.

**Endpoint:** `workflow.kyc.liveness.data` `POST`

```json
{
  "provider": "SELF",
  "status": "PASS",
  "scores": "{\"qualityScore\":1.0,\"brightnessScore\":100,\"brightnessStatus\":\"normal\"}",
  "images": "{\"faceFull\":\"s3://workflow-kyc/tenantImages/2026-04-16/customer_photo.jpg\"}",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyc:liveness:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

> `scores` and `images` are **JSON strings**. Upload the photo via [File Upload API](#api-upload) first.

Email / Phone OTP

#### Email / Phone OTP

**Step 1 — Send:** `workflow.kyc.otp.send` `POST`

```json
{
  "type": "email",
  "identity": "john@example.com",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyc:email:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

> For phone OTP, set `"type": "phone"` and use E.164 format for `identity` (e.g., `+6581234567`). Store the returned `requestId` for the verify step.

**Step 2 — Verify:** `workflow.kyc.otp.verify` `POST`

```json
{
  "type": "email",
  "identity": "john@example.com",
  "code": "985024",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyc:email:exec-abc123def456:...",
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "referenceId": "onboarding-uuid-001"
}
```

Required Documents

#### Required Documents

**Endpoint:** `workflow.kyc.required.doc` `POST`

```json
{
  "doc": "{\"front\":{\"url\":\"s3://workflow-kyc/.../bill.pdf\",\"filename\":\"bill.pdf\",\"content_type\":\"application/pdf\",\"size\":85618}}",
  "isRequired": true,
  "docType": "UTILITY_TELEPHONE_BILL",
  "extraData": "{\"issueDate\":\"2026-03-01\"}",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyc:required_doc:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

After uploading all documents, call `workflow.kyc.required.doc.submit` to advance.

> For optional documents, use `workflow.kyc.non.required.doc` with the same schema. Call `.submit` to advance (even if skipping).

Required Forms

#### Required Forms

**Endpoint:** `workflow.kyc.required.form` `POST`

```json
{
  "formId": "IndividualForm",
  "formData": "{\"field_source_of_funds\":\"EMPLOYMENT\",\"field_annual_income\":\"50000-100000\"}",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyc:required_form:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

Submit all forms, then call `workflow.kyc.required.form.submit`.

---

===== KYB Onboarding =====

## KYB Onboarding

Corporate customer onboarding. Use `eventType: "KYB_EVENT"`.

### Flow Overview

Corporate Particular

→

CRP Collector

→

Required Documents (main + CRPs)

→

Non-Required Documents

→

Required Forms (main + CRPs)

→

[Screen Check]

→

Decision

### KYB Node Routing Table

| nodeType | API | Description |
| --- | --- | --- |
| `flow_action_corporate_particular` | `workflow.kyb.particular.data` | Submit corporate entity info |
| `flow_action_corporate_crp_collector` | `workflow.kyb.crp.ind.particular` / `.corp.particular` / `.submit` | Submit directors, shareholders, UBOs |
| `flow_action_corporate_required_document` | `workflow.kyb.corp.required.doc` + `.submit` | Upload documents for main entity + CRPs |
| `flow_action_corporate_nonrequired_document` | `workflow.kyb.corp.non.required.doc` + `.submit` | Optional documents (can skip) |
| `flow_action_corporate_required_forms` | `workflow.kyb.corp.required.form` + `.submit` | Submit forms for main entity + CRPs |

Corporate Particular

#### Corporate Particular

**Endpoint:** `workflow.kyb.particular.data` `POST`

```json
{
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:corporate_particular:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001",
  "corporateData": "{\"name\":\"Acme Corp Pte Ltd\",\"industry\":\"INFORMATION TECHNOLOGY\",\"entityType\":\"PRIVATE LIMITED COMPANY\",\"countryOfIncorporation\":\"SG\",\"countryOfOperations\":\"SG\",\"email\":\"corp@acme.com\"}"
}
```

> `corporateData` is a **JSON-encoded string**, same pattern as `personData` in KYC.

CRP Collector

### CRP Collector

After corporate particular, collect Connected Related Parties (directors, shareholders, UBOs).

#### CRP Metadata

The `nextStep.metadata` specifies required roles:

```json
{
  "totalRequiredRoles": 2,
  "requiredRoles": [
    { "roleId": "DIRECTOR", "allowIndividual": true, "allowCorporate": false },
    { "roleId": "SHAREHOLDER", "allowIndividual": true, "allowCorporate": true }
  ]
}
```

| Field | Description |
| --- | --- |
| `requiredRoles` | Roles that must be filled |
| `allowIndividual` | Can this role be a person? |
| `allowCorporate` | Can this role be a company? |

#### Submit Individual CRP

**Endpoint:** `workflow.kyb.crp.ind.particular` `POST`

```json
{
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:crp_collector:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001",
  "personData": "{\"name\":\"Jane Director\",\"nationality\":\"SG\",\"date_of_birth\":\"1985-03-20\",\"sex\":\"FEMALE\",\"roles\":[{\"roleId\":\"DIRECTOR\",\"roleName\":\"Director\"}]}"
}
```

Store the returned `crpPid` — needed for liveness, documents, and forms for this CRP.

#### Submit Individual CRP Liveness

**Endpoint:** `workflow.kyb.crp.ind.liveness` `POST`

Same pattern as KYC liveness, with an additional `crpPid` field:

```json
{
  "provider": "SELF",
  "status": "PASS",
  "scores": "{\"qualityScore\":1.0,\"brightnessScore\":100,\"brightnessStatus\":\"normal\"}",
  "images": "{\"faceFull\":\"s3://workflow-kyc/.../jane_photo.jpg\"}",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:crp_collector:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001",
  "crpPid": "acc45a86-f2e9-48c2-8fcd-2bf6563357a1"
}
```

#### Submit Corporate CRP

**Endpoint:** `workflow.kyb.crp.corp.particular` `POST`

```json
{
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:crp_collector:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001",
  "corporateData": "{\"name\":\"CRP Holdings Pte Ltd\",\"entityType\":\"ASSOCIATION\",\"countryOfIncorporation\":\"SG\",\"roles\":[{\"roleId\":\"SHAREHOLDER\",\"roleName\":\"Shareholder\"}]}"
}
```

#### Finalize CRP Submission

**Endpoint:** `workflow.kyb.crp.submit` `POST`

```json
{
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:crp_collector:exec-abc123def456:..."
}
```

> You **must** call `crp.submit` to advance the workflow. Submitting individual CRPs alone does not trigger the transition.

KYB Required Documents

#### KYB Required Documents

**Endpoint:** `workflow.kyb.corp.required.doc` `POST`

Upload documents for the main entity (`crpPid: ""`) and each CRP (`crpPid: "acc45..."`). Same `doc` field schema as KYC. Submit via `workflow.kyb.corp.required.doc.submit`.

**Main entity document:**

```json
{
  "doc": "{\"front\":{\"url\":\"s3://workflow-kyc/.../cert.png\",\"filename\":\"cert.png\",\"content_type\":\"image/png\",\"size\":85618}}",
  "isRequired": true,
  "docType": "CERTIFICATE_OF_INCORPORATION",
  "extraData": "{\"issueDate\":\"2001-05-10\",\"expiryDate\":\"2030-10-10\"}",
  "crpPid": "",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:corporate_document:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

**CRP individual document (double-sided):**

```json
{
  "doc": "{\"front\":{\"url\":\"s3://...front.png\",\"filename\":\"front.png\",\"content_type\":\"image/png\",\"size\":849092},\"back\":{\"url\":\"s3://...back.png\",\"filename\":\"back.png\",\"content_type\":\"image/png\",\"size\":950146}}",
  "isRequired": true,
  "docType": "NATIONAL_ID",
  "extraData": "{\"documentNumber\":\"12034\"}",
  "crpPid": "acc45a86-f2e9-48c2-8fcd-2bf6563357a1",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:corporate_document:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

KYB Non-Required Documents

#### KYB Non-Required Documents

Same schema as required documents. Use `workflow.kyb.corp.non.required.doc` to upload. Call `workflow.kyb.corp.non.required.doc.submit` to advance (even if skipping).

KYB Required Forms

#### KYB Required Forms

**Endpoint:** `workflow.kyb.corp.required.form` `POST`

| Metadata Key | Who Fills It |
| --- | --- |
| `mainForm` | Main corporate entity |
| `crpIndividualForm` | Each individual CRP |
| `crpCorporateForm` | Each corporate CRP |
| `crpBothForm` | Each shareholder CRP |

**Main entity form:**

```json
{
  "formId": "CorporateForm",
  "formData": "{\"field_firm_size_level\":\"small_5_19\",\"field_has_branch\":\"no\"}",
  "crpPid": "",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:corporate_form:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

**CRP individual form:**

```json
{
  "formId": "IndividualCRPForm",
  "formData": "{\"field_0_0\":\"test\",\"field_0_1\":\"Singapore\"}",
  "crpPid": "acc45a86-f2e9-48c2-8fcd-2bf6563357a1",
  "executionId": "exec-abc123def456",
  "callbackKey": "kyb:corporate_form:exec-abc123def456:...",
  "referenceId": "onboarding-uuid-001"
}
```

Submit all forms (main + each CRP), then call `workflow.kyb.corp.required.form.submit`.

---

===== Verification Link =====

## Verification Link

Generate a one-off web link that takes an end user straight into the hosted KYC or KYB flow. Send them the link — by email, chat, or any channel you already use — and they complete the verification in a browser. This is the path to take when you have no website or app of your own to embed an SDK into.

**Endpoint:** `sdk.launch.link.generate` `POST`

Use `apiVersion 1.0.0`. Signing, gateway and the `x-domain` header are the same as every other OpenAPI method (see [Authentication](#api-authentication)).

#### Request

```json
{
  "email": "enduser@example.com",
  "customerId": "cust_internal_id",
  "eventType": "KYC_EVENT"
}
```

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `email` | string | Yes | End-user email |
| `customerId` | string | Yes | Your internal user ID (keep it stable for the same customer) |
| `eventType` | string | Yes | Which flow the link opens: `KYC_EVENT` (individual) or `KYB_EVENT` (corporate) |

#### Response

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "msg": "success",
    "code": 200,
    "data": {
      "url": "https://id-link-platform.width.com/?linkToken=71a2743a-ca3c-436f-bc24-af3a73405a58",
      "expiresAt": 1786679539986
    }
  }
}
```

| Field | Description |
| --- | --- |
| `data.data.url` | The link to hand to the end user. The `linkToken` query parameter identifies this one invitation — treat the whole URL as a secret and send it only to the address you passed in `email`. |
| `data.data.expiresAt` | Expiry time, epoch milliseconds. A link is valid for **7 days** from the moment it is generated; after that, call this endpoint again for a fresh one. |

> Only one link is live per email address at a time. Calling this endpoint again for the **same** `email` invalidates the previous link **the moment the new one is issued** — the copy already in the end user’s hands stops opening, and there is no way to bring it back. Before you reissue, make sure the recipient is not part-way through the flow; if they are, send them the new link. Links issued to different email addresses never affect one another.

#### Errors

An unsupported `eventType` is reported inside `data`, with the gateway-level `apiCode` still `200` — read `data.code`, not the HTTP status:

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "msg": "Invalid eventType: TRANSACTION_EVENT",
    "code": 400,
    "data": {}
  }
}
```

> This endpoint serves identity verification only. Transaction and Web3 event types have no hosted web flow to link to — submit those through [workflow.apply.submit](#api-workflow-submit).

---

===== Transaction Screening =====

## Transaction Screening

Submit transaction data for AML risk assessment. Use `eventType: "TRANSACTION_EVENT"`.

> `TRANSACTION_EVENT` is for **fiat transaction screening** (bank transfers, payments and other off-chain transactions). To screen a blockchain wallet address or an on-chain transaction, use `WEB3_TRANSACTION_EVENT` instead — see [Web3 Transaction Screening](#api-txn-web3).

**Endpoint:** `workflow.apply.submit` `POST`

#### Request

```json
{
  "eventType": "TRANSACTION_EVENT",
  "source": "API",
  "data": {
    "clientTransactionId": "TXN-20260416-001",
    "transactionType": "WITHDRAW",
    "amount": 199999.98,
    "transactionCurrencyId": "SGD",
    "altCurrencyId": "SGD",
    "amountInAltCurrency": 199999.99,
    "customerId": "C_abc123",
    "customerType": 1,
    "cpAId": "SENDER_001",
    "cpABank": "Standard Chartered",
    "cpACountry": "SINGAPORE",
    "cpBId": null,
    "cpBBank": null,
    "cpBCountry": null,
    "transactionTimestamp": "2026-04-16T10:30:00Z"
  }
}
```

#### Non-blocking Response (Async)

Returns immediately with `executionId`. Poll `workflow.execution.status` for the final result — read `caseStatus` / `riskScore` as described in [Workflow Lifecycle API → Status & Case Decision](#api-workflow-status).

```json
{
  "apiCode": 200,
  "data": {
    "executionId": "exec-7a3f1b2c4d5e6f78",
    "requestId": "req-1776243366618",
    "status": "RUNNING"
  }
}
```

#### Blocking Response (Sync)

Waits for workflow completion and returns the decision inline:

```json
{
  "apiCode": 200,
  "data": {
    "executionId": "exec-7a3f1b2c4d5e6f78",
    "status": "COMPLETED",
    "durationMs": 12,
    "output": {
      "action": "approve",
      "code": 100000
    }
  }
}
```

| Field | Description |
| --- | --- |
| `status` | `COMPLETED` = decision made, `TIMEOUT` = exceeded time limit, `FAILED` = error |
| `durationMs` | Processing time in milliseconds |
| `output.action` | `approve` / `reject` / `review` |
| `output.code` | Decision code (defaults: approve=100000, reject=100010; configurable) |

---

===== Web3 Transaction Screening =====

## Web3 Transaction Screening

Submit an on-chain (Web3) transaction event and run blockchain KYT (Know Your Transaction) screening keyed on a **wallet address (`walletAddress`) or a transaction hash (`txHash`)** — provide at least one, or both. The response returns the screening result and a decision. Use `eventType: "WEB3_TRANSACTION_EVENT"`.

**Endpoint:** `workflow.apply.submit` `POST`

> Web3 screening uses the same gateway base URL, the same query-string request envelope (`api` / `apiVersion` / `apiKey` / `sign`) plus the `x-domain` header, and the same HMAC-SHA256 request-body signing as every other OpenAPI call. See **OpenAPI Reference → Getting Started** for the base URL and request format, and **Authentication** for the full signing rules.

> No workflow ID is passed in the request. When your tenant has exactly **one published Web3 workflow**, the platform routes the event to it automatically. If your tenant has multiple published Web3 workflows, contact Width support before integrating to confirm the invocation method for your tenant.

> After submitting, poll `workflow.execution.status` and read the Case decision (`caseStatus` / `riskScore`) as described in [Workflow Lifecycle API → Status & Case Decision](#api-workflow-status).

#### Request

**Variant 1 — `walletAddress` only**

```json
{
  "eventType": "WEB3_TRANSACTION_EVENT",
  "source": "API",
  "data": {
    "chain": "TRON",
    "token": "USDT",
    "walletAddress": "TZ73Ue3KUP4PZwZJoj9v71skBShdCXksSw",
    "customerId": "demo-customer-001",
    "clientTransactionId": "tx-demo-001",
    "amount": 1000,
    "transactionCurrencyId": "USDT"
  }
}
```

**Variant 2 — `txHash` only**

```json
{
  "eventType": "WEB3_TRANSACTION_EVENT",
  "source": "API",
  "data": {
    "chain": "TRON",
    "token": "USDT",
    "txHash": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd",
    "customerId": "demo-customer-001",
    "clientTransactionId": "tx-demo-001",
    "amount": 1000,
    "transactionCurrencyId": "USDT"
  }
}
```

**Variant 3 — both `walletAddress` and `txHash`**

```json
{
  "eventType": "WEB3_TRANSACTION_EVENT",
  "source": "API",
  "data": {
    "chain": "TRON",
    "token": "USDT",
    "walletAddress": "TZ73Ue3KUP4PZwZJoj9v71skBShdCXksSw",
    "txHash": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd",
    "customerId": "demo-customer-001",
    "clientTransactionId": "tx-demo-001",
    "amount": 1000,
    "transactionCurrencyId": "USDT"
  }
}
```

#### Top-level Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `eventType` | String | Yes | Fixed value: `WEB3_TRANSACTION_EVENT` |
| `source` | String | Yes | Fixed value: `API` |
| `data` | Object | Yes | Transaction data (see below) |

#### `data` Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `chain` | String | Yes | Chain identifier, e.g. `TRON`, `ETH`, `BTC`, `BSC`, `POLYGON` |
| `token` | String | Yes | Token symbol, e.g. `USDC`, `USDT`, `ETH`, `BTC` |
| `walletAddress` | String | At least one | Counterparty wallet address |
| `txHash` | String | At least one | On-chain transaction hash |
| `clientTransactionId` | String | No | The ID that identifies this transaction in your system, for audit trails |
| `customerId` | String | No | The ID that identifies the customer in your system |
| `amount` | Number | No | Transaction amount (denominated in `transactionCurrencyId`) |
| `transactionCurrencyId` | String | No | Currency code (e.g. `USDC`, `USDT`, `USD`) |

> **Constraints**
>
> - Provide at least one of `walletAddress` and `txHash`; both may be provided together.
> - When both are provided, they must belong to the same chain and match `chain`.
> - The length of `kytScreenResults` in the response follows from this: one entry when a single value is provided, two entries when both are provided.

#### Response

The endpoint returns **synchronously**. Only **HTTP 200 with `apiCode: 200`** means the request was accepted; an HTTP 4xx/5xx means the gateway did not accept the request and the body carries no `data`. Once accepted, the business result is distinguished by `data.output.code`:

| code | action | Meaning | Client handling |
| --- | --- | --- | --- |
| `100000` | `approve` | No risk hit | Pass as normal |
| `100001` | `reject` | Risk hit | Follow your hit-handling flow (block, log a risk event, etc.) |
| `100002` | `reject` | KYT screening did not complete; reason in `data.output.data.message` | Does not indicate a risk hit |

Two core fields in the response:

- `data.output.action` — decision: `approve` / `reject`
- `data.output.data.kytScreenResults` — array of screening records: **one** entry when only `walletAddress` or only `txHash` is provided; **two** entries when both are provided (tell them apart by each record's `address` field); an **empty array** `[]` when `code = 100002`, with the reason in `data.output.data.message`.

**Approve (`100000`)**

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "executionId": "exec-7208f03b931e4897",
    "requestId": "req-1780120490039",
    "sync": true,
    "status": "COMPLETED",
    "output": {
      "code": 100000,
      "action": "approve",
      "data": {
        "kytScreenResults": [
          {
            "address": "TZ73Ue3KUP4PZwZJoj9v71skBShdCXksSw",
            "chain_name": "TRON",
            "risk_level": "low",
            "risk_score": 0,
            "is_detected": false
          }
        ]
      }
    }
  }
}
```

**Reject — risk hit (`100001`)**

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "executionId": "exec-8e7624be1d8d439a",
    "requestId": "req-1780120982607",
    "sync": true,
    "status": "COMPLETED",
    "output": {
      "code": 100001,
      "action": "reject",
      "data": {
        "kytScreenResults": [
          {
            "address": "TJJLiCdAEN3Ve4aHdgDeUgPnccJki3qCR7",
            "chain_name": "TRON",
            "risk_level": "critical",
            "risk_score": 90,
            "is_detected": true
          }
        ]
      }
    }
  }
}
```

**KYT screening not completed (`100002`)**

`kytScreenResults` is an empty array and `data.output.data.message` gives the reason (only present in this case).

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "executionId": "exec-417cec75a77046d6",
    "requestId": "req-1780138193703",
    "sync": true,
    "status": "COMPLETED",
    "output": {
      "code": 100002,
      "action": "reject",
      "data": {
        "message": "Wallet address does not match the specified chain",
        "kytScreenResults": []
      }
    }
  }
}
```

#### Response Fields

| Field | Type | Description |
| --- | --- | --- |
| `apiCode` | Number | Gateway-layer return code; `200` means the request was accepted. Other values: see Error Codes in the OpenAPI Reference. |
| `apiMsg` | String | Gateway-layer message |
| `data.executionId` | String | Unique ID of the workflow execution instance |
| `data.requestId` | String | Trace ID for this single request |
| `data.sync` | Boolean | Whether the response is synchronous; always `true` for this endpoint |
| `data.status` | String | Workflow execution status; `COMPLETED` on normal completion |
| `data.output.action` | String | Decision: `approve` / `reject` (note: `reject` does not necessarily mean a risk hit — see the business-code table above) |
| `data.output.code` | Number | Business code; see the table above (100000 / 100001 / 100002) |
| `data.output.data.message` | String | Returned only when `code = 100002`; explains why KYT screening did not complete |
| `data.output.data.kytScreenResults` | Array | KYT on-chain screening results; length rule as above (empty array when `code = 100002`) |

**`kytScreenResults[]` fields**

| Field | Type | Description |
| --- | --- | --- |
| `address` | String | The wallet address that was screened (when both `walletAddress` + `txHash` are provided, each record's address differs — use this field to tell them apart) |
| `chain_name` | String | Chain identifier, matching `data.chain` in the request |
| `risk_level` | String | Risk level, e.g. `low`, `critical` |
| `risk_score` | Number | Risk score |
| `is_detected` | Boolean | Whether this address hit a risk |

#### Code Examples

All examples follow the same principle: **serialize the request body to a string once, compute the signature on that string, then send the very same string as the HTTP body**. The example body corresponds to Variant 1 (`walletAddress` only); to call with Variant 2 or 3, just swap the `walletAddress` / `txHash` fields — the rest of the code is unchanged.

**Java:**

```java
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Web3TransactionDemo {
    private static final String GATEWAY = "https://api-gateway-platform.width.com/gateway";
    private static final String API_KEY = System.getenv("WIDTH_API_KEY");
    private static final String API_SECRET = System.getenv("WIDTH_API_SECRET");
    private static final String DOMAIN_ID = System.getenv("WIDTH_DOMAIN_ID");

    public static void main(String[] args) throws Exception {
        String body = """
                {"eventType":"WEB3_TRANSACTION_EVENT","source":"API","data":{\
                "chain":"TRON",\
                "token":"USDT",\
                "walletAddress":"TZ73Ue3KUP4PZwZJoj9v71skBShdCXksSw",\
                "customerId":"demo-customer-001",\
                "clientTransactionId":"tx-demo-001",\
                "amount":1000,\
                "transactionCurrencyId":"USDT"}}""";

        String sign = sign(body, API_SECRET);

        String url = GATEWAY + "?api=workflow.apply.submit"
                + "&apiVersion=1.0.0"
                + "&apiKey=" + URLEncoder.encode(API_KEY, StandardCharsets.UTF_8)
                + "&sign=" + sign;

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
                .header("Content-Type", "application/json")
                .header("x-domain", DOMAIN_ID)
                .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));

        System.out.println("HTTP " + response.statusCode());
        System.out.println(response.body());
    }

    private static String sign(String body, String secret) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] hash = mac.doFinal(body.getBytes(StandardCharsets.UTF_8));
        return HexFormat.of().formatHex(hash);
    }
}
```

**Python:**

```python
import hmac
import hashlib
import json
import os
import requests

GATEWAY = "https://api-gateway-platform.width.com/gateway"
API_KEY = os.environ["WIDTH_API_KEY"]
API_SECRET = os.environ["WIDTH_API_SECRET"]
DOMAIN_ID = os.environ["WIDTH_DOMAIN_ID"]

payload = {
    "eventType": "WEB3_TRANSACTION_EVENT",
    "source": "API",
    "data": {
        "chain": "TRON",
        "token": "USDT",
        "walletAddress": "TZ73Ue3KUP4PZwZJoj9v71skBShdCXksSw",
        "customerId": "demo-customer-001",
        "clientTransactionId": "tx-demo-001",
        "amount": 1000,
        "transactionCurrencyId": "USDT",
    },
}

# Serialize once. Sign and send use the same bytes.
body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)

sign = hmac.new(
    API_SECRET.encode("utf-8"),
    body.encode("utf-8"),
    hashlib.sha256,
).hexdigest()

response = requests.post(
    GATEWAY,
    params={
        "api": "workflow.apply.submit",
        "apiVersion": "1.0.0",
        "apiKey": API_KEY,
        "sign": sign,
    },
    headers={
        "Content-Type": "application/json",
        "x-domain": DOMAIN_ID,
    },
    data=body.encode("utf-8"),  # same bytes used when signing
)

print(response.status_code, response.text)
```

**Node.js:**

```javascript
const crypto = require('crypto');

const GATEWAY = 'https://api-gateway-platform.width.com/gateway';
const API_KEY = process.env.WIDTH_API_KEY;
const API_SECRET = process.env.WIDTH_API_SECRET;
const DOMAIN_ID = process.env.WIDTH_DOMAIN_ID;

const payload = {
  eventType: 'WEB3_TRANSACTION_EVENT',
  source: 'API',
  data: {
    chain: 'TRON',
    token: 'USDT',
    walletAddress: 'TZ73Ue3KUP4PZwZJoj9v71skBShdCXksSw',
    customerId: 'demo-customer-001',
    clientTransactionId: 'tx-demo-001',
    amount: 1000,
    transactionCurrencyId: 'USDT',
  },
};

// Serialize once. Sign and send use the same bytes.
const body = JSON.stringify(payload);

const sign = crypto
  .createHmac('sha256', API_SECRET)
  .update(body, 'utf8')
  .digest('hex');

const url = new URL(GATEWAY);
url.searchParams.set('api', 'workflow.apply.submit');
url.searchParams.set('apiVersion', '1.0.0');
url.searchParams.set('apiKey', API_KEY);
url.searchParams.set('sign', sign);

(async () => {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-domain': DOMAIN_ID,
    },
    body,
  });
  console.log(response.status, await response.text());
})();
```

#### Error Codes

> Gateway-layer error codes (`apiCode`, the 9999xx series) are listed under **OpenAPI Reference → Error Codes** and apply to every endpoint. Business-layer result codes (`data.output.code`, the 10000x series) are specific to this endpoint — see the table at the top of **Response** above.

#### FAQ

**Q: My signature keeps failing — what should I check first?**

A: 99% of `SIGN_ERROR` cases come from a mismatch between the body bytes used to sign and the body bytes actually sent. Make sure you: build the JSON string → compute the signature on it → send the **same string** as the HTTP body. Between signing and sending, do not pretty-print, do not serialize again, do not append a trailing newline.

**Q: Must the request body be minified (whitespace stripped)?**

A: No. The body may keep any newlines/indentation, as long as the bytes you **sign** and the bytes you **send** are exactly the same.

**Q: Can I screen an address before the transaction is broadcast on-chain (pre-transaction screening)?**

A: Yes. Use Variant 1 — provide `walletAddress` only, without `txHash`. Screening is keyed on the address itself, so no on-chain transaction is required: screen the counterparty address first, then decide whether to proceed with the transfer.

---

===== Name Screening =====

## Name Screening

Send a subject — a person or a company — to be screened against watchlists. The platform files the subject under a customer record, runs the screening inside your workflow, raises alerts on matches and opens a case for an analyst to adjudicate. Use `eventType: "MANUAL_CASE_EVENT"`.

> Two ways to screen a name, for two different jobs. This endpoint keeps a record: the subject becomes a customer profile, hits become alerts, and an analyst’s decision is remembered and reused the next time the same `customerId` comes back. If all you want is a throwaway lookup with no customer and no case, use [Quick Scan](#api-quickscan) instead.

**Endpoint:** `workflow.apply.submit` `POST`

POST to the gateway with the usual query string — `api=workflow.apply.submit`, `apiVersion=2.0.0`, `apiKey` and `sign` — plus the `x-domain` header carrying your domain ID. The body is UTF-8 JSON sent with `Content-Type: application/json`, and `sign` is its HMAC-SHA256 over the **exact bytes** you put on the wire: serialise the body once, sign those bytes, send those same bytes, and do not let a framework re-serialise the body afterwards. Full rules and code samples are in [Authentication](#api-authentication).

> Screening consumes quota from the third-party name screening provider, so treat a submission as something that costs money: de-duplicate before you call, and if a call times out, look up how far the previous submission got with [workflow.apply.query](#api-workflow-query) instead of resending blind. How the quota is actually drawn down is whatever the **Admin Console → Billing** usage page reports (see [Usage & Quota](#usage-quota)) — read it there rather than working it out from your own assumptions, and before you integrate at volume put a small trial batch through and compare that page before and after.

#### Request

```json
{
  "eventType": "MANUAL_CASE_EVENT",
  "source": "API",
  "workflowId": "{workflowId}",
  "data": {
    // subject fields, see below
  }
}
```

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `eventType` | string | Yes | Fixed value `MANUAL_CASE_EVENT`. The Console labels this event **Manual**. |
| `source` | string | Yes | Fixed value `API` for server-side integrations. |
| `workflowId` | string | Yes, for this flow | Which screening workflow to run. Take the ID from the workflow list in the Console. Leaving it out is technically allowed — the platform then routes to the most recently published workflow — but for name screening name the workflow explicitly, so a later publish elsewhere cannot silently change what your submissions run through. |
| `data` | object | Yes | The subject being screened. Fields go at the top level of `data`, not nested deeper. |

#### Subject Fields

| Field | Required | Description |
| --- | --- | --- |
| `customerId` | Yes | Your customer number. The platform creates or reuses a customer profile under this key, and an analyst’s decision is remembered against it — several cases on the same customer share what has already been adjudicated. Pick a key that never changes for that customer; the cross-case memory depends on it. |
| `name` | Yes | The subject’s name, as one string — do not split it into surname and given-name fields. For a person send the full name in English; for a company send the registered name. |
| `aliasName` | Recommended | Other names the subject is known by, such as the name in its original script. Each name is screened separately, and the original-script name improves match accuracy noticeably. Separate several names with commas — which means **an alias itself must not contain a comma**: written as `Chen, Dawei` it is read as two names, so write `Chen Dawei`. This applies to `aliasName` only; `name` is never split. |
| `customerType` | Yes | `individual` for a person, `corporate` for a company. |
| `sex` | Recommended (person) | Sex. `F` / `M` or the English word in full. |
| `dateOfBirth` | Recommended (person) | Date of birth. A full date (`1966-03-15`) or the year alone (`1966`) both work. |
| `countryOfNationality` | Recommended (person) | Nationality. ISO 3166 two-letter or three-letter codes are both accepted; the platform normalises them. |
| `countryOfResidence` | Optional | Country of residence, or principal place of business for a company. |
| `occupation` | Optional (person) | Occupation or job title. Shown on the case page. |
| `idType`, `idNumber` | Optional (person) | Identity document type and number. Send them as a pair, and only for a real identity document (passport, national ID and the like) — never an internal reference number. **When they take effect:** only on that customer’s first submission, while the platform has no profile for them yet; from then on the document held on the profile is authoritative and a document sent in the event no longer applies. |
| `countryOfIncorporation` | Recommended (company) | Country of incorporation. If omitted, `countryOfResidence` is used instead. |
| `incorporationDate` | Optional (company) | Date of incorporation, full date or year alone. Written to the customer profile and shown on the case page; in the current version it is not sent to the screening engine as match evidence. |
| `incorporationNumber` | Optional (company) | Company registration number. Matched against the registration numbers on watchlist records — for a company this is the strongest single piece of evidence, so the same rule applies: better empty than approximate, send only a real registration number. |

`sex`, `dateOfBirth` and `countryOfNationality` for a person, and `countryOfIncorporation` and `incorporationNumber` for a company, are used as corroborating evidence: they feed the match and push down weak hits. The more of them you send, the less same-name noise comes back. A missing field is treated neutrally and never counts against the subject.

#### Response

The call is asynchronous: it returns as soon as the submission is accepted, and the screening runs on the platform.

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "executionId": "exec-xxxxxxxxxxxxxxxx",
    "requestId": "req-xxxxxxxxxxxxx",
    "status": "RUNNING"
  }
}
```

| Field | Description |
| --- | --- |
| `data.executionId` | Identifies this execution. Keep it: it is what you quote when asking about progress or reporting a problem, and what [workflow.execution.status](#api-workflow-status) takes to poll the outcome. |
| `data.status` | `RUNNING` on a successful submission. The screening result and risk score end up on the case page in the Console. |

A failed submission returns the gateway’s standard error envelope. The usual causes are a signature that does not match the bytes sent, a missing `x-domain` header, a body that is not valid JSON, and a missing required field.

#### Examples

**Individual subject:**

```json
{
  "eventType": "MANUAL_CASE_EVENT",
  "source": "API",
  "workflowId": "{workflowId}",
  "data": {
    "customerId": "CIF-0001234",
    "name": "CHEN, DAWEI",
    "aliasName": "陳大偉",
    "customerType": "individual",
    "sex": "M",
    "dateOfBirth": "1968",
    "countryOfNationality": "TW",
    "countryOfResidence": "TW",
    "occupation": "Director"
  }
}
```

**Corporate subject:**

```json
{
  "eventType": "MANUAL_CASE_EVENT",
  "source": "API",
  "workflowId": "{workflowId}",
  "data": {
    "customerId": "CIF-0005678",
    "name": "HUAYUAN INTERNATIONAL TRADING CO., LTD",
    "aliasName": "華遠國際貿易有限公司",
    "customerType": "corporate",
    "countryOfIncorporation": "HK",
    "incorporationDate": "2003",
    "incorporationNumber": "0691355",
    "countryOfResidence": "HK"
  }
}
```

---

===== Quick Scan API =====

## Quick Scan API

Quick Scan provides one-off compliance screening with **no need to create a customer or configure a workflow**. Submit a single name and the platform runs several screening engines in parallel — World-Check, Dow Jones, ArtemiScan, Internet Search and your internal watchlist — and returns the matches (hits). Useful for ad-hoc sanctions / PEP (Politically Exposed Person) name checks.

> Quick Scan uses the same gateway base URL, the same query-string request envelope (`api` / `apiVersion` / `apiKey` / `sign`) plus the `x-domain` header, and the same HMAC-SHA256 request-body signing as every other OpenAPI call. See **OpenAPI Reference → Getting Started** for the base URL and request format, and **Authentication** for the full signing rules.

#### Flow

1. `quickscan.submit` — submit a screening; returns an `id` immediately (asynchronous)
2. `quickscan.detail` — poll for status; on `DONE` it returns the hit summary
3. `quickscan.hits` — fetch full hit details per provider, paginated (optional)

#### Endpoints

| API Name | Description | Timeout |
| --- | --- | --- |
| `quickscan.submit` `POST` | Submit a screening | 30s |
| `quickscan.detail` `POST` | Query status and result | 10s |
| `quickscan.hits` `POST` | Fetch hit details (paginated) | 10s |

### quickscan.submit — Submit a Screening

#### Request

```json
{
  "data": {
    "name": "Vladimir Putin",
    "customerType": "Individual",
    "providers": ["WORLD_CHECK", "DOW_JONES", "ARTEMISCAN", "INTERNET_SEARCH"],
    "description": "AML compliance check",
    "providerSettings": {
      "artemiscan": { "sensitivity": 0.6 },
      "worldCheck": { "matchStrength": "STRONG", "maxHits": 20 },
      "dowJones": { "searchType": "Precise", "maxHits": 20 },
      "internetSearch": { "resultCount": 20 }
    }
  }
}
```

#### `data` Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | String | Yes | Name of the entity to screen |
| `customerType` | String / Integer | Yes | `"Individual"` or `"Business"` (integers `1` / `2` also accepted) |
| `providers` | String[] | Yes | List of screening engines (at least one) |
| `description` | String | No | Free-text note |
| `providerSettings` | Object | No | Per-engine parameters (defaults are used when omitted) |

#### Available Engines (`providers`)

| Engine | Description | Consumes Credit |
| --- | --- | --- |
| `WORLD_CHECK` | Refinitiv World-Check sanctions / PEP lists | Yes |
| `DOW_JONES` | Dow Jones Risk & Compliance lists | Yes |
| `ARTEMISCAN` | ArtemiScan composite risk screening | Yes |
| `INTERNET_SEARCH` | Public internet information search | Yes |
| `WATCHLIST` | Internal watchlist (tenant-defined) | No (free) |

#### Engine Parameters (`providerSettings`)

| Engine | Parameter | Default | Options |
| --- | --- | --- | --- |
| `artemiscan` | `sensitivity` | `0.6` | 0–1 (higher = looser matching) |
| `worldCheck` | `matchStrength` | `STRONG` | `EXACT` / `STRONG` / `WEAK` |
| `worldCheck` | `maxHits` | `20` | 5 / 10 / 20 / 50 |
| `dowJones` | `searchType` | `Precise` | `Precise` / `Near` / `Broad` |
| `dowJones` | `maxHits` | `20` | 5 / 10 / 20 / 50 |
| `internetSearch` | `resultCount` | `20` | 10 / 20 / 50 |

#### Response

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "status": "RUNNING"
  }
}
```

| Field | Description |
| --- | --- |
| `data.id` | Screening record ID, used for subsequent queries |
| `data.status` | `RUNNING` (screening in progress) |

### quickscan.detail — Query Result

#### Request

```json
{
  "data": {
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d"
  }
}
```

**Response — in progress**

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "status": "RUNNING"
  }
}
```

**Response — done, hits ≤ 50 (inlined)**

When `totalHits ≤ 50`, the `hits` field returns all hit details inline:

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "status": "DONE",
    "totalHits": 31,
    "truncated": false,
    "hitCounts": {
      "WORLD_CHECK": 7,
      "DOW_JONES": 3,
      "ARTEMISCAN": 1,
      "INTERNET_SEARCH": 20
    },
    "hits": {
      "WORLD_CHECK": [ { ... }, { ... } ],
      "DOW_JONES": [ { ... } ],
      "ARTEMISCAN": [ { ... } ],
      "INTERNET_SEARCH": [ { ... }, { ... } ]
    }
  }
}
```

**Response — done, more than 50 hits**

When there are more than 50 hits, `hits` is `null` and `truncated` is `true`. Use `quickscan.hits` to fetch details page by page:

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "id": "qs-xxx",
    "status": "DONE",
    "totalHits": 128,
    "truncated": true,
    "hitCounts": {
      "WORLD_CHECK": 45,
      "DOW_JONES": 33,
      "ARTEMISCAN": 30,
      "INTERNET_SEARCH": 20
    },
    "hits": null
  }
}
```

#### Response Fields

| Field | Type | Description |
| --- | --- | --- |
| `status` | String | `RUNNING` / `DONE` / `FAILED` |
| `totalHits` | Integer | Total hits across all engines |
| `truncated` | Boolean | `true` = too many hits, fetch via `quickscan.hits` |
| `hitCounts` | Object | Per-engine hit counts `{ "WORLD_CHECK": 7, ... }` |
| `hits` | Object / null | Hit details (returned only when `totalHits ≤ 50`) |

### quickscan.hits — Paginate Hit Details

When `quickscan.detail` returns `truncated: true`, use this endpoint to fetch hit details per engine, page by page. It also works when `truncated: false` if you want a single engine's results on demand.

#### Request

```json
{
  "data": {
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "provider": "WORLD_CHECK",
    "page": 1,
    "pageSize": 20
  }
}
```

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | String | Yes | Screening record ID |
| `provider` | String | Yes | Engine name (`WORLD_CHECK` / `DOW_JONES` / `ARTEMISCAN` / `INTERNET_SEARCH` / `WATCHLIST`) |
| `page` | Integer | No | Page number (default `1`) |
| `pageSize` | Integer | No | Items per page (default `20`, max `100`) |

#### Response

```json
{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "totalHits": 7,
    "truncated": true,
    "hits": {
      "WORLD_CHECK": [
        {
          "firstName": "Vladimir",
          "lastName": "PUTIN",
          "category": "PEP",
          "subCategory": "PEP - Current",
          "addresses": [ { "country": { "code": "RUS", "name": "Russian Federation" } } ],
          "dobs": [ { "dateOfBirth": "1952-10-07" } ]
        }
      ]
    }
  }
}
```

| Field | Description |
| --- | --- |
| `totalHits` | Total hits for this engine |
| `truncated` | Whether more pages remain (`true` = there is a next page) |
| `hits` | Hit details for the current page `{ "PROVIDER": [...] }` |

#### Code Examples

End-to-end example: submit, poll until `DONE`, then paginate if `truncated`. Remember the signing rule — **serialize the request body to a string once, compute the signature on that string, then send the very same string as the HTTP body**.

**Python:**

```python
import hmac, hashlib, json, os, time, urllib.request, urllib.error

GATEWAY    = "https://api-gateway-platform.width.com/gateway"
API_KEY    = os.environ["WIDTH_API_KEY"]
API_SECRET = os.environ["WIDTH_API_SECRET"]
DOMAIN_ID  = os.environ["WIDTH_DOMAIN_ID"]

def sign(body: str) -> str:
    return hmac.new(API_SECRET.encode(), body.encode(), hashlib.sha256).hexdigest()

def post(api: str, body: str) -> dict:
    url = f"{GATEWAY}?api={api}&apiVersion=1.0.0&apiKey={API_KEY}&sign={sign(body)}"
    req = urllib.request.Request(url, data=body.encode(), method='POST',
                                 headers={'Content-Type': 'application/json', 'x-domain': DOMAIN_ID})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.loads(resp.read().decode())

# 1. Submit a screening
submit_body = json.dumps({"data": {
    "name": "Vladimir Putin",
    "customerType": "Individual",
    "providers": ["WORLD_CHECK", "DOW_JONES", "ARTEMISCAN"],
    "providerSettings": {
        "worldCheck": {"matchStrength": "STRONG", "maxHits": 20},
        "dowJones": {"searchType": "Precise", "maxHits": 20},
        "artemiscan": {"sensitivity": 0.6}
    }
}}, separators=(',', ':'))

result = post("quickscan.submit", submit_body)
scan_id = result["data"]["id"]
print(f"Submitted: {scan_id}")

# 2. Poll for the result
while True:
    detail_body = json.dumps({"data": {"id": scan_id}}, separators=(',', ':'))
    detail = post("quickscan.detail", detail_body)
    status = detail["data"]["status"]
    print(f"Status: {status}")
    if status in ("DONE", "FAILED"):
        break
    time.sleep(3)

# 3. If truncated, paginate
if detail["data"].get("truncated"):
    for provider, count in detail["data"]["hitCounts"].items():
        page = 1
        while True:
            hits_body = json.dumps({"data": {
                "id": scan_id, "provider": provider, "page": page, "pageSize": 20
            }}, separators=(',', ':'))
            hits = post("quickscan.hits", hits_body)
            items = hits["data"]["hits"][provider]
            print(f"{provider} page {page}: {len(items)} hits")
            if not hits["data"]["truncated"]:
                break
            page += 1
else:
    # Result already inlined
    for provider, items in detail["data"]["hits"].items():
        print(f"{provider}: {len(items)} hits")
```

**cURL:**

**Submit a screening**

```bash
curl -X POST '{baseUrl}?api=quickscan.submit&apiVersion=1.0.0&apiKey={ak_xxx}&sign={sign}' \
  -H 'Content-Type: application/json' \
  -H 'x-domain: {domainId}' \
  -d '{"data":{"name":"Vladimir Putin","customerType":1,"providers":["WORLD_CHECK","DOW_JONES"]}}'
```

**Query result**

```bash
curl -X POST '{baseUrl}?api=quickscan.detail&apiVersion=1.0.0&apiKey={ak_xxx}&sign={sign}' \
  -H 'Content-Type: application/json' \
  -H 'x-domain: {domainId}' \
  -d '{"data":{"id":"qs-xxx"}}'
```

**Paginate hits**

```bash
curl -X POST '{baseUrl}?api=quickscan.hits&apiVersion=1.0.0&apiKey={ak_xxx}&sign={sign}' \
  -H 'Content-Type: application/json' \
  -H 'x-domain: {domainId}' \
  -d '{"data":{"id":"qs-xxx","provider":"WORLD_CHECK","page":1,"pageSize":20}}'
```

#### Error Codes

**Gateway-layer codes (`apiCode`)**

| apiCode | apiMsg | Cause |
| --- | --- | --- |
| `200` | `OK` | Request succeeded |
| `999001` | `SIGN_ERROR` | Signature verification failed |
| `999301` | `API_INVALID_REQUEST` | Malformed request |
| `999302` | `API_NOT_FOUND` | Wrong API name |
| `999304` | `RATE_LIMIT_TRY_AGAIN` | Rate limited |
| `999305` | `TENANT_NOT_FOUND` | No tenant for this `apiKey` |

**Business-layer codes (`data.code`)**

| code | Meaning |
| --- | --- |
| `200` | Success |
| `400` | Parameter error (missing required field, invalid provider, etc.) |
| `403` | Insufficient Credit |
| `404` | Screening record not found |
| `500` | Internal server error |

#### FAQ

**Q: How long until I get a result?**

A: Usually 3–10 seconds. World-Check and Dow Jones typically return in 2–5 seconds; Internet Search may be slower. Poll `quickscan.detail` every 3 seconds.

**Q: What does `truncated: true` mean?**

A: When the total hit count exceeds 50, `quickscan.detail` does not inline all hit details (to avoid an oversized response). In that case `hits` is `null`, and you fetch details per engine via `quickscan.hits`.

**Q: How much Credit does each scan consume?**

A: One Credit per engine (`WATCHLIST` is free). For example, choosing 3 engines consumes 3 Credits.

**Q: What does `customerType` affect?**

A: `"Individual"` and `"Business"` determine the engines' matching strategy. The Business type additionally matches company name, registration number and similar fields. Integers `1` (Individual) / `2` (Business) are also accepted.

**Q: My signature keeps failing.**

A: Make sure the body bytes used for signing are exactly the bytes you send. Build the JSON string once → sign it → send the same string. Do not pretty-print and do not serialize again.

**Q: Can I submit multiple screenings at once?**

A: Yes. Each `quickscan.submit` call is independent and returns its own `id`. You can submit in parallel and poll each result independently.

---

===== Continuous Monitoring =====

## Continuous Monitoring

Asynchronous review for existing customers. Always non-blocking. Use `eventType: "PERIODIC_FLOW_EVENT"`.

**Endpoint:** `workflow.apply.submit` `POST`

#### Request

```json
{
  "eventType": "PERIODIC_FLOW_EVENT",
  "source": "API",
  "data": {
    "customerId": "C_abc123",
    "customerType": "INDIVIDUAL",
    "name": "John Smith",
    "email": "john@example.com",
    "dateOfBirth": "1990-01-15",
    "countryOfNationality": "SG",
    "idType": "NATIONAL_ID",
    "idNumber": "S9012345A",
    "riskLevel": "LOW",
    "startTime": 1776243366000,
    "lastStartTime": 1776243366000
    // ... see full field reference below
  }
}
```

#### Response

Returns immediately with `executionId`. Poll `workflow.execution.status` until terminal state; read the Case decision (`caseStatus` / `riskScore`) as described in [Workflow Lifecycle API → Status & Case Decision](#api-workflow-status).

```json
{
  "apiCode": 200,
  "data": {
    "executionId": "exec-7a3f1b2c4d5e6f78",
    "requestId": "req-1776243366618",
    "status": "RUNNING"
  }
}
```

**Full data field reference (click to expand)** Field Type Description `customerId` String Your unique customer identifier `customerType` String `INDIVIDUAL` / `CORPORATE` `name` String Full name or company name `phone` String E.164 format `email` String Customer email `salutation` String `Mr` / `Ms` / `Mrs` `aliasName` String Known alias or trading name `formerRegisteredName` String Previous registered name `sex` String `MALE` / `FEMALE` `dateOfBirth` String `YYYY-MM-DD` `countryOfNationality` String ISO 2-letter `countryOfResidence` String ISO 2-letter `countryOfBirth` String ISO 2-letter `address` String Full address `idType` String `NATIONAL_ID` / `INTERNATIONAL_PASSPORT` / `DRIVING_LICENCE` `idNumber` String Document number `idIssuedDate` String `YYYY-MM-DD` `idExpiryDate` String `YYYY-MM-DD` `companyName` String Corporate only `entityType` String From config `avira_entity_types` `incorporationNumber` String Corporate only `incorporationDate` String `YYYY-MM-DD`, corporate only `incorporationExpiry` String `YYYY-MM-DD`, corporate only `countryOfIncorporation` String ISO 2-letter, corporate only `countryOfOperations` String ISO 2-letter, corporate only `imoNumber` String IMO number for shipping entities `isIncorporated` Boolean Whether entity is incorporated `isRegulatedEntity` Boolean Whether entity is regulated `ownershipStructureLayer` String From config `ownership_structure_layer` `industry` String From config `avira_ssic` `occupation` String From config `avira_ssoc` `website` String Company website URL `onboardingMode` String `ONLINE` / `OFFLINE` `paymentMode` String `BANK_TRANSFER` / `CASH` `productComplexity` String From config `product_service_complexity` `bankAccounts` String Associated bank account info `transactionBehaviour` String From config `transaction_behaviour` `riskLevel` String `LOW` / `MEDIUM` / `HIGH` `startTime` Long Epoch ms — current review start `customerCategory` String `RETAIL` / `CORPORATE` `lastStartTime` Long Epoch ms — previous review start

---

===== File Upload =====

## File Upload

For any API requiring S3 URIs (documents, photos), upload files first.

#### Step 1 — Get Upload Token

**Endpoint:** `storage.upload.token` `POST`

Request body: `{}`. Token is valid for **15 minutes**.

**Response:**

```json
{
  "apiCode": 200,
  "data": {
    "uploadToken": "a1b2c3d4e5f6...",
    "expiresIn": 900
  }
}
```

#### Step 2 — Upload File

**Storage Service URL:**

| Environment | URL |
| --- | --- |
| Staging | `https://api-gateway-platform.width.com/storage` |
| Production | `https://api-gateway.width.com/storage` |

**Multipart upload:**

```bash
curl -X POST "${STORAGE_URL}/api/v1/upload/file" \
  -F "uploadToken=a1b2c3d4e5f6..." \
  -F "file=@passport_front.jpg"
```

**Base64 upload:**

```bash
curl -X POST "${STORAGE_URL}/api/v1/upload" \
  -H "Content-Type: application/json" \
  -d '{
    "uploadToken": "a1b2c3d4e5f6...",
    "image": "data:image/jpeg;base64,/9j/4AAQ...",
    "filename": "passport_front.jpg"
  }'
```

**Response:**

```json
{
  "apiCode": 200,
  "data": {
    "url": "s3://workflow-kyc/tenantImages/2026-04-16/abc123.jpg",
    "filename": "passport_front.jpg",
    "content_type": "image/jpeg",
    "size": 245760
  }
}
```

> The S3 URI is an **internal reference**, not a publicly accessible URL. Do not attempt to download files using this URI directly.
>
> **Supported types:** PNG, JPG, JPEG, GIF, WEBP, TIFF, PDF — **Max size:** 20 MB

> **Token expired (HTTP 401)?** Obtain a new token and retry the upload.

---

===== Error Handling =====

### Error Handling & Retry Strategy

| Scenario | Recommendation |
| --- | --- |
| Signature errors (403) | **Do not retry.** Fix signing implementation. |
| Server errors (500) | Retry up to 3 times with exponential backoff (1s → 2s → 4s) |
| Status polling | Every 2–5 seconds, max 30 minutes |
| Upload token 401 | Get new token, retry upload once |
| OTP verify fail | Resend OTP if max attempts exhausted |
| Network timeout | Safe to retry — all APIs are idempotent on `callbackKey` |

---

==================== WEBHOOK ====================

## Webhook Integration

Webhooks let the platform call your own server from inside a workflow — the outbound counterpart to the [OpenAPI](#api-getting-started) pull model. This section covers configuration, request format, signature verification, retry semantics, and reference implementations.

### Concept

A **Webhook** is a reusable HTTP configuration that workflow nodes can invoke. Two call paths share the same configuration:

| Path | Trigger | Mode | Retry | Captures response |
| --- | --- | --- | --- | --- |
| Webhook Action node | Reached as a step in a workflow | Sync (workflow waits) | Configurable per node | Yes — outputs parsed by JsonPath |
| Decision Webhook hook | Optional post-action on a Decision node when status settles to `approve` / `reject` | Fire-and-forget async | None | No (failure is audit-logged only) |

Both paths read the same `HttpServiceDefinition` (URL, method, headers, signature, etc.) — configure once, use in both.

### Configure a Webhook (UI)

Path: `Sidebar → Tools → Webhook → + New Webhook`

| Field | Required | Description |
| --- | --- | --- |
| Webhook Name | yes | Display name; referenced in node editors |
| HTTP Method | yes | `POST` (default) / `PUT` / `PATCH` / `GET` / `DELETE`. `GET` and `DELETE` are sent without a body |
| Webhook URL | yes | Absolute URL. Supports `{variable}` placeholders resolved against the input map at runtime, e.g. `https://api.example.com/users/{userId}` |
| Headers | optional | List of `{name, defaultValue}`. Values support `{variable}` substitution |
| Inputs | optional | Declared input fields. Become the top-level keys of the JSON request body |
| Outputs | optional | List of `{paramName, jsonPath, paramType, defaultValue}`. Extracted from the response as the node's outputs (sync path only) |
| Signature | optional | See Signature Verification below |

After saving, copy the **Webhook ID** — workflow node editors reference Webhooks by this ID.

### Request Format

#### Headers

- Headers configured on the Webhook are sent verbatim (after `{var}` substitution).
- When signature is enabled, two extra headers are added automatically (see Signature Verification).
- For body-carrying methods (POST/PUT/PATCH), `Content-Type` defaults to `application/json; charset=utf-8`; override by adding a `Content-Type` header on the Webhook.

#### Body (POST/PUT/PATCH only)

The resolved inputs map is serialized directly as the JSON body — declared input fields become top-level keys:

```http
POST /receive HTTP/1.1
Content-Type: application/json; charset=utf-8

{
  "customerId": "cust-001",
  "action": "approve",
  "score": 86
}
```

`GET` and `DELETE` are sent without a body.

#### Placeholder substitution

The Webhook URL and header values support `{var}` (single-brace) substitution. The source is the resolved inputs map for the call.

### Signature Verification

The platform signs outbound requests with HMAC so the receiver can authenticate them.

#### Configuration (per Webhook)

| Field | Values |
| --- | --- |
| `type` | `NONE` (default) / `HMAC_SHA256` |
| `payloadFormat` | `TIMESTAMP_BODY` (default) / `BODY` |
| `secret` | Shared secret. Encrypted at rest. Cannot be viewed after saving — keep a backup |
| `signatureHeader` | Header name for the signature. Default `X-Webhook-Signature` |
| `timestampHeader` | Header name for the timestamp. Default `X-Webhook-Timestamp` |

#### Signing rules

```
algorithm = HMAC_SHA256
timestamp = current Unix epoch in milliseconds, as a decimal string
content   = if payloadFormat == BODY            → body
            else (TIMESTAMP_BODY)               → timestamp + "\n" + body
signature = lowercase hex( HMAC(secret, content) )
```

- `body` is the exact bytes sent on the wire — `JSON.stringify(inputs)` for body-carrying methods, or the empty string `""` for GET/DELETE.
- Both `secret` and `content` are UTF-8 encoded.
- The platform sends `X-Webhook-Timestamp` (or your custom header) alongside the signature so the receiver can recompute it deterministically.

#### Verification on the receiver side

1. Read the timestamp from `X-Webhook-Timestamp`.
2. (Recommended) reject if `|now - timestamp| > 5 minutes` to prevent replay.
3. Recompute the signature using the shared secret and the raw request body.
4. Compare in constant time against `X-Webhook-Signature`.

#### Reference: Node.js verifier

```javascript
const crypto = require('crypto');

function verify(req, secret) {
  const timestamp = req.header('X-Webhook-Timestamp');
  const signature = req.header('X-Webhook-Signature');
  if (!timestamp || !signature) return false;

  // Replay protection (5-minute window)
  if (Math.abs(Date.now() - Number(timestamp)) > 5 * 60 * 1000) return false;

  // payloadFormat = TIMESTAMP_BODY (default)
  const content = `${timestamp}\n${req.rawBody}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(content, 'utf8')
    .digest('hex');

  // Constant-time comparison
  const a = Buffer.from(signature, 'utf8');
  const b = Buffer.from(expected, 'utf8');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```

#### Reference: Python verifier

```python
import hmac, hashlib, time

def verify(request_body: bytes, headers: dict, secret: str) -> bool:
    ts = headers.get("X-Webhook-Timestamp")
    sig = headers.get("X-Webhook-Signature")
    if not ts or not sig:
        return False
    if abs(int(time.time() * 1000) - int(ts)) > 5 * 60 * 1000:
        return False
    content = f"{ts}\n".encode() + request_body  # payloadFormat = TIMESTAMP_BODY
    expected = hmac.new(secret.encode(), content, hashlib.sha256).hexdigest()
    return hmac.compare_digest(sig, expected)
```

### Response Handling (Webhook Action node only)

Only the sync Webhook Action node inspects the response and parses outputs; the Decision hook does not parse responses.

| Outcome | Behavior |
| --- | --- |
| `2xx` | Success. Body is parsed against the Webhook's `outputs` JsonPath list; matched values become node outputs |
| `4xx` | Failure. Not retried by default (unless listed in `retryOnStatus`) |
| `5xx` | Failure. Retried up to `maxAttempts` with exponential backoff |
| Network error / timeout | Failure. Retried up to `maxAttempts` with exponential backoff |

#### Output parsing

For each output `{paramName, jsonPath, paramType, defaultValue}`:

- The response body is parsed as JSON.
- The JsonPath expression is evaluated.
- The result is type-converted to `paramType` and exposed as the node output `paramName`.
- If JsonPath misses or the body is not JSON, `defaultValue` is used (`null` if not set).

```
// Response body
{ "data": { "score": 92, "reason": "OK" } }
```

| paramName | jsonPath | result |
| --- | --- | --- |
| `score` | `$.data.score` | `92` |
| `reason` | `$.data.reason` | `"OK"` |

#### Retry semantics

| Field | Default | Notes |
| --- | --- | --- |
| `maxAttempts` | `1` (no retry) | Clamped to `[1, 5]` |
| `backoffMs` | `500` | Exponential: `delay = backoffMs * 2^(attempt-1)` |
| `retryOnStatus` | empty | Extra HTTP status codes (typically `408`, `429`) to retry beyond the default 5xx + network/timeout |

At default `backoffMs=500`, `maxAttempts=5`, the worst-case total backoff is ~7.5 s (0.5s + 1s + 2s + 4s).

### Decision Webhook Hook

A Decision node can optionally fire a Webhook **after** the decision lands on `approve` / `reject`. This path is **fire-and-forget**:

- Sent asynchronously; the workflow does not wait for the response.
- No retry. Failures are audit-logged only and never block the workflow.
- The response body is not parsed.
- Decision metadata (`action` / `code` / `reason` / `tags`) is auto-merged into the payload — only if your input fields don't already declare them.

> **Need response-based branching?**
>
> Use a Webhook Action node instead.

### Receiver Best Practices

1. **Idempotency** — the sync path may re-deliver on network blips; de-duplicate by `executionId` (or your own ID).
2. **Respond fast** — the per-attempt HTTP timeout is 10 s by default; queue long work and ACK immediately.
3. **Status code semantics** — `2xx` success; `4xx` permanent failure (no retry); `5xx` transient (retried). Returning `2xx` for a logical failure is treated as success.
4. **Verify the signature on every request** — never trust the body until the signature passes.
5. **Reject stale timestamps** — protects against replay.
6. **Log the full `X-Webhook-Signature` and `X-Webhook-Timestamp`** during integration to compare.

### Troubleshooting

| Symptom | Likely cause |
| --- | --- |
| 401 / 403 on receiver | Signature mismatch — check algorithm, payload format, and secret; verify `body` is the raw bytes (not pretty-printed JSON) |
| Receiver sees no body for `POST` | Method is `GET` / `DELETE`, or the resolved inputs map is empty |
| `outputs` are all null | Response is non-JSON, or JsonPath does not match. Adjust JsonPath in the Webhook editor's `Output` section |
| Webhook never fires from Decision node | Decision did not land on `approve` / `reject`; or `triggerOn` excludes the current action; or `hook.enabled = false` |
| `Webhook URL is blank after placeholder resolve` | A `{var}` in the URL was not present in inputs. Declare it in `Inputs` or ensure an upstream node provides it |
| Signature secret error | Secret is blank or decryption failed. Re-save the secret in the Webhook editor (Signature section) |

### Quick Reference

- **Signature default headers**: `X-Webhook-Signature`, `X-Webhook-Timestamp` (customizable per Webhook)
- **Default algorithm**: `HMAC_SHA256` (when signature is enabled)
- **Default payload format**: `TIMESTAMP_BODY` → `timestamp + "\n" + body`
- **Default retry**: disabled (`maxAttempts=1`); `backoffMs=500` when enabled
- **Per-attempt HTTP timeout**: 10 s

---

==================== APPENDIX ====================

## Glossary

| Term | Description |
| --- | --- |
| **apiKey** | Public credential identifying your tenant. Included in every API request URL. |
| **apiSecret** | Private signing key for HMAC-SHA256 signatures. Never expose publicly. |
| **executionId** | Unique workflow execution instance identifier. Generated by `workflow.apply.submit`. |
| **callbackKey** | Identifies a specific node waiting for input. Each node has a unique callbackKey. |
| **requestId** | Per-API-call tracking ID for support and debugging. |
| **referenceId** | Your own tracking ID, passed through for audit trail and correlation. |
| **domainId** | Business unit identifier within your tenant (via `x-domain` header). |
| **nodeType** | Type of workflow node waiting for input. Determines which submission API to call. |
| **crpPid** | Connected Related Party identifier in KYB workflows. Links liveness, docs, forms to a CRP. |
| **JSON string field** | Fields like `personData`, `scores`, `images`, `formData` expect a JSON-encoded string, not a nested object. |

Execution Statuses

### Execution Statuses

These are the execution-level statuses. For server-side integrations the Case-level decision dimension (`caseStatus`) is documented in [Workflow Lifecycle API → Status & Case Decision](#api-workflow-status).

| Status | Terminal? | Description |
| --- | --- | --- |
| `CREATED` | No | Created, not yet started |
| `RUNNING` | No | Currently executing |
| `WAITING` | No | Waiting for external input |
| `COMPLETED` | Yes | Successfully completed |
| `FAILED` | Yes | Execution failed |
| `TIMEOUT` | Yes | Execution timed out |
| `CANCELLED` | Yes | Execution cancelled |

Event Types

### Event Types

| eventType | Mode | Description |
| --- | --- | --- |
| `KYC_EVENT` | Async | Individual customer onboarding. Shown as **KYC** in the Console. |
| `KYB_EVENT` | Async | Corporate customer onboarding. Shown as **KYB** in the Console. |
| `TRANSACTION_EVENT` | Sync / Async | Transaction screening |
| `WEB3_TRANSACTION_EVENT` | Sync / Async | Web3 / on-chain transaction screening (KYT) |
| `PERIODIC_FLOW_EVENT` | Async | Continuous monitoring |
| `MANUAL_CASE_EVENT` | Async | [Name screening](#api-name-screening) — submits a subject to the workflow, raising alerts and creating a case for manual review. Shown as **Manual** in the Console. |

Document Types

### Document Types

| Code | Description |
| --- | --- |
| `NATIONAL_ID` | National identity card |
| `INTERNATIONAL_PASSPORT` | International passport |
| `DRIVING_LICENCE` | Driving licence |
| `RESIDENCE_PERMIT` | Residence permit |
| `UTILITY_TELEPHONE_BILL` | Utility / telephone bill |
| `BANK_STATEMENT` | Bank statement |
| `CUSTOMER_ACCEPTANCE_FORM` | Customer acceptance form |
| `SELF_IMAGE` | Self-portrait / selfie |

Changelog

### Changelog

| Version | Date | Changes |
| --- | --- | --- |
| 1.2 | 2026-09-11 | Mobile SDK versions aligned to the production release: iOS 1.0.11 / Android 1.0.11 / Flutter 1.0.2. Credentials reduced to `domain` + `sdkToken` (`appId` / `apiKey` are now encoded inside the token). iOS requires `NSSpeechRecognitionUsageDescription`. Android requires `minSdk 26`, `compileSdk 36`, core library desugaring, and `android.uniquePackageNames=false` on AGP 9. New optional `language` parameter on all three platforms, and an optional `eventType` parameter on Android and Flutter. |
| 1.1.1 | 2026-06-14 | Android Permissions section corrected: the bundled OCR engines (Veriff, Regula) transitively merge `RECORD_AUDIO`, `NFC`, `WAKE_LOCK`, `VIBRATE` and `FLASHLIGHT`. Runtime (dangerous) permissions are now `CAMERA` and `RECORD_AUDIO`; every permission must be reflected in the Google Play Data Safety disclosure. |
| 1.1 | 2026-06-14 | Added Flutter SDK chapter. iOS public type names `Width*` → `WIDTH*` (1.0.5) and microphone (`NSMicrophoneUsageDescription`) now required. SDK versions aligned: iOS 1.0.5 / Android 1.0.2 / Flutter 1.0.1. |
| 1.0 | 2026-04-17 | Initial release — OpenAPI Reference, Android SDK, iOS SDK |

---

© 2026 WIDTH. All rights reserved.
