Authored by the WIDTH team由 WIDTH 团队编写

WIDTH IdentityDeveloper Documentation — Version 1.0 · Last Updated 2026-10-13开发者文档 — 版本 1.0 · 最后更新 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.

WIDTH Identity 提供完整的身份验证与合规平台,支持 KYC、KYB、交易筛查和持续监控工作流。本指南涵盖所有面向客户开发者的集成方式。

Integration Paths集成路径

Web SDKWeb 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.

Web 应用即插即用的验证流程。引入一个包,用链式调用配置,再调用 launch() — SDK 自行弹出弹窗或新标签页,并通过事件回报结果。无需提供 DOM 容器。

  • Self-hosted modal — no DOM container自托管弹窗 — 无需 DOM 容器
  • KYC and KYB workflowsKYC 和 KYB 工作流
  • ESM build, TypeScript typesESM 构建,自带 TypeScript 类型
  • Event-driven results (GREEN / RED)事件驱动结果(GREEN / RED)

Mobile SDK (iOS / Android / Flutter)移动 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.

移动应用即插即用 UI。SDK 处理完整的验证流程 — 证件采集、活体检测、OTP — 并返回结果。

  • Managed UI — minimal code托管 UI — 极少代码
  • KYC and KYB workflowsKYC 和 KYB 工作流
  • Customizable themes可定制主题
  • Resume & lifecycle support恢复与生命周期支持
  • Flutter plugin available提供 Flutter 插件

OpenAPI (Server-to-Server服务端到服务端)

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

通过 HTTPS REST API 进行后端集成。您的服务器逐步提交客户数据并接收工作流结果。

  • Full control over UX完全控制用户体验
  • KYC, KYB, Transaction ScreeningKYC、KYB、交易筛查
  • Continuous Monitoring持续监控
  • HMAC-SHA256 authenticationHMAC-SHA256 身份验证
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. 如果您需要在浏览器中即插即用的验证流程,请选择 Web SDK;在移动应用中需要同样开箱即用的体验且开发量最小,请选择 Mobile SDK。如果您已在自有表单中采集客户数据并希望完全控制后端逻辑,请选择 OpenAPI。两者可以组合使用 — 例如 SDK 处理前端,OpenAPI 处理服务端轮询和交易筛查。工作流也可通过 Webhook 把结果推送到你的服务器。

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:

在 One Platform 控制台的 API & Integration 中可获取两类凭证:

Credential Type凭证类型 Used By使用方 Fields字段
OPENAPI Server-to-server API服务端 API apiKey (ak_) + apiSecret (sk_)
SDK Mobile SDK移动 SDK App Key + SDK Token
The SDK is initialized with the sdkToken only.SDK 仅用 sdkToken 初始化。

How to Obtain Credentials如何获取凭证

  1. Log in to the One Platform Console → API & Integration登录 One Platform 控制台 → API & Integration
    • Staging: https://platform.width.com/saas/integration/api-keys
    • Production: https://app.width.com/saas/integration/api-keys
  2. Click Generate点击 Generate
  3. Note down the credentials:记录凭证:
    • 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. 切勿将 apiSecret 硬编码在源代码中,请使用环境变量或密钥管理器。避免通过命令行参数传递密钥(可能被记录在 shell 历史中)。SDK Token 是公开的客户端标识符,可以安全地打包在应用中。

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.

本节带技术对接方从零走到第一个验证结果:先在 One Platform 控制台准备什么、一次验证从头到尾怎么走、工作流如何得出决策、在哪里查看用量。每一步都链接到下方对应的详细参考章节。

Prerequisites (in the One Platform Console)前置准备(在 One Platform 控制台完成)

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

写代码前,先在目标环境(Staging 或 Production)的 One Platform 控制台里完成以下准备:

  1. Sign in to the Console. Use the Staging console to test and the Production console to go live (URLs in Environments).登录控制台。用 Staging 控制台做测试,用 Production 控制台正式上线(地址见环境)。
  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.确认或新建 Domain(业务单元 / Business Unit)。Domain 用来隔离一条业务线或一个地区——各自独立的工作流、成员和数据。新租户默认带一个 DEFAULT domain;需要区分环境或业务线时,在 Admin Console → Domains / Business Units 下新建。
  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).生成凭证。在 API & Integration 下按集成路径生成——OpenAPI 用 apiKey + apiSecret,移动 SDK 用对应的 SDK 凭证(见凭证)。
  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).配置并发布工作流。在控制台搭好你需要的工作流(KYC、KYB、交易筛查、Web3 或持续监控)并发布。每条工作流对应一个集成时会用到的 eventType(见事件类型附录)。

Your First Verification第一次验证(五步走通)

  1. Choose an integration path. Web SDK, Mobile SDK, or OpenAPI — see Integration Paths for how to decide.选集成路径。Web SDK、移动 SDK 或 OpenAPI——怎么选见集成路径。
  2. Set the environment and credentials. Point your client at the right base URLs and load the credentials from the prerequisites above (see Environments).配好环境与凭证。把客户端指向正确的基址,加载上面前置准备里生成的凭证(见环境)。
  3. Start a verification. SDK path — initialize and launch (Web, iOS, Android, Flutter). OpenAPI path — register the applicant, submit node data, then poll for the result (OpenAPI Reference, KYC Flow).发起验证。SDK 路径:初始化并 launch(Web、iOS、Android、Flutter)。OpenAPI 路径:注册申请人 → 提交节点数据 → 轮询结果(OpenAPI 参考、KYC 流程)。
  4. Receive the result. Poll workflow.execution.status (see Workflow Lifecycle API for the pure server-side path), or have the workflow push results to your server with a Webhook.接收结果。轮询 workflow.execution.status(纯服务端对接路径见 工作流生命周期 API),或让工作流通过 Webhook 把结果推送到你的服务器。
  5. Check the decision and your usage. The final decision is recorded in the Admin Console; see Workflows & the Decision Model for how it is reached and Usage & Quota for what each run consumes.查看决策与用量。最终决策记录在 Admin Console;决策怎么得出见工作流与决策模型,每次运行消耗多少见用量与配额。

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.

工作流是自动选择的。WIDTH 根据请求的 eventType 和它进来的接入通道(source)(Web SDK、iOS、Android 或 OpenAPI)自动路由到对应工作流——你不需要传 workflow ID。KYC 和 KYB 每个通道只对应一条活跃工作流(排他);交易筛查不排他——同一事件类型下可并存多条。

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.

在 Admin Console → Billing 页查看消耗:当前套餐(Plan)和用量统计——按计费周期统计的 API 调用次数、处理案件数(Cases Processed)、工作流数、团队成员数。


Web SDK Integration GuideWeb SDK 集成指南

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.

Width Web SDK 为 Web 应用提供即插即用的身份验证流程。支持 KYC 和 KYB 工作流,包括证件采集、活体检测与审核。SDK 自托管:你引入一个包,用链式调用配置它,再调用 launch() — SDK 会自行弹出弹窗或打开新标签页,并通过事件回报结果。无需提供 DOM 容器。它以 ESM 构建发布,自带完整 TypeScript 类型定义,无 peer 依赖。

Requirements系统要求

Requirement要求 Minimum最低版本
Module format模块格式 ESM (import)ESM(import 引入)
TypeScript Types included (optional)自带类型定义(可选)
Peer dependenciesPeer 依赖 None无
Backend后端 Must issue a session token via sdk.credentials需通过 sdk.credentials 签发会话 token

Step 1: Get a session token (backend)步骤 1:获取会话 token(后端)

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.

Web SDK 从一个一次性会话 token(即 sdkToken)开始。你的服务端向 Width 的 sdk.credentials 接口请求它,再把它交给浏览器。公开的 apiKey 与 domainId 在后续步骤中配置;带密钥的签名只在你的服务端完成。

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

在后端开一个小接口(例如 /your-backend/sdk-token),把 sdkToken 和 domainId 返回给前端。把从 domains[] 中选定的 domainId 在步骤 3 传入 SDK 配置。

Each token is single-use每个 token 仅一次性使用 Each sdkToken is single-use. Reissue a new token whenever a user starts a new verification — do not cache or reuse it. 每个 sdkToken 仅可使用一次。每当用户开始一次新的验证时,都要重新签发一个新 token — 不要缓存或复用。
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. 调用 sdk.credentials 使用与其余接口相同的网关基础地址与 HMAC 签名 — 网关地址、环境与签名细节见上方 OpenAPI 章节。

Step 2: Install the SDK步骤 2:安装 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).

从 npm 安装。安装后即可按包名 @width-com/web-sdk 引入 — ESM 构建,自带 TypeScript 类型定义,无 peer 依赖。装哪个标签同时决定 SDK 连到哪个环境:截至本次更新,默认(latest)版对应正式环境,@beta 标签版对应 platform(测试)环境。请按你的 apiKey 所属环境选择对应标签,并在上线前确认你装的这一版实际打开的是哪个地址(见下方提示)。

# 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标签决定环境 — 装错会看到 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. 验证页地址是随每个发布版本编译进包里的,装好之后连哪个环境就定死了,withConf 里也没有任何字段能改它。截至本次更新,默认(latest)版打开的是 https://identity.width.com/sdk-page(正式环境),@beta 版打开的是 https://identity-platform.width.com/sdk-page(platform 环境)— 这个对应关系取决于两个标签当前各自指向哪个构建,是当下的状态、不是固定规则,上线前请自行确认你装的这一版实际打开的是哪个地址。如果标签与你 apiKey 所属的环境对不上,这个页面会直接显示 Invalid apiKey,流程就停在这里 — 用同一把 key 调用后端 OpenAPI 不受影响,所以问题不在 key 本身。按环境选标签,不要按版本号新旧选。前后端共用一把 key:withConf 里与 key 相关的字段只有 apiKey 一个,它就是你签发 sdk.credentials 时用的那一把 — 包内自带的 TypeScript 类型定义列出了它接受的全部字段。供参考:@beta 目前指向 1.0.0-beta.3(2026-08-05 发布),默认版为 1.0.1,两者都含 eventType 与 language。

Step 3: Initialize (Quick Start)步骤 3:初始化(快速开始)

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.

用一条链式调用构建验证:init 传入会话 token,withConf 传入配置,用 on / onMessage 订阅事件,再 build().launch()。launch() 会弹出自托管的弹窗或新标签页 — 无需提供 DOM 容器。

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 latereventType 与 language 需要 1.0.1 及以上版本 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. 这两个字段自 1.0.1(2026-08-20 发布,即当前默认 latest 版)起提供,@beta 目前指向的 1.0.0-beta.3 同样含有它们 — 也就是说两个环境都能用,标签仍按环境选(见步骤 2)。1.0.0 及更早的正式版不含它们:TypeScript 项目会编译失败,纯 JavaScript 项目则不报错、也不生效。eventType 只接受 KYC_EVENT 或 KYB_EVENT,language 只接受 en 或 zh;两者都是选填,不传即走默认行为。

Configuration (withConf)配置(withConf)

Field字段 Type类型 Required必填 Description描述
apiKey string Yes是 Public Width API Key (ak_...)公开 Width API Key(ak_...)
domainId string Yes是 Business domain GID, from domains[] in sdk.credentials业务域(domain)GID,取自 sdk.credentials 的 domains[]
email string Yes是 End-user email终端用户邮箱
customerId string Yes是 Your internal user ID你的内部用户 ID
mode 'modal' | 'newtab' No否 Presentation, default 'modal'展示形态,默认 '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.界面语言。不传该字段时界面为英文;不会按浏览器语言自动判断。自 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). Available from 1.0.1.这次要跑哪一类流程——个人核验(KYC_EVENT)还是企业核验(KYB_EVENT)。不传该字段时按默认方式路由(见工作流与决策模型)。自 1.0.1 起提供。
zIndex number No否 Modal stacking order弹窗层级

Step 4: Handle the result步骤 4:处理验证结果

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.

按你订阅的事件分支处理。最终结论由 reviewResult.reviewAnswer 携带,只有两个取值:结论为通过时是 GREEN,其余一律是 RED。

.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已有最终结论 — 读取 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. executionId 是与后端 / OpenAPI 对账的句柄。对 idCheck.onApplicantSubmitted(异步审核)场景请持久化它,以便服务端稍后轮询最终状态。

Verification result reference验证结果参考

The final verdict is carried by reviewResult.reviewAnswer:

最终结论由 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, or the case in the Console). 未通过。SDK 会把「通过」以外的所有结论都映射成 RED——被拒绝的会落在这里,其他非通过的结果同样落在这里。把 RED 当作「已拒绝」处理之前,先查案件状态(workflow.execution.status 返回的 caseStatus,或到控制台看该案件)。
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. 截至 1.0.1(1.0.0-beta.3 相同),Web SDK 只把结论收成这两个值,没有第三个取值。GREEN 走通过分支;RED 按「未通过」处理,除非案件状态确认它就是拒绝。

Methods方法

Call调用 Returns返回 Purpose作用
widthWebSdk.init(accessToken) builder Start the chain with the session token用会话 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启动验证,返回本次会话的整条验证页网址 — 形如 https://identity.width.com/sdk-page?sdkMode=1&sdkSession=<会话 id>&apiKey=<你的 apiKey>&theme=light,其中主机名取自你安装的那一版(见步骤 2)— 启动失败时返回 ''。这条网址对应的就是本次验证会话,它背后的会话 token 仅一次性有效(见步骤 1)。container 被忽略
instance.close() void Programmatically close the verification window主动关闭验证窗口

Events事件参考

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

用 .on(eventName, callback) 注册单个事件,或用 .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)用户关闭(仅经 onMessage) {}
Errors错误投递 Validation failures and runtime errors are all delivered via idCheck.onError — the SDK does not throw to your code. 校验失败与运行时错误统一经 idCheck.onError 投递 — SDK 不会向你的代码抛异常。

Error Codes错误码

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

在 idCheck.onError 中,payload.code 为以下之一:

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否

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.

Web SDK 依赖 crypto.randomUUID、ES2020 语法,以及现代的 fetch 与 postMessage。下表是同时具备这三项的最低版本,低于该版本的浏览器不在支持范围内。

Browser浏览器 Minimum version最低版本
Chrome / Edge (desktop)Chrome / Edge(桌面端) 92+
FirefoxFirefox 95+
Safari (macOS and iOS)Safari(macOS 与 iOS) 15.4+
Chrome (Android)Chrome(Android) 92+

Troubleshooting故障排查

Symptom现象 Cause可能原因 Resolution解决
onError { INVALID_INPUT, "apiKey is required." } apiKey missing or emptyapiKey 缺失或为空 Pass the public API Key传入公开 API Key
onError { INVALID_INPUT, "accessToken is required." } Backend didn't return sdkToken后端未返回 sdkToken Check the sdk.credentials integration检查 sdk.credentials 集成
onError { INVALID_INPUT, "domainId is required." } domainId not passed in withConf初始化时 withConf 未传 domainId Pass the id of the domain you picked from domains[] in the sdk.credentials response传入你从 sdk.credentials 返回的 domains[] 中选定那个 domain 的 id
onError { INVALID_INPUT, "email is required." } Missing email缺少 email Pass the end-user email传入终端用户邮箱
onError { INVALID_INPUT, "customerId is required." } Missing customerId缺少 customerId Pass the internal user ID传入内部用户 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 appsapiKey 与 accessToken 不属于同一应用 Reissue the token with the same apiKey用同一 apiKey 重新签发 token
onError { SDK_ERROR } Network / connection issue网络 / 连接问题 Rebuild the chain and launch() again重新构建链并再次 launch()
Modal won't appear / iframe blocked弹窗不出现 / iframe 被拦截 Domain not allowlisted, or CSP frame-src missing the origin域名未加白名单,或 CSP frame-src 缺少该源 Add the origin under API & Integration in the Console (see the note below the table), then allow it in your CSP frame-src在控制台 API & Integration 下把该源加进白名单(见表格下方说明),并在 CSP frame-src 里放行它
Camera permission denied相机权限被拒 Host Permissions-Policy is too strict宿主 Permissions-Policy 过严 Update your policy headers (see note below)更新你的策略头(见下方说明)
No events fire无事件触发 Session still ongoing, or callbacks not registered会话仍在进行,或未注册回调 Wait for completion; confirm your .on() callbacks等待完成;检查 .on() 回调
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. 白名单由你自己在控制台配置:在 API & Integration(API 与集成) 下,把承载 SDK 的每个源逐个加进去。每条地址必须以 https:// 或 http:// 开头、不带路径、也不支持通配符,因此每个主机名都要单独写一条(例如 https://app.example.com 和 https://checkout.example.com)。如果这个页面上看不到生成密钥的按钮,通常是当前账号的角色缺少管理 API 密钥这条权限 — 这类按钮按权限渲染,没有权限时是直接不显示、而不是变灰,请让租户管理员为你开通。
CSP & Permissions-PolicyCSP 与权限策略 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. 在 modal 模式下,SDK 会在你自己的页面里插入一个 iframe 来加载验证页,所以只要你的页面设了 Content-Security-Policy,就必须在 frame-src 里放行这个源,并通过 Permissions-Policy 把相机(以及活体所需的麦克风 / 运动传感器)授权给同一个源。填哪个源取决于你装的是哪个标签(见步骤 2):默认(latest,当前为 1.0.1)版加载的是 https://identity.width.com,@beta 版加载的是 https://identity-platform.width.com。按你实际上线的那一版选对应的一段 — 源没写进 frame-src,浏览器就会拦掉这个 iframe,验证窗口只剩空白。
# 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 Integration GuideiOS SDK 集成指南

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.

Width Identity SDK 为 iOS 应用提供即插即用的身份验证流程。支持 KYC 和 KYB 工作流。你 import WidthIdentity 并调用一个入口;SDK 即呈现完整的采集 / 活体 / 审核界面,并返回单一结果。公共 API 使用 Swift 原生类型(带关联值的枚举、结构体、闭包),从 Swift 中使用。

Requirements系统要求

Requirement要求 Minimum最低版本
iOS 16.0+ deployment target16.0+(部署目标)
Xcode 16+
Dependency manager依赖管理器 Swift Package Manager or CocoaPodsSwift Package Manager 或 CocoaPods

Installation安装

Option A: Swift Package Manager (Recommended)方式 A:Swift Package Manager(推荐)

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.

WidthIdentity-iOS 是私有仓库 — 在你的 GitHub 账号拿到访问权之前,Xcode 和 git 都只会提示仓库不存在,所以先确认访问权已开通,再执行下面的步骤。

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

在 Xcode 中:File > Add Package Dependencies…,输入:

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

Or in Package.swift:

或在 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方式 B:CocoaPods

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

WidthIdentity 发布在 Width 的私有 Specs 仓库,因此需在 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.

该 Specs 仓库同样是私有的 — 只有你的 GitHub 账号拿到访问权之后,pod install 才解析得到;没有访问权时,这个源看起来就是「仓库不存在」。

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.

然后执行 pod install。

Info.plist PermissionsInfo.plist 权限

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:

SDK token 不再存放于 Info.plist。它在运行时通过 CredentialsConfig.sdkToken 传入(见快速开始)。相机、麦克风、语音识别三项使用描述都必须声明;照片库那一项可选:

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

NSCameraUsageDescription 与 NSMicrophoneUsageDescription 两项都是必填:证件扫描环节会录制背景音频用于反欺诈,缺了麦克风这个 key,应用会在运行时直接崩溃。SDK 没有任何与环境相关的 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.

NSSpeechRecognitionUsageDescription 必填的原因不一样。SDK 运行时从不申请语音识别,但 AwsLiveness.xcframework 静态吸收了 Amplify 的 Predictions 插件,该插件引用了 SFSpeechRecognizer。缺这个 key,App Store 会在入库(ingestion,上传包进入审核前的自动校验)阶段直接退回(错误码 ITMS-90683)— 而且是在整个二进制包传完之后才报,与这个接口有没有被调用无关。这个 key 的文案直说「本应用不使用语音识别」即可:权限永不申请,用户也就永远看不到这句话。

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.

SDK 一共包含八个 xcframework:WidthIdentity、SecCamera、onnxruntime、AwsLiveness、Veriff、DocumentReader、DocumentReaderCore、RegulaCommon,全部自动嵌入。其中 AwsLiveness 是自包含的,你不需要自己引入任何 Amplify 或 AWS 依赖。

Quick Start快速开始

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

import WidthIdentity 提供两种等价的入口风格 — 按喜好选择即可。两者驱动完全相同的验证界面。

Direct input (UIKit)直接输入(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)直接输入(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)Handler 风格入口(备选)

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

WIDTHMobileSDK 是另一种入口风格,以对象方式使用 — 先构造对象,设置属性与各个 handler 闭包,再调用 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:

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. accessToken 里装的是 sdkToken;其余凭据在客户端通过 sdk.credentials / sdk.applicant 设置。凭据或申请人信息缺失这类配置错误,会表现为 sdk.status == .failed,并在 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.

直接输入入口接受一个 SdkEventLogger,可将 SDK 生命周期事件(INFO / WARN / ERROR)接入你自己的管道(Crashlytics、DataDog 等);回调触发前已脱敏 PII(个人身份信息)。Handler 风格入口通过 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())

Configuration Reference配置参考

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

输入结构与 Android 相同:VerificationInput、CredentialsConfig(domain 与 sdkToken)以及 CustomerConfig(customerId + email,两者都必填)。字段详情参见 Android 配置参考。在 iOS 上,VerificationInput 的初始化器是 throws 的,并额外接受一个可选的 eventLogger。

iOS-specific entry points and theme overrides:

iOS 特定的入口与主题覆盖:

Symbol符号 Purpose用途
WIDTHVerification.present(from:input:completion:) UIKit native entry pointUIKit 原生入口
View.widthVerification(isPresented:input:onResult:) SwiftUI native entry pointSwiftUI 原生入口
WIDTHMobileSDK(accessToken:) + credentials/applicant + present(from:) UIKit handler-style entryUIKit Handler 风格入口
View.widthMobileSDK(isPresented:makeSDK:) SwiftUI handler-style entrySwiftUI Handler 风格入口
ThemeConfig / ThemeMode Optional theme override可选主题覆盖
UILanguage Optional UI language (.en default / .zh)可选的界面语言(.en 为默认值 / .zh)

Handling Results结果处理

Direct-input VerificationResult直接输入的 VerificationResult

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

五种 Swift 枚举变体(与 Android 的五种变体对应):

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用户退出但打算稍后返回(可恢复);若工作流尚未开始,executionId 为 nil
.cancelled(executionId) User explicitly discarded; execution destroyed, not resumable用户主动放弃;执行已销毁,不可恢复
.failed(code, message, executionId?) Internal error内部错误
Dismissed vs CancelledDismissed 与 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. .dismissed 表示用户暂停、可恢复;.cancelled 表示用户放弃、服务端执行已销毁(不可恢复)。若失败发生在执行创建之前,executionId 可能为 nil;如果存在,请在工单中附上该 ID 以加快排查。

Handler-style entryHandler 风格入口

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.

verificationHandler { (isApproved: Bool) } 在最终通过/拒绝决定时触发。sdk.status(WIDTHStatus):.approved、.finallyRejected、.pending(人工审核)、.incomplete(中途退出 / 等待,可恢复)、.cancelled(已销毁)、.failed。当为 .failed 时,sdk.failReason(WIDTHException)为 .initialization、.network、.api、.permission、.workflow、.unknown 之一 — 每个都暴露 code 与 message。

Theme Customization主题定制

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

验证界面默认跟随系统外观。用 dayNightMode 强制指定模式;省略则跟随系统。

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

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.

与 Android 行为一致。在 iOS 上,活跃工作流期间会禁用 sheet 的下滑关闭手势,以防止意外丢失进度。

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.

恢复验证时,使用相同的 customerId 再次启动验证界面,SDK 会自动检测进行中的工作流。

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)仅当允许用户从照片库选取证件图片时(系统 PhotosPicker 并不严格要求该 key)
Speech recognition语音识别 NSSpeechRecognitionUsageDescription Yes是 Checked by App Store ingestion. The permission is never requested at runtime, so the user never sees this string由 App Store 入库校验检查。运行时永不申请该权限,用户也就永远看不到这句文案
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. 相机与麦克风均为必填。证件扫描步骤会录制背景音频作为反欺诈措施,因此缺少 NSMicrophoneUsageDescription 会在启动时导致硬崩溃。NSSpeechRecognitionUsageDescription 同样必填,但它卡的是 App Store 入库校验、不是运行时(见「安装」一节)。没有任何 SDK 环境相关的 Info.plist key(无位置 key、无 token key)。网络:通过 URLSession 使用 HTTPS,无需配置 NSAppTransportSecurity 例外。

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.

App Thinning:XCFramework 支持 App Thinning。不嵌入 Bitcode(已在 Xcode 14 中弃用)。如遇 release 构建问题,请检查应用 target 中 Strip Swift Symbols (STRIP_SWIFT_SYMBOLS) 是否设置为默认值 (YES)。

Troubleshooting故障排查

Issue问题 Solution解决方案
No such module 'WidthIdentity'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).SPM:File > Packages > Resolve Package Versions。确认 WidthIdentity 库已添加到 Target > General > Frameworks, Libraries, and Embedded Content 中。CocoaPods:声明私有源 source 'https://github.com/width-com/Specs.git',执行 pod install,并打开 .xcworkspace(而非 .xcodeproj)。
.failed on launch (e.g. W-INIT-410)启动时返回 .failed(如 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.VerificationInput 初始化器在 domain / sdkToken 为空,或 customerId / email 为空时抛错;输入闭包抛出的错误会表现为 .failed。请确认这四项都非空。
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.确保 Info.plist 中存在 NSCameraUsageDescription 且描述不为空。若用户此前已拒绝权限,iOS 不会重新弹窗 — SDK 会检测到此状态并显示引导界面,指引用户前往设置 > 你的应用 > 相机开启权限。
Theme colors not applied主题颜色未生效 Verify hex values, case-sensitive tokens, correct theme map检查十六进制值、令牌名称(区分大小写)及正确的主题字典
SwiftUI sheet not presentingSwiftUI sheet 未弹出 Attach .widthVerification / .widthMobileSDK to a view in the hierarchy, not conditionally将 .widthVerification / .widthMobileSDK 附加到视图层级中的视图上,而非条件性添加
UIKit: "not in window hierarchy"UIKit:"not in window hierarchy" Present from a view controller after viewDidAppear在 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.AWS 活体检测页面的文案跟随设备语言,不跟随 SDK 的 language 设置。流程的其余部分仍按 sdk.language 显示。
Upgrading: bump the version constraint (the SPM from: value or the Podfile version) and resolve packages. 升级:把版本约束改成新版本号(SPM 的 from: 值,或 Podfile 里的版本),再重新解析依赖即可。

Android SDK Integration GuideAndroid SDK 集成指南

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.

Width Identity SDK 为 Android 应用提供即插即用的身份验证流程。支持 KYC 和 KYB 工作流,包括证件采集、活体检测与审核。SDK 在独立的 Activity 中运行;你只需添加一个依赖、调用一个入口,SDK 即返回单一结果。

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 build36 — SDK 发布产物的 AAR 元数据里写着 minCompileSdk=36,构建工具会强制校验,配得比它低会直接构建失败
Kotlin 1.9+
Gradle / AGP 8.0+
Java 11 source/target11(source/target)
Host app宿主应用 Jetpack Compose-based or View-based (the SDK runs in its own Activity)Jetpack Compose 或传统 View 体系均可(SDK 在自己的 Activity 中运行)

Installation安装

Step 1: Add the Maven Repository步骤 1:添加 Maven 仓库

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.

在 settings.gradle.kts 中。Width 仓库提供 SDK 及其由 Width 托管的传递依赖(com.width.risksec、com.width.camera);其余依赖(AndroidX / Kotlin / Ktor / CameraX)从 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.

SDK 内置的证件采集引擎由各自的厂商托管,不在 Width 的 Maven 上,所以它们的仓库也要加上 — 构建期必须有,哪怕某个采集商在你的流程里用不到。下面两个厂商仓库块请原样照抄。

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步骤 2:添加依赖

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

在应用级 build.gradle.kts 中。单个坐标即可传递引入相机、活体及配套库 — 无需 BOM,也无需额外坐标。

dependencies {
    implementation("com.width.identity:sdk-activity:1.0.11")
}
minSdk requirement: the SDK requires minSdk 26. minSdk 要求:SDK 要求 minSdk 26。

Step 3: Required Build Settings步骤 3:必需的构建配置

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

下面两项配置加在你自己的 App 模块上,不是 SDK 侧的事。不加,构建直接失败 — 两项都不需要改你的任何源码。

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:

必须开启 core library desugaring(把新版 Java 标准库的能力降级到旧 Android 版本上可用的编译期处理)。内置的 AWS Rekognition 活体引擎带的 Amplify AAR 在元数据里声明了 requires core library desugaring,AGP 会在 App 侧强制校验(checkReleaseAarMetadata / checkDebugAarMetadata),与你的 minSdk 是多少无关。在 App 模块加上:

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:

AGP 9 上必须加 android.uniquePackageNames=false。 AWS 活体引擎传递引入的两个产物(com.google.ai.edge.litert:litert-support 与 litert-support-api,都是 1.4.1)声明了同一个库命名空间 org.tensorflow.lite.support — 这是上游的打包缺陷。AGP 9 的清单合并会校验命名空间唯一性,冲突就以 Validation failed, exiting 中断构建。在项目的 gradle.properties 里加上:

# gradle.properties
android.uniquePackageNames=false
No more BOM or UI coordinate不再需要 BOM 与 UI 坐标 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-bom 平台依赖加上单独的 sdk-ui-width-modern 坐标。现在不再需要 — sdk-activity 已聚合全部内容。
SDK token movedSDK Token 位置变更 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). SDK token 不再通过 AndroidManifest.xml 的 <meta-data> 节点 / strings.xml 注册。现在改为在运行时作为 CredentialsConfig 中的 sdkToken 字段传入(见快速开始)。

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.

SDK 提供两种等价的入口风格 — 按你的调用点选择即可。两者驱动完全相同的验证界面,并返回单一结果。

Direct input (ActivityResultContract)直接输入(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)Builder 入口(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.

链式构造器(fluent builder)把启动所需的输入串成一条链装配起来 — 依次给出 access token、凭据、申请人,再按需挂上 handler,最后 build 并启动,返回单一的 WIDTHCompletionResult。先用 WIDTHVerification 契约在 composition 中注册 launcher,再在调用点构建并启动。

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.

这只是另一种入口写法,不是另一条启动路径:builder 在底层装配出原生的 VerificationInput,跑的仍是同一套流程。withAccessToken 传的就是 sdkToken,租户的 appId / apiKey 已经编码在这个 token 里、由 SDK 在设备上解密;客户端只需要通过 withCredentials 传 domain,通过 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.

withEventType 可选("KYC_EVENT" / "KYB_EVENT")— 传了就直接进入对应流程、跳过 SDK 内的选择页;不传则由用户自己选。

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. VerificationInput(...) 在下列情况抛出 IllegalArgumentException:domain / sdkToken 为空,customerId / email 为空,或 eventType 传了非空值但不是 "KYC_EVENT" / "KYB_EVENT";build() 则在必填的 builder 字段没设时抛出。请在调用点捕获。

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.

注册一个 SdkEventLogger 即可将 SDK 生命周期事件(INFO / WARN / ERROR)接入你自己的管道(Crashlytics、Timber、DataDog 等)。回调触发前已脱敏已知的 PII(个人身份信息)。SdkEventLogger 是函数式接口,任何需要它的位置都可以传入 lambda。

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 = ...).

该 logger 是全局且可选的;调用 SdkLogging.setLogger(null) 即可停止转发。也可以通过 withHandlers(onEvent = ...) 在 builder 上就地注册同一个 logger。

Configuration Reference配置参考

VerificationInput

Field字段 Type类型 Required必填 Description描述
credentials CredentialsConfig Yes是 SDK authenticationSDK 认证配置
customer CustomerConfig Yes是 Customer identity客户身份信息
theme ThemeConfig No否 UI theme customizationUI 主题定制
eventType String No否 "KYC_EVENT" / "KYB_EVENT" to skip the in-SDK selection screen; omit to let the user pick传 "KYC_EVENT" / "KYB_EVENT" 可跳过 SDK 内的流程选择页;不传则由用户自己选
language UILanguage No否 UI language: UILanguage.EN (default) / .ZH界面语言:UILanguage.EN(默认)/ .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>)SDK token(以往通过 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.) customerId 和 email 两者都必须提供且不可为空。任一为空,构造时即抛出 IllegalArgumentException。(此规则比以往更严格 — 以往只要求二者至少提供其一。)

Public API公开 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.

com.width.identity.activity 是唯一对客户开放的包 — 其余都是内部实现,在你的应用里引用会直接编译报错。

Symbol符号 Purpose用途
Verification ActivityResultContract entry pointActivityResultContract 入口
VerificationInput / CredentialsConfig / CustomerConfig Launch parameters启动参数
VerificationResult / VerificationDecision Direct-input result直接输入入口的结果
WIDTHMobileSDK.Builder + WIDTHVerification Builder entry point (Compose)Builder 入口(Compose)
WIDTHCompletionResult / WIDTHStatus / WIDTHException Builder result typesBuilder 入口的结果类型
ThemeConfig / WIDTHDayNightMode Optional theme / day-night override可选的主题 / 日夜模式覆盖
UILanguage Optional UI language (EN default / ZH)可选的界面语言(EN 为默认值 / 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.

不传 language 就是英文 — SDK 不会跟随设备语言。第三方采集页面另有限制:Veriff 只有在设备联网、且租户的集成开启了中文时才显示中文,否则仍是英文;Regula 只支持简体中文。

Handling Results结果处理

Direct-input VerificationResult直接输入的 VerificationResult

VerificationResult is a sealed class with five variants:

VerificationResult 是一个密封类,包含五种变体:

Result结果 Fields字段 Description描述
Completed executionId, decision Server returned a decision: APPROVED / REJECTED / REVIEW (under manual review out-of-band)服务端返回决定:APPROVED / REJECTED / REVIEW(在带外进行人工审核)
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.用户退出但打算稍后返回(X → 保留进度,或在工作流开始前退出)。服务端执行被保留,下次启动即可恢复;若工作流尚未开始,executionId 为 null。可恢复。
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.用户主动放弃验证(X → 放弃)。SDK 已等待服务端的 workflow.execution.cancel,执行已销毁,无法恢复。
Failed code, message, executionId? Internal error内部错误
Dismissed vs CancelledDismissed 与 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). 旧版只有一个 Cancelled 现在被拆分为两种:Dismissed 表示用户暂停、可恢复;Cancelled 表示用户放弃、服务端执行已销毁(不可恢复)。

Builder WIDTHCompletionResultBuilder 的 WIDTHCompletionResult

Case变体 When何时
SuccessTermination(status, executionId?) Flow ended normally; final state carried by status流程正常结束;最终状态由 status 携带
AbnormalTermination(exception, executionId?) Technical failure; exception.code / exception.message carry detail技术性失败;exception.code / exception.message 携带细节

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.

status 是 WIDTHStatus:Approved、FinallyRejected、Pending(人工审核)、Incomplete(可恢复 / 已 dismissed)、Cancelled(已销毁)。exception 是 WIDTHException:Init、Network、Api、Permission、Workflow、Unknown 之一 — 每个都暴露 code 与 message。

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 设置模式,或在 Builder 入口覆盖日间/夜间。两者省略时均跟随系统设置。

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

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

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.

恢复验证时,使用相同的 customerId 调用 launcher.launch(...),SDK 会自动检测进行中的工作流。

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:

SDK 与其内置的采集引擎声明了所需的全部权限,并会自动合并进你的应用 — 你无需声明或申请它们:

<!-- 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)证件采集、活体检测(SDK 核心)
INTERNET Install-time安装时 API communication (SDK core)API 通信(SDK 核心)
ACCESS_NETWORK_STATE Install-time安装时 Connectivity checks (SDK core)网络连接检测(SDK 核心)
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. 运行时(危险级)权限是 CAMERA 与 RECORD_AUDIO;由 SDK 及其采集引擎在各自的 Activity 内部申请,你的应用不会弹窗。上述每一项权限都会出现在应用的权限列表里,必须如实反映到你的 Google Play Data Safety(数据安全)申报中。SDK 不需要任何存储 / 媒体权限 — 选择证件图片走系统照片选择器。

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

ProGuard / R8:SDK 内置了混淆规则,无需额外配置。

Troubleshooting故障排查

Issue问题 Solution解决方案
Failed to resolve com.width.identity:...无法解析 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.确保 Width Maven 仓库配置在 settings.gradle.kts 中(而非 build.gradle.kts),并使用单一坐标 com.width.identity:sdk-activity:1.0.11(不再用 BOM)。如果解析不到的是 com.veriff 或 com.regula.*,说明步骤 1 里那两个厂商仓库没加。
IllegalArgumentException on launch启动时抛出 IllegalArgumentException 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".检查 domain / sdkToken 以及 customerId 和 email 是否都非空。还要检查 eventType:一旦传了值,就必须正好是 "KYC_EVENT" 或 "KYB_EVENT"。
Camera not working摄像头无法使用 Check the merged manifest for permission conflicts; the SDK auto-merges CAMERA from its library manifest.检查合并后的 manifest 是否存在权限冲突;SDK 会从其库 manifest 自动合并 CAMERA。
Theme colors not applied主题颜色未生效 Verify hex values (no # prefix), case-sensitive token names检查十六进制值(无需 # 前缀),令牌名称区分大小写
Build fails on checkReleaseAarMetadata / checkDebugAarMetadata with requires core library desugaring构建在 checkReleaseAarMetadata / checkDebugAarMetadata 上失败,提示 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.在 App 模块开启 core library desugaring 并加上 desugar_jdk_libs 依赖 — 见「安装」的步骤 3。这项校验与你的 minSdk 是多少无关。
Build fails on the same AAR metadata check because the module's compileSdk is lower than the SDK requires同一道 AAR 元数据校验失败,原因是模块的 compileSdk 低于 SDK 的要求 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.SDK 的几个 AAR 在元数据里写着 minCompileSdk=36,构建工具会强制校验,模块拿比它低的版本编译就会中断构建。在 App 模块把 compileSdk 设为 36 — 见「系统要求」。这与 minSdk 是两回事,后者仍是 26。
Manifest merge fails with Validation failed, exiting on AGP 9AGP 9 上清单合并失败,报 Validation failed, exiting Add android.uniquePackageNames=false to your project's gradle.properties — see Installation, Step 3.在项目的 gradle.properties 里加上 android.uniquePackageNames=false — 见「安装」的步骤 3。
Upgrading: bump the version string in your build.gradle.kts; Gradle fetches the new artifacts from maven.width.com on the next sync. 升级:把 build.gradle.kts 里的版本号改成新版本,下次 sync 时 Gradle 会从 maven.width.com 拉取新产物。

Flutter SDK Integration GuideFlutter SDK 集成指南

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

WIDTH Identity SDK 以即插即用的 Flutter 插件形式提供身份验证流程(KYC 与 KYB)。你添加一个依赖、调用一个入口;原生 SDK 全屏呈现完整的采集 / 活体 / 审核界面,并返回单一结果。该插件封装原生 iOS 与 Android SDK — 仅支持 iOS 与 Android(不支持 web 或桌面)。

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. 插件 1.0.2 — 绑定 iOS SDK 1.0.11 与 Android SDK 1.0.11。升级插件即一并升级原生 SDK;不要手动覆盖原生依赖。

Requirements系统要求

Requirement要求 Minimum最低版本
Flutter 3.10+
iOS 16.0+ deployment target, Xcode 16+, CocoaPods16.0+(部署目标)、Xcode 16+、CocoaPods
Android minSdk 26 (Android 8.0), compileSdk 36, core library desugaring enabled (see Android below)minSdk 26(Android 8.0)、compileSdk 36,并开启 core library desugaring(见下文 Android 一节)
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. 原生 SDK 是单环境构建 — 每个发布版只连一个 WIDTH 环境,环境在构建时就写死了。本版本绑定的原生 SDK 是生产环境的构建,所以 WIDTH 下发给你的 domain / accessToken 也必须是生产凭据。用别的环境的 token,过不了 SDK 的安全初始化,报错表现为 W-RISK-102。

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.

插件仓库、以及它 iOS 侧要拉的那个私有 Specs 仓库,都要先给你的 GitHub 账号开通访问权 — 在那之前,flutter pub get 和 pod install 都只会提示仓库不存在。

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

该插件通过 WIDTH 的私有 Git 仓库分发。将它添加到 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.

然后执行 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:

原生 WidthIdentity pod 从 WIDTH 的私有 Specs 仓库解析。在 ios/Podfile 顶部声明两个 source 并设置 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.

然后执行 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.

在 android/app/build.gradle 中设置 minSdk 26。插件会自动注册 WIDTH Maven 仓库、供应商采集引擎仓库(Veriff、Regula)以及原生依赖。

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

原生 SDK 内置的 AWS 活体引擎要求两项构建配置 — 都加在你自己的 App 上,两项都不涉及你的源码:

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

该引擎的 Amplify AAR 在元数据里声明了「requires core library desugaring」,AGP 会在 App 模块上强制校验,与你的 minSdk 是多少无关;不开启,构建直接失败。

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

AGP 9 的清单合并会校验库命名空间的唯一性,而活体引擎传递引入的两个产物(com.google.ai.edge.litert:litert-support 与 litert-support-api)声明了同一个命名空间 org.tensorflow.lite.support — 这是上游的打包缺陷。不加这个开关,构建会以 Validation failed, exiting 失败。

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

若你的项目启用了 RepositoriesMode.FAIL_ON_PROJECT_REPOS,则改为在 android/settings.gradle 中声明这些仓库:

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.*") }
        }
    }
}

Permissions权限

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

iOS — 添加到 ios/Runner/Info.plist。相机、麦克风、语音识别三项必填;照片库那一项可选:

<!-- 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 for the full list, and reflect every permission in your Google Play Data Safety disclosure.

Android — 原生 SDK 的 manifest 会自动合并所需权限,你无需声明。运行时(危险级)权限是 CAMERA 与 RECORD_AUDIO(后者由内置的采集 / 活体引擎引入),由 SDK 在其自有 Activity 内部申请。完整权限清单见 Android 章「权限」节,并需把每一项反映到你的 Google Play Data Safety(数据安全)申报中。

Quick Start快速开始

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

引入插件,用链式调用构建 SDK,再 await sdk.launch()。当原生流程关闭时该 future 完成。

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.

传入 onEvent handler,可在你自己的管道(Crashlytics、DataDog 等)中接收 SDK 生命周期事件(INFO / WARN / ERROR);回调触发前已脱敏 PII(个人身份信息)。

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

withLanguage(WIDTHLanguage.zh) 把整个流程切成简体中文 — 包括 SDK 自身的文案,以及后端返回的 {en, zh} 动态内容。不传就是英文:原生 SDK 从不跟随设备语言,所以已有的集成不会受影响。

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.

内置的第三方采集页面另有限制:证件扫描商只有在设备联网、且租户的集成开启了中文时才显示中文,否则仍是英文;证件阅读器只支持简体中文。

Handling Results结果处理

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

launch() 总会完成;对 SDK 级别的失败不会抛出异常。

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用户中途退出或决定仍在等待;用相同 customerId 可恢复
cancelled User explicitly discarded the verification; not resumable用户主动放弃验证;不可恢复
failed Internal error; see result.exception内部错误;见 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.

当为 .failed 时,result.exception(WIDTHException)带一个 type — initialization、network、api、permission、workflow、unknown 之一 — 并保留原始 code(如 W-LIV-499)与 message。result.executionId 标识该次运行,便于支持排查。

API ReferenceAPI 参考

Symbol符号 Purpose用途
WIDTHMobileSDK.init(accessToken) Entry point, returns the builder入口,返回 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可选的 KYC / KYB 流程预选
WIDTHDayNightMode Forced theme强制主题
WIDTHLanguage Optional UI language (en default / zh)可选的界面语言(en 为默认值 / 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. 升级:修改 pubspec.yaml 中的 ref 标签并执行 flutter pub get。每个插件版本都绑定了它验证过的原生 SDK 版本 — 不要手动覆盖原生依赖。

OpenAPI ReferenceOpenAPI 参考

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

通过 HTTPS REST API 进行服务端到服务端集成。所有请求均以 HTTP POST 发送至 Gateway URL。

Getting Started快速入门

Base URL基础地址

Environment环境 Gateway URLGateway URL
Staging https://api-gateway-platform.width.com/gateway
Production https://api-gateway.width.com/gateway

Request Format请求格式

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 nameAPI 名称
apiVersion Query Yes是 Varies per interface — workflow.apply.submit recommends 2.0.0, others use 1.0.0 (see Workflow Lifecycle API)按接口而定 — workflow.apply.submit 推荐 2.0.0,其余用 1.0.0(见 工作流生命周期 API)
apiKey Query Yes是 Your API key您的 API key
sign Query Yes是 HMAC-SHA256 signature of request body请求体的 HMAC-SHA256 签名
x-domain Header Yes是 Your business domain ID您的业务 domain ID

Response Format响应格式

Success:

成功:

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

Error:

错误:

{
  "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). 分两层读。HTTP 状态码是传输层 — 4xx/5xx 表示网关未受理请求(无 data)。HTTP 200 时再看 apiCode 判断网关结果(200 = 成功)。部分业务接口会在 data 下再包一层 { code, data, msg } 业务信封 — 业务数据在 data.data(见下方「注册客户」示例)。

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 foundAPI 名称未找到 Verify api parameter检查 api 参数
999303 API_NON_AUTHORIZED Not authorized for this API无此 API 权限 Check apiKey permissions检查 apiKey 权限
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 exceededAPI 调用配额已用尽 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.

所有节点数据提交接口均基于 callbackKey 幂等。重复提交相同 callbackKey 是安全的 — 仅首次成功提交生效,因此网络超时后可放心重试。

Interaction Model交互模型


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.

密钥和请求体均使用 UTF-8 编码。结果为 64 位小写十六进制字符串。 签名必须基于 HTTP body 的原始字节计算。

Code Examples代码示例

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:

import hmac, hashlib

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

Node.js:

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

Configuration配置

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

在启动工作流前,获取平台配置数据(国家列表、证件类型、表单模板等)。

Endpoint:接口: prepare.avira.config POST

{
  "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)Particular 节点 (KYC & KYB)
required-form Form templates with validation rules带验证规则的表单模板 Required Forms nodesRequired Forms 节点
avira_countries Country list (ISO codes + names)国家列表 (ISO 代码 + 名称) Nationality, residence, etc.国籍、居住国等
avira_document_master Supported document types per country各国支持的证件类型 OCR & document uploadOCR 及证件上传
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 particularKYB particular
ownership_structure_layer Ownership structure depth settings股权结构层级设置 KYB workflowsKYB 工作流
transaction_behaviour Transaction behaviour categories交易行为类别 KYB formsKYB 表单
product_service_complexity Product/service complexity categories产品/服务复杂度类别 KYB formsKYB 表单
source_of_wealth Source of wealth options财富来源选项 KYC/KYB formsKYC/KYB 表单
avira_source_of_funds Source of funds options资金来源选项 KYC/KYB formsKYC/KYB 表单
Caching — Configuration data changes infrequently. Cache it locally and refresh daily or on demand. 缓存 — 配置数据变更频率低,建议本地缓存并每日或按需刷新。

Workflow Lifecycle API工作流生命周期 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.

工作流生命周期 API 是纯服务端对接路径:由你的后端发起一个事件、轮询执行状态与 Case(案件,一次审核的记录单元)审核结论,并在请求丢失或被重试时查询该客户是否已有进行中的执行。三个接口构成一个闭环。

This differs from the node-driven SDK path documented under KYC / 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.

它与 KYC / KYB 章节记录的节点驱动 SDK 路径不同:那里客户端逐个节点提交数据,这里由平台从头到尾跑完整个已发布工作流,你只需发起并轮询。

Flow Overview流程概览

Submit发起 → ↻ Poll until caseStatus is terminal↻ 轮询直到 caseStatus 达到终态 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.

workflow.apply.query 位于这个循环之前,作为恢复路径:当一次 submit 可能已经发生过(超时或上游重试)时先调用它,避免重复提交。

Billing计费

API Purpose用途 Billed计费
workflow.apply.submit Start a workflow execution发起工作流执行 Yes — charged per eventType是 — 按 eventType 扣对应额度
workflow.execution.status Read execution status + Case decision by executionId按 executionId 查执行状态与 Case 结论 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 for the base URL (Staging api-gateway-platform.width.com/gateway / Production api-gateway.width.com/gateway) and request format, and Authentication for the full signing rules. 三个接口与其余 OpenAPI 接口共用同一网关基础地址、同一套 query-string 请求信封(api / apiVersion / apiKey / sign)加 x-domain 请求头,以及同样的请求体 HMAC-SHA256 签名。基础地址(Staging api-gateway-platform.width.com/gateway / 生产 api-gateway.width.com/gateway)与请求格式见 OpenAPI 参考 → 快速入门,完整签名规则见 身份验证 章节。

Submit a Workflow发起工作流

Endpoint:接口: workflow.apply.submit POST

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

按 eventType + source 路由到当前已发布(PUBLISHED)的工作流并发起执行。

apiVersionapiVersion 版本

apiVersion Behaviour说明
1.0.0 Auto-routes by eventType + source按 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.在 1.0.0 基础上支持可选 workflowId,显式指定要执行的已发布工作流;workflowId 为空时行为与 1.0.0 完全一致。推荐使用。

Request请求

{
  "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; it appears as Manual in the Console.事件类型:KYC_EVENT / KYB_EVENT / TRANSACTION_EVENT / WEB3_TRANSACTION_EVENT / MANUAL_CASE_EVENT,以租户开通的事件为准。前两项在平台界面上显示为 KYC 和 KYB,那是界面显示名;接口里要传 KYC_EVENT 和 KYB_EVENT。MANUAL_CASE_EVENT 用于把主体提交做名单筛查,在平台界面上显示为 人工。
source string Yes是 Origin. Server-side integrations always send API.来源。服务端对接固定填 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.业务数据。customerId 必填且必须对同一客户保持稳定(workflow.apply.query 依赖它做恢复查询);其余字段依工作流入口事件的字段定义。
workflowId string No否 2.0.0 only. Names a published workflow; empty means auto-route by event.仅 2.0.0。指定已发布工作流 ID;为空则按事件自动路由。

Response响应

{
  "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.执行实例 ID。请务必持久化 — 后续用它轮询 workflow.execution.status。
status string Initial status (EXECUTING / SUBMITTED).初始状态(EXECUTING / SUBMITTED)。
sync boolean Whether the execution ran synchronously; in sync mode the output carries the decision directly.是否同步执行;同步模式下 output 直接携带决策结果。
code int 200 = OK; 403 = quota exhausted (billing blocked).200 = 正常;403 = 额度不足(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. 额度 — submit 是唯一计费的接口。data.code 返回 403 表示该 eventType 的额度已用尽;不要盲目重试 — 请联系管理员充值或调整额度。

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.

只读接口 — 不触发执行、不计费。executionId 按租户(及 x-domain)校验归属,无法跨租户查询。使用 apiVersion 1.0.0。

Request请求

{ "executionId": "exec-7208f03b931e4897" }
Field字段 Type类型 Required必填 Description描述
executionId string Yes是 The execution instance ID returned by workflow.apply.submit.workflow.apply.submit 返回的执行实例 ID。

Response响应

{
  "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.执行状态:RUNNING / WAITING / COMPLETED / FAILED / CANCELED。
caseNo string Associated Case number (C%06d); empty until a Case is generated.关联 Case 编号(C%06d);尚未生成 Case 时为空。
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.Case 处理状态:UNASSIGNED(队列待分配)/ UNDER_REVIEW(审核员处理中)/ RETURNED(退回重做)/ OTHER_GROUP(本组已处理完,流程仍在其他组/节点进行)/ APPROVED / REJECTED / CLOSED(已完成,流程结束);无 Case 时为空。轮询退出条件依据此字段。
riskScore number Risk score (0–100); empty if none.风险评分(0–100);无则为空。
resolvedAt long Resolution time (epoch millis); empty until resolved.结案时间(epoch 毫秒);未结案为空。
currentNode etc.currentNode 等 object SDK flow-control internals (currentNode / output / pendingCallbackTask); ignore them for server-side integration.SDK 流程控制用的内部字段(currentNode / output / pendingCallbackTask),服务端集成请忽略。
An empty data string means the executionId does not exist, or belongs to a different tenant/domain than the current apiKey. data 为空字符串时,表示 executionId 不存在,或不属于当前 apiKey 所在的租户/domain。

Status Semantics状态语义

status caseStatus Meaning含义
RUNNING / WAITING empty空 Executing (including waiting on data collection); no Case yet.执行中(含等待信息采集),尚未生成 Case。
RUNNING / WAITING UNASSIGNED / UNDER_REVIEW / RETURNED Stopped at a review node awaiting manual handling — keep polling.执行停在 review 节点等待人工处理 — 继续轮询。
RUNNING / WAITING OTHER_GROUP The current Case’s group is done; the flow continues in another group/node — keep polling.当前 Case 所在组已处理完,流程仍在其他组/节点进行 — 继续轮询。
COMPLETED / CANCELED APPROVED / REJECTED / CLOSED Decision reached, flow finished.已出结论,流程结束。
FAILED — Execution failed; contact support with the executionId.执行失败,请联系支持并提供 executionId。

Response by Stage各阶段响应示例

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

阶段 1 — 自动节点执行中,Case 尚未生成(到达决策节点前的短暂窗口):

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

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

无 caseStatus 字段 → 尚未生成 Case,继续轮询。

Stage 2 — Case generated, awaiting manual handling:

阶段 2 — Case 已生成,等待人工处理:

{ "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.

人工处理期间 caseStatus 反映进度:UNASSIGNED(队列待分配)→ UNDER_REVIEW(审核员领取后);退回重做时为 RETURNED。

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

阶段 3 — 已出结论(人工审核或自动决策):

{ "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). 多审核组流程中,当前 Case 处理完后若整体流程仍在其他组/节点进行,caseStatus 为 OTHER_GROUP — 请继续轮询至 caseStatus 变为终态(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:

每次执行到达决策节点后都会生成 Case(人工审核 → UNASSIGNED / UNDER_REVIEW;自动通过/拒绝/关闭 → 直接产生终态 Case),因此:

# 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. 轮询节奏 — 间隔 3–5 秒;进入人工处理阶段(caseStatus ∈ {UNASSIGNED, UNDER_REVIEW, RETURNED})可放宽至 30–60 秒。

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.

按 eventType + source + customerId 查询该客户是否已有执行。只读 — 不触发新执行、不计费。使用 apiVersion 1.0.0。

Request请求

{
  "eventType": "KYC_EVENT",
  "source": "API",
  "customerId": "demo-customer-001"
}
Field字段 Type类型 Required必填 Description描述
eventType string Yes是 Same as at submit time.与 submit 时一致。
source string Yes是 Same as at submit time.与 submit 时一致。
customerId string Yes是 Same as data.customerId at submit time (must stay stable for the same customer).与 submit 时 data.customerId 一致(必须对同一客户保持稳定)。

Response响应

{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "executionId": "exec-7208f03b931e4897",
    "status": "RUNNING"
  }
}
Match命中情况 executionId status Suggested action建议动作
Customer already approved客户已审批通过 most recent COMPLETED execution最近一次 COMPLETED 执行 APPROVED Do not submit again.不要重复提交。
An execution is in flight存在进行中的执行 that execution该执行 RUNNING Switch to polling workflow.execution.status.转轮询 workflow.execution.status。
No match (rejected or no record)未命中(被拒/无记录) empty空 — Call submit normally.可正常调用 submit。
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. customerId 稳定性 — customerId 必须与 submit 时 data.customerId 完全一致,且对同一客户长期稳定;否则恢复查询无法命中。

Error Codes错误码

Layer层级 Code码 Meaning说明 Action处理建议
Gateway apiCode网关 apiCode 200 Success (check data.code for the business result)成功(业务结果看 data.code) —
Gateway apiCode网关 apiCode 999302 API name errorAPI 名称错误 Check api / apiVersion检查 api / apiVersion
Gateway apiCode网关 apiCode 999305 apiKey invalid or disabledapiKey 无效或已停用 Verify the API Key on the API & Integration page核对 API & Integration 页面的 API Key
Gateway apiCode网关 apiCode 999001 Signature error签名错误 Check the sign computation (sign the raw body, no extra newlines)检查 sign 计算(body 原文签名、无多余换行)
Gateway apiCode网关 apiCode 999401 Service timeout服务超时 Retry later; contact support if it persists稍后重试;持续出现请联系支持
data.code 400 Missing parameter参数缺失 Check the request body检查请求 body
data.code 403 Quota exhausted (submit only)额度不足(仅 submit) Ask an admin to top up / adjust the quota联系管理员充值/调整额度
empty datadata 为空 — Execution does not exist or belongs to another tenant/domain (status only)execution 不存在或不属于当前租户/domain(仅 status) Verify executionId against your apiKey / x-domain; always send the required x-domain header核对 executionId 与 apiKey / x-domain;x-domain 为必填 header,请始终显式携带

Code Example代码示例

curl (full loop)curl(完整闭环)

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常见问题

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:submit 超时了,不确定是否已发起,怎么办?
不要直接重试 submit(会重复计费)。先调 workflow.apply.query:命中 RUNNING / APPROVED 则拿回 executionId 继续轮询;未命中再重新 submit。
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:status 查不到刚提交的 execution(data 为空)?
确认与提交时使用同一个 apiKey 与 x-domain——接口按租户和 domain 校验归属,跨 domain 查询返回空 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.
Q:执行长时间停在 RUNNING / WAITING 是异常吗?
不一定。停在 review 节点等待人工处理时执行状态不会变为终态,此时 caseStatus 为 UNASSIGNED / UNDER_REVIEW / RETURNED。以 caseStatus 判断处理进度。

KYC OnboardingKYC 个人客户入驻

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

个人客户入驻的多步骤工作流。使用 eventType: "KYC_EVENT"。

Flow Overview流程概览

Register Customer注册客户 → Start Workflow启动工作流 → ↻ Repeat per node until status = COMPLETED↻ 逐个节点重复,直到 status = COMPLETED Poll Status轮询状态 → Submit Node Data提交节点数据 status = COMPLETED→ Get Final Decision获取最终结论

Step 1 — Register Customer步骤 1 — 注册客户

Endpoint:接口: workflow.applicant.register POST

{
  "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. customerId 和 email 至少需传一个。此接口幂等 — 重复调用将返回已有客户。

Response:

响应:

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

Step 2 — Start Workflow步骤 2 — 启动工作流

Endpoint:接口: workflow.apply.submit POST

{
  "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 and Status & Case Decision.

保存返回的 executionId — 后续所有接口调用均需使用。关于 apiVersion 2.0.0 与本工作流共用的 Case 结论字段(caseStatus / riskScore),见 工作流生命周期 API → 发起 与 查询状态与审核结论。

Step 3 — Poll Status步骤 3 — 轮询状态

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. 启动工作流后约等待 2 秒再首次轮询,系统需要短暂时间初始化节点。
{
  "executionId": "exec-abc123def456"
}
Status Meaning含义 Action处理方式
RUNNING Executing, no node waiting执行中,尚无节点等待 Continue polling (2–5 sec)继续轮询 (2–5 秒)
WAITING Node waiting for input节点等待输入 Read currentNode and submit data读取 currentNode 并提交数据
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:

当 status = WAITING 时的关键字段:

Step 4 — Submit Node Data步骤 4 — 提交节点数据

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.

每次提交响应都包含 nextStep 对象,可直接使用以进入下一步 — 无需每次提交间轮询。仅在恢复会话或等待最终结果时轮询。

Step 5 — Internal Processing & Completion步骤 5 — 内部处理与完成

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.

最后一个用户输入节点完成后,响应中不再包含 nextStep,表示工作流已进入自动处理阶段(筛查、规则评估、决策)。后端应轮询 workflow.execution.status 直至终态。

Status Meaning含义
COMPLETED Workflow finished. Decision is recorded and visible in Admin Console.工作流已完成,决策已记录并可在管理控制台查看。
WAITING Flagged for manual review. Will transition to COMPLETED after review.标记为人工审核,审核完成后转为 COMPLETED。
FAILED Execution failed. Contact support.执行失败,联系技术支持。
TIMEOUT Exceeded configured time limit.超出配置的时间限制。
CANCELLED Cancelled via workflow.execution.cancel.已通过 workflow.execution.cancel 取消。

Cancel Execution取消执行

Endpoint:接口: workflow.execution.cancel POST

{
  "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.

若流程中断,使用已保存的 executionId 调用 workflow.execution.status,即可从上一个待处理节点恢复。数据不会丢失。


KYC Node API ReferenceKYC 节点 API 参考

Typical node sequence:

典型节点顺序:

OCR身份证件 OCR → Particular个人信息 → Liveness活体检测 → Email/Phone OTP邮箱 / 手机 OTP → Required Documents必传文件 → Required Forms必填表单 → [Screen Check][AML/制裁筛查] → Decision决策

Nodes in brackets are automatic — no client action needed.

方括号中的节点为自动执行 — 无需客户端操作。

KYC Node Routing TableKYC 节点路由表

nodeType API Description描述
flow_action_identity_document workflow.kyc.ocr → workflow.kyc.ocr.data Upload document images, retrieve OCR results上传证件图片,获取 OCR 结果
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提交 PASS 状态及客户照片
flow_action_validate_email workflow.kyc.otp.send + workflow.kyc.otp.verify Email verification via OTP邮箱 OTP 验证
flow_action_validate_phone workflow.kyc.otp.send + workflow.kyc.otp.verify Phone verification via OTP手机 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 neededAML/制裁筛查 — 无需操作

Identity Document (OCR)身份证件 (OCR)

Two-step: submit images, then poll results.

两步操作: 先提交图片,再轮询结果。

Step 1 — Submit:步骤 1 — 提交: workflow.kyc.ocr POST

Parameter参数 Type类型 Required必填 Description描述
provider String Yes是 WIDTH / REGULA / VERIFF
frontImage String Yes是 S3 URI of document front image证件正面图片的 S3 URI
backImage String No否 S3 URI of document back image证件背面图片的 S3 URI
documentType String Yes是 NATIONAL_ID / INTERNATIONAL_PASSPORT / DRIVING_LICENCE / RESIDENCE_PERMIT
region String Yes是 ISO 2-letter country codeISO 双字母国家代码
executionId String Yes是 Execution ID
callbackKey String Yes是 From currentNode.callbackKey取自 currentNode.callbackKey
referenceId String Yes是 Your tracking ID您的追踪 ID
includeDocverCheck Boolean No否 Enable document verification启用证件真伪验证
Upload images first via the File Upload API to obtain S3 URIs. 需先通过文件上传接口上传图片以获取 S3 URI。

Step 2 — Poll Results:步骤 2 — 轮询结果: workflow.kyc.ocr.data POST

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

2–5 秒后轮询。OCR 通常在 5–15 秒内完成。

Particular

Endpoint:接口: workflow.kyc.particular.data POST

{
  "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. 注意: personData 是一个 JSON 编码的字符串,而非嵌套对象。必须先 JSON.stringify() 再放入请求体。

Liveness

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

在 OpenAPI 模式下,活体检测是数据提交步骤而非交互式检测。提交 status: "PASS" 及客户照片即可。

Endpoint:接口: workflow.kyc.liveness.data POST

{
  "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 first. scores 和 images 均为 JSON 字符串。需先通过文件上传接口上传照片。

Email / Phone OTP邮箱 / 手机 OTP

Step 1 — Send:步骤 1 — 发送: workflow.kyc.otp.send POST

{
  "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. 手机 OTP 时设置 "type": "phone",identity 使用 E.164 格式(如 +6581234567)。保存返回的 requestId 用于验证步骤。

Step 2 — Verify:步骤 2 — 验证: workflow.kyc.otp.verify POST

{
  "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必传文件

Endpoint:接口: workflow.kyc.required.doc POST

{
  "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.

上传完所有文件后,调用 workflow.kyc.required.doc.submit 推进工作流。

For optional documents, use workflow.kyc.non.required.doc with the same schema. Call .submit to advance (even if skipping). 可选文件使用 workflow.kyc.non.required.doc,请求体结构相同。即使跳过也需调用 .submit 以推进。

Required Forms必填表单

Endpoint:接口: workflow.kyc.required.form POST

{
  "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.

提交所有表单后,调用 workflow.kyc.required.form.submit。


KYB OnboardingKYB 企业客户入驻

Corporate customer onboarding. Use eventType: "KYB_EVENT".

企业客户入驻流程。使用 eventType: "KYB_EVENT"。

Flow Overview流程概览

Corporate Particular公司信息 → CRP Collector关联方采集 → Required Documents (main + CRPs)必传文件(主体 + 关联方) → Non-Required Documents选传文件 → Required Forms (main + CRPs)必填表单(主体 + 关联方) → [Screen Check][AML/制裁筛查] → Decision决策

KYB Node Routing TableKYB 节点路由表

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提交董事、股东、UBO
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

Endpoint:接口: workflow.kyb.particular.data POST

{
  "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. corporateData 是 JSON 编码的字符串,与 KYC 中的 personData 格式一致。

CRP Collector关联方采集

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

企业信息提交后,采集关联方(Connected Related Parties): 董事、股东、最终受益人 (UBO)。

CRP Metadata关联方元数据

The nextStep.metadata specifies required roles:

nextStep.metadata 指定需填充的角色:

{
  "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

{
  "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.

保存返回的 crpPid — 后续此关联方的活体检测、文件和表单提交均需使用。

Submit Individual CRP Liveness提交个人关联方活体检测

Endpoint:接口: workflow.kyb.crp.ind.liveness POST

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

与 KYC 活体检测格式相同,额外传入 crpPid 字段:

{
  "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

{
  "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

{
  "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. 必须调用 crp.submit 以推进工作流。仅提交各关联方不会触发流程流转。

KYB Required DocumentsKYB 必传文件

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.

为主体(crpPid: "")和各关联方(crpPid: "acc45...")上传文件。doc 字段结构与 KYC 相同。完成后调用 workflow.kyb.corp.required.doc.submit。

Main entity document:

主体文件:

{
  "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):

个人关联方文件(双面):

{
  "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 DocumentsKYB 可选文件

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

请求体与必传文件相同。使用 workflow.kyb.corp.non.required.doc 上传。无论是否上传,均需调用 workflow.kyb.corp.non.required.doc.submit 以推进。

KYB Required FormsKYB 必填表单

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:

主体表单:

{
  "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:

个人关联方表单:

{
  "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.

提交所有表单(主体 + 各关联方)后,调用 workflow.kyb.corp.required.form.submit。


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.

生成一条一次性网页链接,终端用户点开就进入托管的 KYC 或 KYB 流程。链接怎么送到用户手里由你决定——邮件、聊天工具、任何现有渠道都行,用户在浏览器里把资料填完。如果你自己没有网站或 App 可以嵌 SDK,就走这条路。

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

使用 apiVersion 1.0.0。签名方式、网关地址和 x-domain 请求头与其他 OpenAPI 接口完全一致(见身份验证)。

Request请求

{
  "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)你的内部用户 ID(对同一客户保持稳定)
eventType string Yes是 Which flow the link opens: KYC_EVENT (individual) or KYB_EVENT (corporate)链接打开哪一类流程:KYC_EVENT(个人)或 KYB_EVENT(企业)

Response响应

{
  "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.要交给终端用户的链接。查询参数 linkToken 标识这一次邀请——整条 URL 视同密钥,只发给你在 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.失效时刻,毫秒时间戳。链接自生成起 7 天 内有效;过期后再调一次本接口换一条新的。
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. 同一个邮箱同一时间只有一条链接是活的。用同一个 email 再调一次本接口,前一条立刻作废——终端用户手里那条当场就打不开了,而且没有任何办法恢复。所以重新签发之前先确认对方没在填;如果他正填到一半,把新链接补发给他。用不同邮箱签出来的链接互不影响。

Errors错误处理

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

eventType 填了不支持的值时,错误信息在 data 里,网关层的 apiCode 仍然是 200 — 判断成败要读 data.code,不是 HTTP 状态码:

{
  "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. 本接口只服务身份核验。交易类与 Web3 类事件没有可跳转的托管网页流程,请改用 workflow.apply.submit 提交。

Transaction Screening交易筛查

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

提交交易数据进行 AML 风险评估。使用 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. TRANSACTION_EVENT 用于法币交易筛查(银行转账、支付等链下交易)。如需筛查区块链钱包地址或链上交易,请改用 WEB3_TRANSACTION_EVENT,见 Web3 交易筛查。

Endpoint:接口: workflow.apply.submit POST

Request请求

{
  "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.

立即返回 executionId。轮询 workflow.execution.status 获取最终结果 — caseStatus / riskScore 的读法见 工作流生命周期 API → 查询状态与审核结论。

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

Blocking Response (Sync)同步响应

Waits for workflow completion and returns the decision inline:

等待工作流完成后内联返回决策结果:

{
  "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 = errorCOMPLETED = 已决策, TIMEOUT = 超时, FAILED = 错误
durationMs Processing time in milliseconds处理耗时(毫秒)
output.action approve / reject / review
output.code Decision code (defaults: approve=100000, reject=100010; configurable)决策码(默认: approve=100000, reject=100010; 可配置)

Web3 Transaction ScreeningWeb3 交易筛查

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

提交一笔 Web3(链上)交易事件,基于钱包地址(walletAddress)或交易哈希(txHash)进行区块链 KYT(Know Your Transaction,交易/地址风险筛查)筛查 — 二者至少传一个,也可同时传,响应中返回筛查结果与决策。使用 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. Web3 筛查与其余 OpenAPI 接口共用同一网关基础地址、同一套 query-string 请求信封(api / apiVersion / apiKey / sign)加 x-domain 请求头,以及同样的请求体 HMAC-SHA256 签名。基础地址与请求格式见 OpenAPI 参考 → 快速入门,完整签名规则见身份验证章节。
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. 请求中不需要传工作流 ID。租户下只有一个已发布的 Web3 工作流时,平台会把事件自动路由到该工作流。若租户发布了多个 Web3 工作流,请在对接前联系 Width 支持,确认适用于您租户的调用方式。
After submitting, poll workflow.execution.status and read the Case decision (caseStatus / riskScore) as described in Workflow Lifecycle API → Status & Case Decision. 提交后轮询 workflow.execution.status,Case 结论(caseStatus / riskScore)的读法见 工作流生命周期 API → 查询状态与审核结论。

Request请求

Variant 1 — walletAddress only方式一 — 只传 walletAddress

{
  "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方式二 — 只传 txHash

{
  "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方式三 — 同时传 walletAddress 与 txHash

{
  "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固定值:WEB3_TRANSACTION_EVENT
source String Yes是 Fixed value: API固定值:API
data Object Yes是 Transaction data (see below)交易数据(见下)

data Fieldsdata 字段

Field字段 Type类型 Required必填 Description说明
chain String Yes是 Chain identifier, e.g. TRON, ETH, BTC, BSC, POLYGON链标识,如 TRON、ETH、BTC、BSC、POLYGON
token String Yes是 Token symbol, e.g. USDC, USDT, ETH, BTC代币符号,如 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您系统中标识本次交易的 ID,用于审计追踪
customerId String No否 The ID that identifies the customer in your system您系统中标识客户的 ID
amount Number No否 Transaction amount (denominated in transactionCurrencyId)交易金额(按 transactionCurrencyId 计价)
transactionCurrencyId String No否 Currency code (e.g. USDC, USDT, USD)货币代码(如 USDC、USDT、USD)
Constraints约束

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:

接口同步返回。HTTP 200 + apiCode: 200 才表示请求被受理;HTTP 4xx/5xx 表示请求未被网关受理,响应体不会包含 data。请求被受理后,业务结果由 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.messageKYT 筛查未完成,原因见 data.output.data.message Does not indicate a risk hit不代表命中风险

Two core fields in the response:

响应中两个核心字段:

Approve (100000)通过(100000)

{
  "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)命中(100001)

{
  "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)KYT 筛查未完成(100002)

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

kytScreenResults 为空数组,data.output.data.message 给出未完成原因(仅在此场景下出现)。

{
  "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.网关层返回码,200 表示请求被受理;其他值见 OpenAPI 参考的错误码表。
apiMsg String Gateway-layer message网关层返回信息
data.executionId String Unique ID of the workflow execution instance工作流执行实例的唯一 ID
data.requestId String Trace ID for this single request单次请求的链路追踪 ID
data.sync Boolean Whether the response is synchronous; always true for this endpoint是否为同步响应,本接口固定 true
data.status String Workflow execution status; COMPLETED on normal completion工作流执行状态,正常完成为 COMPLETED
data.output.action String Decision: approve / reject (note: reject does not necessarily mean a risk hit — see the business-code table above)决策结果:approve / reject(注意 reject 不一定代表命中,详见上文业务码对照表)
data.output.code Number Business code; see the table above (100000 / 100001 / 100002)业务码,见上文对照表(100000 / 100001 / 100002)
data.output.data.message String Returned only when code = 100002; explains why KYT screening did not complete仅当 code = 100002 时返回,说明 KYT 筛查未完成的原因
data.output.data.kytScreenResults Array KYT on-chain screening results; length rule as above (empty array when code = 100002)KYT 链上筛查结果,长度规则见上文(code = 100002 时为空数组)

kytScreenResults[] fieldskytScreenResults[] 字段

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)被筛查的钱包地址(同时传 walletAddress + txHash 时,每条记录的地址不同,请以此字段区分)
chain_name String Chain identifier, matching data.chain in the request链标识,对应请求中的 data.chain
risk_level String Risk level, e.g. low, critical风险等级,如 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.

所有示例都遵循同一原则:先把请求 body 序列化成字符串,再对这个字符串计算签名,然后把同一个字符串作为 HTTP body 发出去。示例 body 对应方式一(只传 walletAddress);如需按方式二或方式三调用,只需替换 body 中的 walletAddress / txHash 字段,其余代码逻辑不变。

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:

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:

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. 网关层错误码(apiCode,9999xx 系列)在 OpenAPI 参考 → 错误码统一列出,适用于所有接口;业务层结果码(data.output.code,10000x 系列)是本接口专属,见上文 响应 顶部的对照表。

FAQ常见问题

Q: My signature keeps failing — what should I check first?Q:签名总是不通过,应该先查什么?

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.

A:99% 的 SIGN_ERROR 都是因为「签名用的 body 字节」与「实际发送的 body 字节」不一致。请确保:构造 JSON 字符串 → 对它计算签名 → 把同一个字符串作为 HTTP body 发送。签名与发送之间不要 pretty-print、不要再调一次序列化、不要补尾部换行。

Q: Must the request body be minified (whitespace stripped)?Q:请求 body 必须压缩(去空格)吗?

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.

A:不需要。body 里可以保留任意换行/缩进,只要您签名时用的字节与发送时用的字节完全相同即可。

Q: Can I screen an address before the transaction is broadcast on-chain (pre-transaction screening)?Q:交易还没上链,能先筛查这个地址有没有风险吗?

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.

A:可以。使用方式一 — 只传 walletAddress、不传 txHash。筛查以地址本身为对象,不要求交易已经上链:可先筛查对手方地址,再决定是否发起转账。


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

把一个待筛查主体(个人或企业)送进平台做名单筛查。平台会按客户号建档,在你的工作流里跑完筛查,命中就产生告警并开一个案件交给分析员裁定。使用 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 instead. 筛一个名字有两条路,用途不同。本接口是留痕的那条:主体会落成客户档案,命中变成告警,分析员的裁定结论会被记住,同一个 customerId 下次再来时直接复用。如果只想临时查一下、不建客户也不开案件,请改用Quick Scan 一次性筛查。

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.

POST 到网关,query string 照常带 api=workflow.apply.submit、apiVersion=2.0.0、apiKey 和 sign,再加上装着你的 domain ID 的 x-domain 请求头。请求体是 UTF-8 编码的 JSON,Content-Type: application/json;sign 是对 实际发出去的那份字节做 HMAC-SHA256 ——先把请求体序列化成字节,对这份字节签名,再把同一份字节发出去,别让框架在签完之后又重新序列化一遍。完整规则和各语言代码见身份验证。

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 instead of resending blind. How the quota is actually drawn down is whatever the Admin Console → Billing usage page reports (see 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. 筛查会消耗第三方名单筛查供应商的配额,所以每一次提交都当成花钱的动作来对待:调用前先去重;万一调用超时,先用workflow.apply.query查上一次提交跑到哪一步了,别直接重发。额度到底怎么扣,以 Admin Console → Billing 用量页上的数字为准(见用量与配额),别照自己的理解推算;正式放量接入之前,先小批量跑一两笔,比一比那一页跑前跑后的差值。

Request请求

{
  "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.固定填 MANUAL_CASE_EVENT。该事件在平台界面上显示为 人工。
source string Yes是 Fixed value API for server-side integrations.服务端对接固定填 API。
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.这次筛查跑哪条工作流。工作流 ID 在平台的工作流列表里取。不传也能跑——平台会自动路由到最新发布的那条——但名单筛查这个场景请把工作流写明,免得别人后来发布了新版本,你的提交在你不知情的情况下换了流程。
data object Yes是 The subject being screened. Fields go at the top level of data, not nested deeper.被筛查的主体。字段直接放在 data 的第一层,不要再往下嵌。

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.主体的其它名字,比如原文名(中文名等)。每个名字都会单独跑一遍筛查,原文名对命中准确性帮助显著。多个名字用英文逗号分隔——也就是说别名本身不能带逗号:写成 Chen, Dawei 会被当成两个名字,请写 Chen Dawei。这条只管 aliasName;name 不会被拆。
customerType Yes是 individual for a person, corporate for a company.个人填 individual,企业填 corporate。
sex Recommended (person)建议(个人) Sex. F / M or the English word in full.性别。F / M 或英文全称都可以。
dateOfBirth Recommended (person)建议(个人) Date of birth. A full date (1966-03-15) or the year alone (1966) both work.出生日期。完整日期(1966-03-15)或只给年份(1966)都可以。
countryOfNationality Recommended (person)建议(个人) Nationality. ISO 3166 two-letter or three-letter codes are both accepted; the platform normalises them.国籍。ISO 3166 两位或三位码均可,平台自动归一。
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.注册国。未传时以 countryOfResidence 兜底。
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.

个人的 sex、dateOfBirth、countryOfNationality 和企业的 countryOfIncorporation、incorporationNumber 会作为佐证参与比对与降分排序:传得越全,同名噪音越少。字段缺失时按中性处理,不会误伤主体。

Response响应

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

本接口是异步的:提交被接受即返回,筛查在平台侧继续跑。

{
  "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 takes to poll the outcome.本次执行的编号。请留存:向平台方问进度或排查问题时用它,用workflow.execution.status轮询结果时也传它。
data.status RUNNING on a successful submission. The screening result and risk score end up on the case page in the Console.提交成功时为 RUNNING。筛查结果与风险评分最终体现在平台的案件页上。

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.

提交失败时返回网关标准错误结构。常见原因是签名与实际发出的字节不一致、缺 x-domain 请求头、请求体不是合法 JSON、必填字段缺失。

Examples完整示例

Individual subject:个人主体:

{
  "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:企业主体:

{
  "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 APIQuick Scan 一次性筛查

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 提供一次性合规筛查能力,无需创建客户或配置工作流。提交一个姓名,系统会同时调用多个筛查引擎(World-Check、Dow Jones、ArtemiScan、互联网搜索、内部监控名单),返回命中结果,适合做临时的制裁 / PEP(Politically Exposed Person,政治公众人物)姓名核查。

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. Quick Scan 与其余 OpenAPI 接口共用同一网关基础地址、同一套 query-string 请求信封(api / apiVersion / apiKey / sign)加 x-domain 请求头,以及同样的请求体 HMAC-SHA256 签名。基础地址与请求格式见 OpenAPI 参考 → 快速入门,完整签名规则见身份验证章节。

Flow调用流程

  1. quickscan.submit — submit a screening; returns an id immediately (asynchronous)提交筛查,立即返回 id(异步执行)
  2. quickscan.detail — poll for status; on DONE it returns the hit summary轮询状态,DONE 时返回命中摘要
  3. quickscan.hits — fetch full hit details per provider, paginated (optional)按引擎分页获取完整命中详情(可选)

Endpoints接口列表

API NameAPI 名称 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 Screeningquickscan.submit — 提交筛查

Request请求

{
  "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 Fieldsdata 字段

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)"Individual" 或 "Business"(也兼容整数 1 / 2)
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)可选引擎(providers)

Engine引擎 Description说明 Consumes Credit消耗 Credit
WORLD_CHECK Refinitiv World-Check sanctions / PEP listsRefinitiv World-Check 制裁 / PEP 名单 Yes是
DOW_JONES Dow Jones Risk & Compliance listsDow Jones Risk & Compliance 名单 Yes是
ARTEMISCAN ArtemiScan composite risk screeningArtemiScan 综合风险筛查 Yes是
INTERNET_SEARCH Public internet information search互联网公开信息搜索 Yes是
WATCHLIST Internal watchlist (tenant-defined)内部监控名单(租户自定义) No (free)否(免费)

Engine Parameters (providerSettings)引擎参数(providerSettings)

Engine引擎 Parameter参数 Default默认值 Options可选值
artemiscan sensitivity 0.6 0–1 (higher = looser matching)0~1(越大匹配越宽松)
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响应

{
  "apiCode": 200,
  "apiMsg": "OK",
  "data": {
    "code": 200,
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "status": "RUNNING"
  }
}
Field字段 Description说明
data.id Screening record ID, used for subsequent queries筛查记录 ID,用于后续查询
data.status RUNNING (screening in progress)RUNNING(筛查进行中)

quickscan.detail — Query Resultquickscan.detail — 查询结果

Request请求

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

Response — in progress响应 — 进行中

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

Response — done, hits ≤ 50 (inlined)响应 — 完成,命中数 ≤ 50(内联返回)

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

当 totalHits ≤ 50 时,hits 字段内联返回全部命中详情:

{
  "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响应 — 完成,命中数大于 50

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

当总命中数大于 50 时,hits 为 null、truncated 为 true,需使用 quickscan.hits 分页获取详情:

{
  "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.hitstrue = 命中过多,需用 quickscan.hits 分页获取
hitCounts Object Per-engine hit counts { "WORLD_CHECK": 7, ... }各引擎命中数量 { "WORLD_CHECK": 7, ... }
hits Object / null Hit details (returned only when totalHits ≤ 50)命中详情(仅 totalHits ≤ 50 时返回)

quickscan.hits — Paginate Hit Detailsquickscan.hits — 分页获取命中详情

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.

当 quickscan.detail 返回 truncated: true 时,使用此接口按引擎分页获取命中详情。truncated: false 时也可用此接口按需获取单个引擎的结果。

Request请求

{
  "data": {
    "id": "qs-b701733c3eca438fb27b68b0ed05ad9d",
    "provider": "WORLD_CHECK",
    "page": 1,
    "pageSize": 20
  }
}
Field字段 Type类型 Required必填 Description说明
id String Yes是 Screening record ID筛查记录 ID
provider String Yes是 Engine name (WORLD_CHECK / DOW_JONES / ARTEMISCAN / INTERNET_SEARCH / WATCHLIST)引擎名称(WORLD_CHECK / DOW_JONES / ARTEMISCAN / INTERNET_SEARCH / WATCHLIST)
page Integer No否 Page number (default 1)页码(默认 1)
pageSize Integer No否 Items per page (default 20, max 100)每页条数(默认 20,最大 100)

Response响应

{
  "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)是否还有更多页(true = 还有下一页)
hits Hit details for the current page { "PROVIDER": [...] }当前页命中详情 { "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.

端到端示例:提交、轮询到 DONE,若 truncated 再分页获取。注意签名规则 — 先把请求 body 序列化成字符串,再对这个字符串计算签名,然后把同一个字符串作为 HTTP body 发出去。

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提交筛查

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查询结果

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分页获取命中

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)

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 nameAPI 名称错误
999304 RATE_LIMIT_TRY_AGAIN Rate limited触发限流
999305 TENANT_NOT_FOUND No tenant for this apiKeyapiKey 对应租户不存在

Business-layer codes (data.code)业务层错误码(data.code)

code Meaning含义
200 Success成功
400 Parameter error (missing required field, invalid provider, etc.)参数错误(缺少必填字段、provider 无效等)
403 Insufficient CreditCredit 额度不足
404 Screening record not found筛查记录不存在
500 Internal server error服务内部错误

FAQ常见问题

Q: How long until I get a result?Q:提交后多久能拿到结果?

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.

A:通常 3~10 秒。World-Check 和 Dow Jones 一般 2~5 秒返回,互联网搜索可能稍慢。建议每 3 秒轮询一次 quickscan.detail。

Q: What does truncated: true mean?Q:truncated: true 是什么意思?

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.

A:当总命中数超过 50 条时,quickscan.detail 不会在响应中内联全部命中详情(避免响应体过大)。此时 hits 为 null,需通过 quickscan.hits 按引擎分页获取。

Q: How much Credit does each scan consume?Q:每次筛查消耗多少 Credit?

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

A:每个引擎消耗 1 个 Credit(WATCHLIST 免费)。例如选择 3 个引擎 = 消耗 3 个 Credit。

Q: What does customerType affect?Q:customerType 有什么影响?

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.

A:"Individual" 和 "Business" 决定了筛查引擎的匹配策略。Business 类型会额外匹配公司名称、注册号等字段。也兼容整数 1(Individual)/ 2(Business)。

Q: My signature keeps failing.Q:签名总是不通过?

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.

A:确保签名时用的 body 字节与实际发送的完全一致。一次性构造 JSON 字符串 → 签名 → 发送同一个字符串。不要 pretty-print,不要再次序列化。

Q: Can I submit multiple screenings at once?Q:可以同时提交多个筛查吗?

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

A:可以。每次 quickscan.submit 调用都是独立的,各自返回不同的 id。可并行提交,独立轮询结果。


Continuous Monitoring持续监控

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

对存量客户的异步持续审查。始终为异步模式。使用 eventType: "PERIODIC_FLOW_EVENT"。

Endpoint:接口: workflow.apply.submit POST

Request请求

{
  "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.

立即返回 executionId。轮询 workflow.execution.status 直至终态;Case 结论(caseStatus / riskScore)的读法见 工作流生命周期 API → 查询状态与审核结论。

{
  "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 formatE.164 格式
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-letterISO 双字母
countryOfResidence String ISO 2-letterISO 双字母
countryOfBirth String ISO 2-letterISO 双字母
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取自配置 avira_entity_types
incorporationNumber String Corporate only仅企业
incorporationDate String YYYY-MM-DD, corporate onlyYYYY-MM-DD, 仅企业
incorporationExpiry String YYYY-MM-DD, corporate onlyYYYY-MM-DD, 仅企业
countryOfIncorporation String ISO 2-letter, corporate onlyISO 双字母, 仅企业
countryOfOperations String ISO 2-letter, corporate onlyISO 双字母, 仅企业
imoNumber String IMO number for shipping entities航运实体的 IMO 编号
isIncorporated Boolean Whether entity is incorporated是否已注册
isRegulatedEntity Boolean Whether entity is regulated是否受监管
ownershipStructureLayer String From config ownership_structure_layer取自配置 ownership_structure_layer
industry String From config avira_ssic取自配置 avira_ssic
occupation String From config avira_ssoc取自配置 avira_ssoc
website String Company website URL公司网站 URL
onboardingMode String ONLINE / OFFLINE
paymentMode String BANK_TRANSFER / CASH
productComplexity String From config product_service_complexity取自配置 product_service_complexity
bankAccounts String Associated bank account info关联银行账户信息
transactionBehaviour String From config transaction_behaviour取自配置 transaction_behaviour
riskLevel String LOW / MEDIUM / HIGH
startTime Long Epoch ms — current review startEpoch 毫秒 — 本次审查开始时间
customerCategory String RETAIL / CORPORATE
lastStartTime Long Epoch ms — previous review startEpoch 毫秒 — 上次审查开始时间

File Upload文件上传

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

需要 S3 URI 的接口(证件、照片等),需先通过此接口上传文件。

Step 1 — Get Upload Token步骤 1 — 获取上传令牌

Endpoint:接口: storage.upload.token POST

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

请求体: {}。令牌有效期 15 分钟。

Response:

响应:

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

Step 2 — Upload File步骤 2 — 上传文件

Storage Service URL:

存储服务地址:

Environment环境 URL
Staging https://api-gateway-platform.width.com/storage
Production https://api-gateway.width.com/storage

Multipart upload:

Multipart 上传:

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

Base64 upload:

Base64 上传:

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:

响应:

{
  "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. S3 URI 是内部引用,非公开可访问的 URL,请勿直接通过此 URI 下载文件。
Supported types: PNG, JPG, JPEG, GIF, WEBP, TIFF, PDF — Max size: 20 MB 支持格式: PNG, JPG, JPEG, GIF, WEBP, TIFF, PDF — 大小限制: 20 MB
Token expired (HTTP 401)? Obtain a new token and retry the upload. 令牌过期 (HTTP 401)? 重新获取令牌后重试上传。

Error Handling & Retry Strategy错误处理与重试策略

Scenario场景 Recommendation建议
Signature errors (403)签名错误 (403) Do not retry. Fix signing implementation.不要重试。修复签名实现。
Server errors (500)服务端错误 (500) Retry up to 3 times with exponential backoff (1s → 2s → 4s)最多重试 3 次,指数退避 (1s → 2s → 4s)
Status polling状态轮询 Every 2–5 seconds, max 30 minutes每 2–5 秒,最长 30 分钟
Upload token 401上传令牌 401 Get new token, retry upload once重新获取令牌,重试上传一次
OTP verify failOTP 验证失败 Resend OTP if max attempts exhausted若达到最大尝试次数则重新发送 OTP
Network timeout网络超时 Safe to retry — all APIs are idempotent on callbackKey可安全重试 — 所有接口基于 callbackKey 幂等

Webhook IntegrationWebhook 集成

Webhooks let the platform call your own server from inside a workflow — the outbound counterpart to the OpenAPI pull model. This section covers configuration, request format, signature verification, retry semantics, and reference implementations.

Webhook 让平台在工作流内部回调你自己的服务器 — 与 OpenAPI 的拉取模型相对,是「推送」方向。本节涵盖配置、请求格式、签名校验、重试语义与参考实现。

Concept概念

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

平台里的 Webhook 是一份可复用的 HTTP 配置,工作流节点可以引用它发起调用。两条调用路径共用同一份配置:

Path路径 Trigger触发时机 Mode模式 Retry是否重试 Captures response是否解析响应
Webhook Action nodeWebhook 动作节点 Reached as a step in a workflow工作流执行到该节点时 Sync (workflow waits)同步(工作流等待) Configurable per node节点级可配 Yes — outputs parsed by JsonPath是 — 按 JsonPath 解析为输出
Decision Webhook hookDecision Webhook 钩子 Optional post-action on a Decision node when status settles to approve / rejectDecision 节点决策落定为 approve / reject 后的可选回调 Fire-and-forget async异步 Fire-and-forget None否 No (failure is audit-logged only)否(失败仅审计)

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

两条路径都读同一份 HttpServiceDefinition(URL、method、headers、签名等),一次配置两处可用。

Configure a Webhook (UI)在平台配置 Webhook(UI)

Path: Sidebar → Tools → Webhook → + New Webhook

路径:侧栏 → Tools → Webhook → + New Webhook

Field字段 Required是否必填 Description说明
Webhook NameWebhook 名称 yes是 Display name; referenced in node editors展示名,节点编辑器里通过此名引用
HTTP MethodHTTP 方法 yes是 POST (default) / PUT / PATCH / GET / DELETE. GET and DELETE are sent without a bodyPOST(默认)/ PUT / PATCH / GET / DELETE。GET 和 DELETE 不发送 body
Webhook URLWebhook URL yes是 Absolute URL. Supports {variable} placeholders resolved against the input map at runtime, e.g. https://api.example.com/users/{userId}绝对 URL,支持 {var} 占位符替换,运行时由 input map 提供,例如 https://api.example.com/users/{userId}
HeadersHeaders optional可选 List of {name, defaultValue}. Values support {variable} substitution{name, defaultValue} 列表;value 同样支持 {var} 占位符
InputsInputs optional可选 Declared input fields. Become the top-level keys of the JSON request body声明的输入字段,作为 JSON 请求体的顶层 key
OutputsOutputs optional可选 List of {paramName, jsonPath, paramType, defaultValue}. Extracted from the response as the node's outputs (sync path only){paramName, jsonPath, paramType, defaultValue} 列表,从响应体提取后作为节点输出(仅同步路径生效)
SignatureSignature optional可选 See Signature Verification below见下文「签名校验」

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

保存后会得到一个 Webhook ID,工作流节点编辑器通过此 ID 引用 Webhook。

Request Format请求格式

Headers请求头

Body (POST/PUT/PATCH only)请求体(仅 POST/PUT/PATCH)

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

inputs map 直接序列化成 JSON 作为 body — 声明的输入字段成为顶层 key:

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.

GET 和 DELETE 不发送 body。

Placeholder substitution占位符替换

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

Webhook URL 和 header value 支持 {var}(单大括号)替换。替换源是该次调用解析出的 inputs map。

Signature Verification签名校验

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

平台对外发请求时使用 HMAC 签名,便于接收方验证身份。

Configuration (per Webhook)配置项(每个 Webhook 独立)

Field字段 Values取值
type NONE (default) / HMAC_SHA256NONE(默认)/ HMAC_SHA256
payloadFormat TIMESTAMP_BODY (default) / BODYTIMESTAMP_BODY(默认)/ 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签名头名,默认 X-Webhook-Signature
timestampHeader Header name for the timestamp. Default X-Webhook-Timestamp时间戳头名,默认 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) )

Verification on the receiver side接收方校验流程

  1. Read the timestamp from X-Webhook-Timestamp.从 X-Webhook-Timestamp 取出时间戳;
  2. (Recommended) reject if |now - timestamp| > 5 minutes to prevent replay.(建议)若 |now - timestamp| > 5 分钟,拒绝请求(防重放);
  3. Recompute the signature using the shared secret and the raw request body.用共享 secret 重新计算签名;
  4. Compare in constant time against X-Webhook-Signature.与 X-Webhook-Signature 做等长比较(防时序攻击)。

Reference: Node.js verifier参考实现:Node.js

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)响应处理(仅 Webhook 动作节点)

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

只有同步的 Webhook 动作节点会检查响应并按 outputs 解析;Decision 钩子不解析响应。

Outcome结果 Behavior行为
2xx Success. Body is parsed against the Webhook's outputs JsonPath list; matched values become node outputs成功。按 Webhook 的 outputs JsonPath 列表解析 body,命中的字段成为节点输出
4xx Failure. Not retried by default (unless listed in retryOnStatus)失败。默认不重试(除非该状态码被显式列入 retryOnStatus)
5xx Failure. Retried up to maxAttempts with exponential backoff失败。按 maxAttempts 退避重试
Network error / timeout网络异常 / 超时 Failure. Retried up to maxAttempts with exponential backoff失败。按 maxAttempts 退避重试

Output parsing输出解析

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

对每条 outputs {paramName, jsonPath, paramType, defaultValue}:

// 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)1(不重试) Clamped to [1, 5]限制在 [1, 5] 范围
backoffMs 500 Exponential: delay = backoffMs * 2^(attempt-1)指数退避,delay = backoffMs * 2^(attempt-1)
retryOnStatus empty空 Extra HTTP status codes (typically 408, 429) to retry beyond the default 5xx + network/timeout除默认的 5xx + 网络异常 + 超时之外,额外要重试的 HTTP 状态码(常用 408、429)

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

按默认 backoffMs=500、maxAttempts=5 计算,最坏情况累计退避 ~7.5 秒(0.5s + 1s + 2s + 4s)。

Decision Webhook HookDecision Webhook 钩子

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

Decision 节点可选地在决策落地为 approve / reject 之后触发一次 Webhook 推送。此路径是 fire-and-forget:

Need response-based branching?需要根据响应分支? Use a Webhook Action node instead. 请改用 Webhook 动作节点。

Receiver Best Practices接收方实践建议

  1. Idempotency — the sync path may re-deliver on network blips; de-duplicate by executionId (or your own ID).幂等 — 同步路径在网络抖动时可能重发,请按 executionId(或您自定义 ID)去重;
  2. Respond fast — the per-attempt HTTP timeout is 10 s by default; queue long work and ACK immediately.快速响应 — 平台每次尝试的 HTTP 超时默认 10 秒,耗时操作请先排队、立即 ACK;
  3. Status code semantics — 2xx success; 4xx permanent failure (no retry); 5xx transient (retried). Returning 2xx for a logical failure is treated as success.状态码语义 — 2xx 表示成功;4xx 表示永久失败(不重试);5xx 表示瞬时失败(会重试)。给逻辑失败返 2xx 会被当成成功;
  4. Verify the signature on every request — never trust the body until the signature passes.每次都校验签名 — 验签通过前不要信任 body;
  5. Reject stale timestamps — protects against replay.拒绝过期时间戳 — 防重放;
  6. Log the full X-Webhook-Signature and X-Webhook-Timestamp during integration to compare.联调时打全 X-Webhook-Signature 和 X-Webhook-Timestamp — 方便比对。

Troubleshooting故障排查

Symptom现象 Likely cause可能原因
401 / 403 on receiver接收方返回 401 / 403 Signature mismatch — check algorithm, payload format, and secret; verify body is the raw bytes (not pretty-printed JSON)签名不匹配 — 检查算法、payload 格式、secret;确认 body 是发到对端的原始字节(不是格式化后的 JSON)
Receiver sees no body for POSTPOST 请求接收方没收到 body Method is GET / DELETE, or the resolved inputs map is empty方法是 GET / DELETE;或解析后的 inputs map 为空
outputs are all nulloutputs 全部为 null Response is non-JSON, or JsonPath does not match. Adjust JsonPath in the Webhook editor's Output section响应不是 JSON、或 JsonPath 未命中。在 Webhook 编辑器 Output 区调整 JsonPath
Webhook never fires from Decision nodeDecision 节点没有触发 Webhook Decision did not land on approve / reject; or triggerOn excludes the current action; or hook.enabled = false决策没有落到 approve / reject;或 triggerOn 不包含当前 action;或 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 itURL 里的 {var} 没出现在 inputs 里 — 在 Inputs 区声明,或确保上游节点提供
Signature secret errorSignature secret 报错 Secret is blank or decryption failed. Re-save the secret in the Webhook editor (Signature section)secret 为空或解密失败 — 在 Webhook 编辑器 Signature 区重新保存 secret

Quick Reference速查


Glossary术语表

Term术语 Description描述
apiKey Public credential identifying your tenant. Included in every API request URL.标识租户的公开凭证。包含在每个 API 请求 URL 中。
apiSecret Private signing key for HMAC-SHA256 signatures. Never expose publicly.用于 HMAC-SHA256 签名的私有密钥。切勿公开暴露。
executionId Unique workflow execution instance identifier. Generated by workflow.apply.submit.唯一的工作流执行实例标识符。由 workflow.apply.submit 生成。
callbackKey Identifies a specific node waiting for input. Each node has a unique callbackKey.标识等待输入的特定节点。每个节点有唯一的 callbackKey。
requestId Per-API-call tracking ID for support and debugging.每次 API 调用的追踪 ID,用于支持和调试。
referenceId Your own tracking ID, passed through for audit trail and correlation.您自定义的追踪 ID,透传用于审计追踪和关联。
domainId Business unit identifier within your tenant (via x-domain header).租户内的业务单元标识符(通过 x-domain 请求头传递)。
nodeType Type of workflow node waiting for input. Determines which submission API to call.等待输入的工作流节点类型。决定应调用哪个提交 API。
crpPid Connected Related Party identifier in KYB workflows. Links liveness, docs, forms to a CRP.KYB 工作流中的关联方标识符。将活体检测、证件、表单关联到指定 CRP。
JSON string field Fields like personData, scores, images, formData expect a JSON-encoded string, not a nested object.personData、scores、images、formData 等字段接受 JSON 编码的字符串,而非嵌套对象。

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.

下表是执行层状态。服务端对接时,Case 层的审核结论维度(caseStatus)见 工作流生命周期 API → 查询状态与审核结论。

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事件类型

eventType Mode模式 Description描述
KYC_EVENT Async异步 Individual customer onboarding. Shown as KYC in the Console.个人客户入驻。平台界面上显示为 KYC。
KYB_EVENT Async异步 Corporate customer onboarding. Shown as KYB in the Console.企业客户入驻。平台界面上显示为 KYB。
TRANSACTION_EVENT Sync / Async同步 / 异步 Transaction screening交易筛查
WEB3_TRANSACTION_EVENT Sync / Async同步 / 异步 Web3 / on-chain transaction screening (KYT)Web3 链上交易筛查(KYT)
PERIODIC_FLOW_EVENT Async异步 Continuous monitoring持续监控
MANUAL_CASE_EVENT Async异步 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证件类型

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更新日志

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.移动 SDK 版本对齐正式发布版:iOS 1.0.11 / Android 1.0.11 / Flutter 1.0.2。凭据精简为 domain + sdkToken 两项(appId / apiKey 已编码在 token 内)。iOS 新增必填的 NSSpeechRecognitionUsageDescription。Android 要求 minSdk 26、compileSdk 36、开启 core library desugaring,AGP 9 上还需 android.uniquePackageNames=false。三端均新增可选的 language 参数,Android 与 Flutter 另新增可选的 eventType 参数。
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.修正 Android「权限」节:内置的 OCR 引擎(Veriff、Regula)会传递合并 RECORD_AUDIO、NFC、WAKE_LOCK、VIBRATE、FLASHLIGHT。运行时(危险级)权限现为 CAMERA 与 RECORD_AUDIO;每一项权限都须反映到 Google Play Data Safety(数据安全)申报。
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.新增 Flutter SDK 章。iOS 公共类型名 Width* → WIDTH*(1.0.5),麦克风(NSMicrophoneUsageDescription)改为必填。SDK 版本对齐: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首次发布 — OpenAPI 参考、Android SDK、iOS SDK



© 2026 WIDTH. All rights reserved.