# LegiChain V3 integration guide

Use the customer OpenAPI 3.1 documents distributed with this guide: `openapi-api.json`, `openapi-compute.json` and `openapi-media.json`. They describe separate regional API, assigned compute and retained-media surfaces. The downloadable customer documents exclude platform administration, internal transport and operator endpoints. The runtime also serves its filtered customer contract at `/openapi-public.json`.

The documents describe the V3 implementation, not a production environment provision or capacity guarantee. Obtain your workspace, regional API origin and permitted capture/compute origins during onboarding. V3 is a major-version integration; do not reuse V2 paths or assume wire compatibility. Tolerate additive response fields and branch on documented machine-readable states and codes.

## Credentials and workspace scope

Keep the workspace-bound `v3_` API key on your backend. Send `Authorization: Bearer <SERVER_API_KEY>` only to the configured regional API. Its scopes must permit the requested operation. `X-Workspace-ID` selects a workspace for a panel session; a server API key is already workspace-bound and any supplied workspace header must match that binding. A persona reference in one workspace does not authorize access in another.

Give an applicant device only its scoped `session_token`, `onboarding_id`, trusted regional API origin and allowed compute origins. A `compute_token` is issued for one accepted assignment and goes only to its returned compute origin. Neither token replaces your server API key for customer administration or new sessions. Never place credentials in URLs, browser storage or logs. Do not follow a region redirect while forwarding credentials.

## Create a persona, quote and session

1. Call `POST /v3/personas` with `{"external_subject_id":"your-stable-customer-reference"}` on your backend. Persist the returned persona ID in the workspace's scope. Names or document numbers are not cross-tenant matching keys.
2. Call `POST /v3/onboardings/quote` with the selected `services`, explicit `retention_years`, and optional `interview_mode`. This reads the server's current catalogue without creating an attempt. Do not calculate prices in your client.
3. Call `POST /v3/onboardings` with that persona, selected services and a persisted `Idempotency-Key`. Creation currently returns HTTP **200**, an asynchronous session state, `session_token` and a `queue` description. HTTP success is not a verification approval.

```http
POST /v3/onboardings
Authorization: Bearer <SERVER_API_KEY>
Content-Type: application/json
Idempotency-Key: <PERSISTED_ATTEMPT_KEY>

{
  "persona_id": "<PERSONA_ID>",
  "services": ["kyc", "ai_interview", "aml", "address"],
  "interview_mode": "ai",
  "interview_locale": "en-US",
  "retention_years": 10
}
```

Supported services are `kyc`, `ai_interview`, `aml`, `address` and `wallet_screening`. Selecting `kyc` creates a new identity-verification journey and collects its required evidence. To run only an interview for an existing verified person, use `services:["ai_interview"]`, the existing `persona_id`, and `verified_onboarding_id` referencing approved, retained KYC from the same persona and workspace. Set `interview_mode:"ai"` or `"manual"`; neither standalone interview asks the applicant to upload their identity documents again. The source must satisfy the published flow's identity-field prerequisites; AI also requires its retained selfie reference. A missing or ineligible source requires new KYC. Use either explicit `services` or legacy `bundled_products`, not both. Standalone manual currently accepts only the interview service; use a new full journey for additional selected checks.

Omitted/null retention inherits the workspace configuration; explicit zero selects temporary retention. The backend freezes one quote per session. Empty sessions and waiting do not charge. The first accepted input charges that quote once; retries or additional files for the same session do not create another retention charge. A new session is a new billable attempt. Retention starts at closure; retention zero purges temporary evidence after 24 hours.

The customer's active published panel flow defines interview questions, their order, expected answer types and voices. The session snapshots its selected version; an integration guide or client does not redefine it. Supported interview locales are `tr-TR`, `en-US`, `de-DE`, `es-ES` and `it-IT`. Omit `interview_locale` to use the published flow's default language. An explicit choice must have its translation and audio available in that flow. Website and capture UI locales (`tr`, `en`, `de`, `es`, `it`) are separate; they do not change the session's immutable interview language, region or identity fields.

## Queue, claim and direct compute

The initial receipt does not guarantee an immediately available compute host. Read `GET /v3/onboardings/{id}/queue` or subscribe to authenticated `GET /v3/onboardings/{id}/events`. SSE is a short-lived notification channel, not a durable replay log; reconnect or poll status after disconnect. A browser transport must support the Authorization header rather than placing tokens in the URL.

When an offer is available, `POST /v3/onboardings/{id}/claim` with `{"offer_token":"<OFFER_TOKEN>"}`. The assignment includes `compute_url`, `compute_token`, `expires_in` and `assignment_revision`. Check the HTTPS origin against the trusted regional allowlist before sending that token. Refresh the allowlist with `GET /v3/onboardings/{id}/compute-origins`; an authorized backend may also request a device bootstrap with `POST /v3/onboardings/{id}/sdk-session` within the original session lifetime.

Use `POST /v3/onboardings/{id}/reconnect` to refresh an expired or changed assignment. It may return a compute assignment, terminal/manual status or a queue state. Never continue uploading to an old host after assignment change. Replay only original bytes explicitly listed in `reupload_required`, preserving logical keys and recording sequence/timestamps. If those bytes were lost, expose a technical recovery state instead of substituting new evidence.

JSON-only AML/wallet sessions report `queue.state:"not_required"`; they do not use camera capture or reserve a GPU slot. A standalone manual interview using retained KYC also bypasses compute admission and goes to the manual operator queue. A new KYC journey with a later manual interview still needs compute for its identity checks.

## Capture and processing

Upload evidence directly to the assigned compute origin, using **raw bytes**, not multipart:

```http
PUT {compute_url}/compute/onboardings/{id}/files/{logical_key}?kind=document_front&document_type=passport
Authorization: Bearer <COMPUTE_TOKEN>
Content-Type: image/jpeg

<CAMERA_IMAGE_BYTES>
```

Use the evidence kind, content type and bounded query fields documented in the compute OpenAPI. Preserve the logical key and exact bytes for a retry. Files are camera-captured through the SDK; native NFC sends raw chip evidence for server verification. A client cannot declare a chip or document verified.

Wait for approved KYC and required selected checks before the AI interview. Fetch prepared question audio through `/interview/start` and `/prompts/{step_id}`. AI uses one recorder: send only its new fragments to `/capture/chunks/{sequence}` with monotonic `start_ms`/`end_ms`; do not resend an ever-growing cumulative recording. Submit `/answers` with the step, attempt and accepted recording range, then poll `/answers/{answer_id}`. A photo step uploads its own camera image and calls `/photo-step`. Finish the same recording with `/capture/end` and its last sequence. Upload acceptance or `PENDING_FINAL` is not a final identity decision.

For AI-only sessions referencing earlier KYC, selected AML/wallet checks initialize after the first billable recording fragment. Start the same recorder, send that initial fragment, then hold questions until `bundle_ready`; do not wait for those checks before sending their initialization trigger. If address is selected, collect its claim/proof before opening the interview recorder. Use the SDK's state handling for this ordering.

LiveKit is only for manual video calls. For an existing verified persona, create the standalone session with `POST /v3/onboardings`, `services:["ai_interview"]`, `interview_mode:"manual"`, `persona_id` and `verified_onboarding_id`. It reuses approved retained KYC, binds the panel's active published flow, and does not allocate a GPU or collect new identity evidence. Call `POST /v3/onboardings/{id}/manual/join`, then read `/manual`. Connect the manual media URL/token only when the response includes `media`; a waiting state has no live call token. The customer's licensed operators handle the flow-derived checklist and recorded decision.

Automatic AI-to-manual fallback is an explicit company/workspace setting: `workspace.policy.ai_manual_fallback_enabled` defaults to `false`. Enable it in the customer panel before creating sessions; each new session snapshots the policy without changing the published flow or its audio digest. An eligible AI `REVIEW` result (for example, verification could not complete within the flow's attempt limit) is handed to the regional automatic-fallback job after its evidence is safely archived. It enters the same manual queue: an available operator can take it immediately; otherwise the applicant waits. No human-reviewer escalation request is required for this enabled automatic path. Explicit consent refusal, hard KYC failure, and arbitrary transport errors do not activate it.

The device follows the server's returned manual state and queue rather than creating another persona, KYC or interview session. First poll `GET /v3/onboardings/{id}` with the scoped session token. Once the open session reports `state:"manual_waiting"` and `interview_mode:"manual"`, read `/v3/onboardings/{id}/manual`. Before the regional handoff job creates the call, that endpoint still returns 404; this is not a verification rejection. Stop on a terminal parent session. Connect LiveKit participant data only when the manual response includes `media`. The integration-guide checkbox documents this branch; it does not enable the company setting or send a client-side policy override. Existing reviewer-driven escalation remains a separate authorized operator action.

## Product inputs, results and reports

`POST /v3/products` requires an `Idempotency-Key` and returns HTTP **202** with a product ID, onboarding ID, product status and scoped session token. Read `GET /v3/products/{product_id}` for the eventual result. When submitting one of a parent session's selected products, include its `onboarding_id` and reuse the same parent persona. Do not omit that ID or add a separate retention selection: doing so creates a standalone billable session. Use JSON for AML/wallet input; an address proof is uploaded through assigned compute.

For wallet tracing, first read `/v3/products/wallet-capabilities`. Require a fresh regional corpus and a configured network for positive depth. New requests default to `wallet_depth:2`; use `0` for exact-address list matching or `1` for direct counterparties. Specify the network explicitly (`ETH`, `BSC`, `ARB`, `POLYGON`, `XBT`/`BTC`, `TRX`); an asset ticker does not identify its chain. Interpret `trace.complete`, `coverage`, `reasons`, `limitations` and `snapshot` with the hits. `inconclusive` is not clean; a related-address hit establishes exposure evidence, not guilt or ownership. Bitcoin input/output links do not establish an exact payer–payee relation.

For the session itself, read `GET /v3/onboardings/{id}` and its authoritative state/results. `review_required`, `bundle_review`, `technical_error`, cancellation and expiry require distinct handling. A terminal `completed` product-only session does not mean every selected check was clear. Reports are asynchronous too: `POST /v3/onboardings/{id}/report` returns 202; GET that resource for readiness and an authorized media link. Retained evidence is accessed through expiring regional `/f/{token}` links, not storage-provider credentials.

## Photo fraud before the KYC decision

When enabled on the assigned compute release, the existing liveness capture queues photo analysis in a separate worker. KYC waits for every current required source before finalizing its decision or allowing AI interview admission. Read the lightweight `fraud.status` from `GET /v3/onboardings/{id}`. Your backend can read `GET /v3/onboardings/{id}/fraud` with a regional API key that has `pii:read`; applicant SDK tokens cannot read detailed scores. Use bounded polling while jobs are pending, including earlier unfinished jobs in `counts`. No separate fraud-completed webhook is added: `onboarding.closed` and the KYC product's `product.completed` follow the combined decision and other required completion stages.

The detailed response describes the latest source-bound job, with counts for all jobs in the session. Its `result` is non-null only on completion. Per-job outcomes are `attack_flag`, `no_attack_flag` or `abstention`. The authorized onboarding detail also contains `result.photo_fraud_gate`, a versioned object (`version: "fraud52-v1"`, `required`, `status`, `source_ids`, `job_ids`, and optional `source_onboarding_id`). Gate states are `not_required`, `pending`, `passed`, `attack`, `error`. Pending fraud keeps KYC in `kyc_processing`; attack rejects with `HARD_PHOTO_FRAUD_ATTACK`; abstention or terminal technical failure yields `technical_error`, never approval. A `passed` fraud gate still requires the remaining KYC checks. A superseded result, missing native face or missing job is not clean. An expired detailed response contains only `status: "expired"`. Frame preparation, durable recording and the required wait have processing cost; the check adds no separate charge. The current server SDK candidate has no dedicated fraud wrapper; use this authenticated HTTP route and the published OpenAPI schema.

## Webhooks

Register a regional endpoint through `POST /v3/webhooks` with the required permissions. Keep its signing secret private. Delivery is at least once and may be out of order. Verify the raw body before parsing:

```text
Legichain-Signature: t=<UNIX_TIMESTAMP>,v1=<HEX_SIGNATURE>
Legichain-Event-ID: <EVENT_ID>

expected = HMAC_SHA256(endpoint_secret, UTF8(timestamp) + b"." + exact_body_bytes)
```

Use constant-time comparison, a bounded timestamp tolerance and durable payload-ID deduplication. Acknowledge accepted deliveries promptly with 2xx, then fetch the resource from its regional API with your own authorization. Payloads contain opaque event/resource IDs and state, not identity fields or media. Do not treat event order as a transaction sequence. The normal sender makes at most eight attempts; an authorized replay can deliver an event again. The OpenAPI `webhooks` section carries the event schema and supported names.

## Retries, pagination and errors

Reuse an `Idempotency-Key` only for the same logical mutation with the same body. Different input under the same key returns a conflict. Retrying after an uncertain response uses the original key; do not create a new paid attempt to recover a lost receipt. Not every write accepts this header—follow the operation contract. Never automatically repeat an unrelated mutation on a generic 500.

List endpoints return `next_cursor`; pass it unchanged as `after` with the same filters and stop when null. Some operator inventories use different cursors; customer integration should follow its own published endpoint. Exports can be bounded, so inspect their documented continuation/truncation metadata.

Errors use `{"error":{"code":"...","message":"...","details":{...}}}`. Validation responses may also retain a sanitized `detail` list. Use `error.code`, not localized UI text, for behavior. Handle 401 as credential/assignment expiry, 403 as scope denial, 402 as credit authority, 409 as a state or idempotency conflict, and 422 as invalid input. Apply bounded backoff for retryable failures and honor `Retry-After` when present on 429/503. The 503 codes `site_control_unreadable` (site controls are being repaired; new work is refused meanwhile), `intake_paused` (the site is temporarily not accepting new work), `waiting_room_full` and `compute_preparing` are retryable, carry `Retry-After` and are never an identity decision; work already in progress is unaffected, and the same `Idempotency-Key` may be reused for the retry. Refresh state before deciding to retry. Capacity and provider failures must not be presented as an identity rejection.

## SDK delivery

The **3.0.0-dev.2** local server integration candidate (Python `3.0.0.dev2`) includes a Node `.tgz`, Python `.whl`, .NET `.nupkg`, Java `.jar`/`.pom` and Go source archive. These are built artifacts for controlled integration delivery; no npm, PyPI, Maven, NuGet or Go registry release has been published. Obtain the package bundle and its `manifest.json` from the technical team and verify its checksums before installation. Follow the bundled `sdks/CUSTOMER-PACKAGE.md` delivery instructions and `sdks/CONTRACT.md` for scoped transports and platform setup; the Go archive uses a local module replacement.

The package includes webhook verification helpers, but durable event deduplication remains your backend's responsibility. Native mobile packages were not rebuilt for this server candidate. Real device behavior, Apple signing, provider access, production origins and measured GPU capacity have separate acceptance steps. Audio ZIP exports are flow resources with a manifest, not a compiled SDK or credentials.
