# API Authentication with Bearer Keys Source: https://docs.gu1.ai/en/api-reference/authentication Authenticate gu1 API requests using bearer API keys, including how to issue keys from the dashboard, scope permissions, and rotate credentials. ## Overview gu1 uses **API keys** to authenticate requests. All API requests must include your API key in the `Authorization` header using the Bearer scheme. Keys are issued in the format `gk__...` (see [API key format](#api-key-format) below). ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` > [!WARNING] > > Keep your API keys secure! Never commit them to version control or share them publicly. ## Getting Your API Key **1. Log in to Dashboard** Navigate to [app.gu1.ai](https://app.gu1.ai) and log in to your account **2. Access API Keys Section** Click **Settings** → **API Keys** in the sidebar **3. Create New Key** Click **Create API Key** button **4. Configure Key** * Give your key a descriptive name (e.g., "Production API", "Development") * Open **Manage permissions** and select **granular permissions** (`resource:action` pairs) aligned with your workspace RBAC. Grant only what the integration needs. * Optionally set an expiration date **5. Copy and Store** Copy the generated key immediately - it will only be shown once! ## Using Your API Key Include your API key in the `Authorization` header of every request: ```bash theme={null} curl http://api.gu1.ai/entities \ -H "Authorization: Bearer gk_prod_YOUR_KEY_HERE" ``` ### Example with Different Methods ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"type": "company", "name": "Acme Corp"}' ``` ```javascript JavaScript / Node.js theme={null} const response = await fetch('http://api.gu1.ai/entities', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ type: 'company', name: 'Acme Corp' }) }); ``` ```python Python theme={null} import requests headers = { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', } data = { 'type': 'company', 'name': 'Acme Corp' } response = requests.post( 'http://api.gu1.ai/entities', headers=headers, json=data ) ``` ## API Key Format API keys are opaque strings with the prefix `gk_`, followed by an **environment segment** and a random suffix (for example `gk_prod_...`). The segment reflects the environment you chose when creating the key (for example production vs sandbox). **Use production keys only with production organizations and data.** ## Permissions Permissions are **granular**: in the dashboard you assign allowed **resources** and **actions** (the same `resource:action` model as workspace RBAC). Each integration should receive the smallest set of permissions required for its endpoints. > [!NOTE] > > Follow the principle of least privilege — prefer explicit `resource:action` grants over broad access. ## Best Practices > [accordion] Secure Storage > > * Store API keys in environment variables or secret management systems > * Never hardcode keys in your source code > * Never commit keys to version control (use `.env` files and `.gitignore`) > [accordion] Key Rotation > > * Rotate API keys regularly (every 90 days recommended) > * Create new keys before revoking old ones to avoid downtime > * Update all systems that use the old key > [accordion] Monitor Usage > > * Regularly review API key activity in the dashboard > * Set up alerts for unusual usage patterns > * Immediately revoke compromised keys > [accordion] Environment Separation > > * Use test keys for development and staging > * Use live keys only in production > * Never use live keys on developer machines ## Error Responses If authentication fails, you'll receive one of these error responses: ### Missing API Key ```json theme={null} { "error": { "code": "UNAUTHORIZED", "message": "No API key provided" } } ``` **HTTP Status:** `401 Unauthorized` ### Invalid API Key ```json theme={null} { "error": { "code": "INVALID_API_KEY", "message": "Invalid API key provided" } } ``` **HTTP Status:** `401 Unauthorized` ### Expired API Key ```json theme={null} { "error": { "code": "EXPIRED_API_KEY", "message": "API key has expired" } } ``` **HTTP Status:** `401 Unauthorized` ### Insufficient Permissions ```json theme={null} { "error": { "code": "FORBIDDEN", "message": "API key does not have permission to perform this action" } } ``` **HTTP Status:** `403 Forbidden` ## Rate Limiting API keys are subject to rate limits based on your plan: | Plan | Requests per hour | Requests per day | | - | - | - | | **Free** | 100 | 10,000 | | **Starter** | 300 | 100,000 | | **Professional** | 1,200 | 500,000 | | **Enterprise** | Custom | Custom | ### Rate Limit Headers All API responses include rate limit information in the headers: ```http theme={null} X-RateLimit-Limit: 100 X-RateLimit-Remaining: 85 X-RateLimit-Reset: 2025-01-15T10:00:00Z ``` | Header | Description | | - | - | | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Number of requests remaining in the current window | | `X-RateLimit-Reset` | ISO 8601 timestamp when the rate limit resets | ### Rate Limit Exceeded Response When you exceed rate limits, you'll receive: ```json theme={null} { "error": "Rate limit exceeded", "code": "RATE_LIMIT_EXCEEDED", "message": "You have exceeded your API rate limit. Try again in 60 minutes.", "retryAfter": 3600, "retryAfterMinutes": 60, "limit": 100, "remaining": 0, "resetAt": "2025-01-15T10:00:00Z" } ``` **HTTP Status:** `429 Too Many Requests` **Response Headers:** ```http theme={null} X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 2025-01-15T10:00:00Z Retry-After: 3600 ``` > [!TIP] > > Monitor the rate limit headers in your responses to implement proactive rate limiting in your application. The `Retry-After` header indicates how many seconds you should wait before retrying. ## Testing Your API Key Use this simple test to verify your API key is working: ```bash theme={null} curl http://api.gu1.ai/auth/test \ -H "Authorization: Bearer YOUR_API_KEY" ``` **Success Response:** ```json theme={null} { "valid": true, "apiKey": { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Production API", "environment": "prod", "organizationId": "550e8400-e29b-41d4-a716-446655440001", "scopes": [], "rateLimit": 1000, "rateLimitRemaining": 999, "expiresAt": null, "lastUsedAt": "2026-01-10T12:00:00.000Z" } } ``` ## Next Steps > [card] [Create Your First Entity](/en/api-reference/entities/create) > > Start using the API to create entities > [card] [Define Custom Schemas](/en/api-reference/data-ingestion/custom-schemas) > > Set up data mapping for your use case > [card] [Webhooks](/en/webhooks/overview) > > Receive real-time notifications > [card] [KYC complete flow](/en/use-cases/kyc/complete-flow) > > End-to-end KYC integration guide # Archive automation Source: https://docs.gu1.ai/en/api-reference/automations/archive-automation DELETE /automations/{id} Archive an automation in gu1 to soft-delete it and stop future runs while preserving its configuration and execution history for later restore. ## Endpoint ``` DELETE https://api.gu1.ai/automations/:id ``` Archived automations are excluded from execution. Use [Restore automation](/en/api-reference/automations/restore-automation) to undo. ## Response **200** — `{ "success": true, "archived": true }` **404** — not found # Cancel execution (standby) Source: https://docs.gu1.ai/en/api-reference/automations/cancel-execution POST /automations/executions/{executionId}/cancel Cancel a paused automation execution in gu1 by execution ID, automation ID, or signed callback link to stop a waiting workflow from resuming. ## POST by execution ID ``` POST https://api.gu1.ai/automations/executions/:executionId/cancel ``` Authenticated. ## POST by automation ID ``` POST https://api.gu1.ai/automations/:id/cancel ``` Cancels the **most recent** waiting execution for that automation. ## GET with token (link) ``` GET https://api.gu1.ai/automations/executions/:executionId/cancel?token= ``` Returns HTML (“You have cancelled.”). ## Response **200** — `{ "success": true, "cancelled": true, ... }` # Continue execution (standby) Source: https://docs.gu1.ai/en/api-reference/automations/continue-execution POST /automations/executions/{executionId}/continue Resume a paused automation execution in gu1 by execution ID or callback link, with an optional payload merged into the saved event snapshot. ## Overview After a **standby** pause, continue the same execution. Optional JSON **payload** is merged onto the snapshot before the engine refreshes context from the database. *** ## POST by execution ID ``` POST https://api.gu1.ai/automations/executions/:executionId/continue Content-Type: application/json ``` **Body (optional):** `{ "payload": { ... } }` Authenticated with the org’s API key or session. ## GET with token (email/SMS link) ``` GET https://api.gu1.ai/automations/executions/:executionId/continue?token= ``` No session required; `callbackToken` must match the execution row. Returns an HTML confirmation page. ## POST by automation ID ``` POST https://api.gu1.ai/automations/:id/continue Content-Type: application/json ``` Resumes the **most recent** waiting execution for that automation. Optional `{ "payload": { ... } }`. ## Response (JSON routes) **200** — `{ "success": true, "waiting"?: boolean, "executionId"?, "completed"?, "continuedToStep"?, ... }` # Create automation Source: https://docs.gu1.ai/en/api-reference/automations/create-automation POST /automations Create a new automation workflow in gu1, specifying trigger, conditions, actions, and graph nodes that the engine validates for synergy. ## Endpoint ``` POST https://api.gu1.ai/automations Content-Type: application/json ``` ## Body (main fields) **name** `string` *required* Display name **type** `string` `realtime` (default) | `scheduled` **triggerType** `string` *required* Valid engine trigger (e.g. `manual_execution`, `investigation_created`, `scheduled`, …) **triggerConfig** `object` Trigger-specific config (schedule, filters, etc.) **conditions** `array` Condition objects: `field`, `operator`, `value` **actions** `array` Legacy flat list: `{ type, config }` **steps** `array` `{ conditions, actions, waitAfterStep? }[]` **graph** `object` `{ nodes[], edges[] }` — nodes: `trigger` | `condition` | `action`; edges may include `sourceHandle`: `true` | `false`. Must include at least one **trigger** node. **layout** `object` Optional node positions for the builder UI **enabled** `boolean` Default `true` ## Response **201** — `{ "automation": { ... } }` **400** — validation or synergy error (`synergyErrors` may be present) # Execute automation (test) Source: https://docs.gu1.ai/en/api-reference/automations/execute-automation POST /automations/{id}/execute Run a test execution of a gu1 automation using synthetic event data from the organization, without creating an execution row or waiting state. ## Endpoint ``` POST https://api.gu1.ai/automations/:id/execute ``` Builds a **test** event (sample entity/alert/investigation from the organization) and calls **`processEvent`**. Does **not** create an execution row or support **standby**. ## Response **200** — `{ "success": true, "message": "...", "automationId": "...", "casesProcessed": 1 }` **400** — e.g. no entities in org, or automation is archived # Get execution context (waiting) Source: https://docs.gu1.ai/en/api-reference/automations/execution-context GET /automations/executions/{executionId}/context Read the saved event snapshot for a waiting gu1 automation execution, exposing entity, alert, and investigation context for UI review screens. ## Endpoint ``` GET https://api.gu1.ai/automations/executions/:executionId/context ``` Only returns data while the execution status is **`waiting`**. ## Response **200** — `{ "context": { ... } }` **404** — not found or not in waiting state # Get automation Source: https://docs.gu1.ai/en/api-reference/automations/get-automation GET /automations/{id} Retrieve a single gu1 automation by ID, including its trigger configuration, graph definition, conditions, actions, and most recent executions. ## Endpoint ``` GET https://api.gu1.ai/automations/:id ``` ## Path Parameters **id** `string` *required* Automation UUID ## Response **200** — `{ "automation": { ... }, "recentExecutions": [...] }` (last 10 executions) **404** — `{ "error": "Automation not found" }` # List automations Source: https://docs.gu1.ai/en/api-reference/automations/list-automations GET /automations List all automations in your gu1 organization with optional filters for trigger type, status, and archived state, used to populate workflow lists. ## Endpoint ``` GET https://api.gu1.ai/automations ``` ## Query Parameters **type** `string` `realtime` | `scheduled` **enabled** `string` `true` | `false` **triggerType** `string` Filter by trigger type (must be a valid automation trigger). **archived** `string` `true` to return only archived automations; default lists non-archived. ## Response **200** — `{ "automations": [...], "total": number, "totalArchived"?: number }` ## Example ```bash theme={null} curl -s "https://api.gu1.ai/automations?enabled=true" \ -H "Authorization: Bearer YOUR_API_KEY" ``` # List executions Source: https://docs.gu1.ai/en/api-reference/automations/list-executions GET /automations/{id}/executions Retrieve paginated execution history for a single gu1 automation, including status, duration, processed cases, errors, and trigger event metadata. ## Endpoint ``` GET https://api.gu1.ai/automations/:id/executions?limit=20&offset=0 ``` ## Query Parameters **limit** `number` Default 20, max 100 **offset** `number` Pagination offset (default 0) ## Response **200** — `{ "executions": [...], "total": number }` # Restore automation Source: https://docs.gu1.ai/en/api-reference/automations/restore-automation POST /automations/{id}/restore Restore a previously archived gu1 automation so it becomes active again and resumes processing events according to its trigger configuration. ## Endpoint ``` POST https://api.gu1.ai/automations/:id/restore ``` ## Response **200** — `{ "success": true, "restored": true }` # Run automation (manual API) Source: https://docs.gu1.ai/en/api-reference/automations/run-automation POST /automations/{id}/run Trigger a production run of a gu1 automation via API for workflows configured with the manual_execution trigger, with full standby state support. ## Endpoint ``` POST https://api.gu1.ai/automations/:id/run Content-Type: application/json ``` **Only** automations with **`triggerType: "manual_execution"`** are allowed. Uses **`runAutomationById`** — creates an execution row when the workflow has **wait** steps, and may return **`waiting: true`**. ## Body **entityId** `string` Optional UUID — loads entity into `event.data` **transactionId** `string` Optional UUID — sets transaction context (`entityType: transaction`) **data** `object` Merged into `event.data` (custom fields, `phone`, `email` for notifications, etc.) ## Response **200 (completed)** — `{ "success": true, "message": "Automation run completed.", "automationId": "..." }` **200 (standby)** — includes `waiting: true`, `executionId`, `callbackToken`, `pausedAtStep`, `totalSteps`, `pausedAtNodeId`, `nextNodeId` as applicable **403** — trigger is not `manual_execution` **404** — not found or archived # List templates Source: https://docs.gu1.ai/en/api-reference/automations/templates GET /automations/templates List read-only automation templates available in Gu1, including pre-built graphs and optional preconfiguration parameters you can apply when cloning into the visual builder. ## Endpoint ``` GET https://api.gu1.ai/automations/templates ``` ## Response **200** — `{ "templates": [ ... ] }` Each template includes: | Field | Description | | - | - | | `code` | Stable catalog code | | `sortOrder` | Gallery order | | `automations` | One or more automation payloads (same shape as `POST /automations`) | | `visibility` | Optional `{ showInTabs: ["realtime" \| "scheduled"] }` | | `parameterDefinitions` | Optional knobs for preconfiguration (path + `mirrorPaths`) before create | ## Create from template ``` POST https://api.gu1.ai/automations/from-template ``` Body: ```json theme={null} { "code": "alert_created_email_notify", "paramValues": { "rule_external_ids": [], "severities": ["HIGH", "CRITICAL"], "recipient_emails": "ops@example.com", "message_template": "alert_created_email" } } ``` * `paramValues` is optional. When the template defines `parameterDefinitions` with `required: true`, missing values return **400**. * Values are applied to both flat fields and graph node data via `mirrorPaths`. * Example `alert_created_email_notify` creates a realtime automation: `alert_created` → `send_push_notification` (email). * Example `entity_monitoring_scheduled` creates a scheduled automation: cron → `fetch_entities` (filters) → `run_risk_matrix` (chosen matrix). > [!NOTE] > > Automations created from a template are **always created disabled** (`enabled: false`), regardless of the template definition. Review the configuration and activate them with `POST /automations/:id/toggle` (or from the dashboard) when ready. # Toggle automation Source: https://docs.gu1.ai/en/api-reference/automations/toggle-automation POST /automations/{id}/toggle Enable or disable a gu1 automation without archiving it, pausing event processing while keeping the workflow configuration intact for later use. ## Endpoint ``` POST https://api.gu1.ai/automations/:id/toggle ``` ## Response **200** — `{ "automation": { ... } }` with updated `enabled` # Update automation Source: https://docs.gu1.ai/en/api-reference/automations/update-automation PUT /automations/{id} Partially update a gu1 automation's name, graph, conditions, actions, or trigger configuration; the engine re-validates synergy when steps change. ## Endpoint ``` PUT https://api.gu1.ai/automations/:id Content-Type: application/json ``` Same fields as [Create automation](/en/api-reference/automations/create-automation), all optional. ## Response **200** — `{ "automation": { ... } }` **404** — automation not found # List waiting executions Source: https://docs.gu1.ai/en/api-reference/automations/waiting-executions GET /automations/waiting-executions List automation executions currently in standby state for the gu1 organization, used to surface waiting workflows in inboxes and review queues. ## Endpoint ``` GET https://api.gu1.ai/automations/waiting-executions ``` Useful for operator dashboards to show flows pending continue/cancel. ## Response **200** — list of waiting executions with metadata (automation name, labels for where it paused, etc.) # Country Requirements Source: https://docs.gu1.ai/en/api-reference/entities/country-requirements Get the validation fields and document types required per country for KYC and KYB onboarding flows in the gu1 universal entity data model. ## Overview The country requirements endpoints help developers understand what fields are required for entity creation in different countries. Each country has specific validation rules, tax ID formats, and required fields. This eliminates trial-and-error when creating entities and provides clear guidance on what data is needed. For **companies**, fiscal address fields (e.g. `domicilioFiscal`, `direccion`, `address`) are **optional** at creation. You can create with tax ID and legal name only, then populate the address later via manual edit or country enrichments (e.g. ARCA for Argentina). ## Supported Countries gu1 currently supports **16 countries** with comprehensive validation: > [card] 🇦🇷 Argentina > > CUIT validation > [card] 🇧🇷 Brazil > > CNPJ validation > [card] 🇲🇽 Mexico > > RFC validation > [card] 🇨🇱 Chile > > RUT validation > [card] 🇨🇴 Colombia > > NIT validation > [card] 🇵🇪 Peru > > RUC validation > [card] 🇺🇾 Uruguay > > RUT validation > [card] 🇪🇨 Ecuador > > RUC validation > [card] 🇵🇾 Paraguay > > RUC validation > [card] 🇧🇴 Bolivia > > NIT validation > [card] 🇻🇪 Venezuela > > RIF validation > [card] 🇺🇸 United States > > EIN validation > [card] 🇨🇦 Canada > > BN validation > [card] 🇪🇸 Spain > > CIF/NIF/NIE validation > [card] 🇵🇹 Portugal > > NIPC validation > [card] 🇪🇪 Estonia > > Registrikood validation *** ## Get All Countries ``` GET http://api.gu1.ai/entities/country-requirements ``` Retrieve a list of all supported countries. ### Response Example ```json theme={null} { "success": true, "countries": [ { "code": "AR", "name": "Argentina" }, { "code": "BR", "name": "Brazil" }, { "code": "MX", "name": "Mexico" }, { "code": "US", "name": "United States" }, ... ], "total": 16 } ``` *** ## Get Country-Specific Requirements ``` GET http://api.gu1.ai/entities/country-requirements/:countryCode ``` Get detailed validation requirements for a specific country. ### Path Parameters **countryCode** `string` *required* ISO 3166-1 alpha-2 country code (e.g., "AR", "BR", "US") ### Response Fields **success** `boolean` Indicates if the request was successful **country** `object` Country validation details **country properties** **code** `string` ISO country code **name** `string` Country name **taxIdName** `string` Local name for tax ID (e.g., "CUIT", "CNPJ", "RFC") **taxIdFormat** `string` Regular expression pattern for tax ID validation **requiredFields** `array` List of required attribute field names **optionalFields** `array` List of optional attribute field names. For companies, this includes fiscal address fields that can be filled later. **registries** `array` List of official registries for this country **documentation** `object` Example request payload **documentation properties** **example** `object` Complete example of how to create an entity for this country *** ## Examples ### Get Argentina Requirements ```bash cURL theme={null} curl http://api.gu1.ai/entities/country-requirements/AR \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities/country-requirements/AR', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }); const data = await response.json(); console.log(data.country); ``` ```python Python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities/country-requirements/AR', headers={'Authorization': 'Bearer YOUR_API_KEY'} ) requirements = response.json() print(requirements['country']) ``` ### Response Example ```json theme={null} { "success": true, "country": { "code": "AR", "name": "Argentina", "taxIdName": "CUIT", "taxIdFormat": "^\\d{2}-\\d{8}-\\d{1}$", "requiredFields": [ "cuit", "razonSocial" ], "optionalFields": [ "domicilioFiscal", "iibb", "actividadPrincipal", "fechaInicioActividades" ], "registries": [ "AFIP", "IGJ", "RPC" ] }, "documentation": { "example": { "type": "company", "externalId": "company_123", "name": "Example Company", "countryCode": "AR", "taxId": "Example CUIT", "attributes": { "cuit": "Example cuit", "razonSocial": "Example razonSocial", "domicilioFiscal": "Example domicilioFiscal" } } } } ``` *** ## Country-Specific Examples ### 🇦🇷 Argentina (CUIT) ```json theme={null} { "type": "company", "externalId": "company_ar_001", "name": "Tech Solutions Argentina", "countryCode": "AR", "taxId": "30-71234567-8", "attributes": { "cuit": "30-71234567-8", "razonSocial": "Tech Solutions S.A.", "domicilioFiscal": "Av. Corrientes 1234, CABA", "iibb": "901-123456-7", "actividadPrincipal": "Desarrollo de Software" } } ``` Minimal company creation (address optional): ```json theme={null} { "type": "company", "externalId": "company_ar_minimal", "name": "Tech Solutions Argentina", "countryCode": "AR", "taxId": "30-71234567-8", "attributes": { "cuit": "30-71234567-8", "razonSocial": "Tech Solutions S.A." } } ``` ### 🇧🇷 Brazil (CNPJ) ```json theme={null} { "type": "company", "externalId": "company_br_001", "name": "Tech Solutions Brasil", "countryCode": "BR", "taxId": "12.345.678/0001-90", "attributes": { "cnpj": "12.345.678/0001-90", "razaoSocial": "Tech Solutions Ltda", "enderecoFiscal": "Av. Paulista, 1000 - São Paulo, SP", "inscricaoEstadual": "123.456.789.012", "cnae": "6201-5/00" } } ``` ### 🇲🇽 Mexico (RFC) ```json theme={null} { "type": "company", "externalId": "company_mx_001", "name": "Tech Solutions México", "countryCode": "MX", "taxId": "TSM980101ABC", "attributes": { "rfc": "TSM980101ABC", "razonSocial": "Tech Solutions S.A. de C.V.", "domicilioFiscal": "Av. Reforma 123, Ciudad de México", "regimenFiscal": "601" } } ``` ### 🇺🇸 United States (EIN) ```json theme={null} { "type": "company", "externalId": "company_us_001", "name": "Tech Solutions Inc", "countryCode": "US", "taxId": "12-3456789", "attributes": { "ein": "12-3456789", "legalName": "Tech Solutions Inc.", "address": "123 Main St, San Francisco, CA 94102", "stateOfIncorporation": "Delaware", "naicsCode": "541511" } } ``` ### 🇪🇸 Spain (CIF / NIF / NIE) Company `taxId` accepts **CIF** (incorporated companies), **NIF** (sole traders / autónomos), and **NIE** (foreign-resident autónomos). ```json theme={null} { "type": "company", "externalId": "company_es_001", "name": "Tech Solutions España", "countryCode": "ES", "taxId": "A12345678", "attributes": { "cif": "A12345678", "razonSocial": "Tech Solutions S.L.", "direccionFiscal": "Calle Gran Vía 1, Madrid", "cnae": "6201" } } ``` ```json theme={null} { "type": "company", "externalId": "company_es_autonomo_001", "name": "Monochef Academy", "countryCode": "ES", "taxId": "74387028Z" } ``` *** ## Error Responses ### 404 - Country Not Supported ```json theme={null} { "success": false, "error": { "code": "COUNTRY_NOT_SUPPORTED", "message": "Country code 'XX' is not supported", "details": { "countryCode": "XX", "supportedCountries": ["AR", "BR", "MX", ...] } } } ``` *** ## Best Practices > [accordion] Query Before Creating > > Always query country requirements before creating entities to ensure you collect all necessary data from your users upfront. > [accordion] Cache Requirements > > Country requirements rarely change. Consider caching them in your application to reduce API calls. > [accordion] Validate Client-Side > > Use the `taxIdFormat` regex pattern to validate tax IDs on the client side before submitting to the API. > [accordion] Localize Field Names > > Display field names in the user's language. The API returns local field names (e.g., "razonSocial" for Argentina instead of "legalName"). *** ## Next Steps > [card] [Create Entity](/api-reference/entities/create) > > Use the requirements to create a properly validated entity > [card] [Validate Tax IDs](/en/api-reference/entities/country-requirements) > > Validate tax IDs before entity creation # Create an entity automatically with enrichment Source: https://docs.gu1.ai/en/api-reference/entities/create-automatic POST /entities/automatic Automatically create a person or company enriched from official registries in the gu1 universal entity model for KYC, KYB, and risk analysis. ## Overview The automatic entity creation endpoint allows you to create entities by providing minimal information (tax ID and country). The system automatically: * Fetches company/person data from official registries * Enriches the entity with additional information * Creates related entities (shareholders, directors) based on the specified depth * Executes enrichments automatically This is ideal for KYB (Know Your Business) and KYC (Know Your Customer) processes where you want to onboard entities with complete information automatically. ## Endpoint ``` POST http://api.gu1.ai/entities/automatic ``` ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Request Body **taxId** `string` *required* Tax identification number of the entity (CNPJ/CPF for Brazil, CUIT/CUIL for Argentina, RUT for Chile). Within an organization, an active **`taxId`** (normalized: letters and digits only) may belong to **only one** entity — whether `person` or `company`. If the same type already exists, the API reuses it (`alreadyExisted`). If another type already holds that tax ID, the request fails with **`409`** and code **`DUPLICATE_TAX_ID`**. **Type**: `string` (min length: 1) **country** `string` *required* ISO 3166-1 alpha-2 country code. Automatic creation supports **`BR`**, **`AR`**, and **`CL`** only. Any other country returns an error stating automatic creation is not supported for it — use [Create an entity](/en/api-reference/entities/create) instead. **Type**: `string` (length: 2) **type** `string` *required* Type of entity to create: * `company` - Business entity * `person` - Individual person **Type**: `enum` - `'company' | 'person'` **nationality** `string | null` Optional. ISO 3166-1 alpha-2 or a label the API maps to ISO2; stored on the **main** entity row (same validation as [Create entity](/en/api-reference/entities/create)). **monitoring** `object` Optional. Same semantics as [Create entity](/en/api-reference/entities/create#example-gu1-sanctions-monitoring-on-create), with two maps: * **`main`**: watchlist for the **root** entity (`taxId` in the body) when enrichments run from `autoExecuteIntegrations`. * **`relationships`**: watchlist for **shareholders / related** entities at `depth` > 0 when enrichments run from `autoExecuteIntegrationsShareholders` (per `company` / `person`). **Today only** `global_gueno_sanctions_enrichment`. Recommended value: `{ "watchlist": true }` or `{ "watchlist": true, "riskMatrixId": "" | null }` (legacy `boolean` also accepted). Each map only affects entities that actually receive that enrichment. Requires the code in the matching enrichment array and org monitoring ON in Marketplace. **externalId** `string` Your unique identifier for this entity in your system. **Optional.** When omitted, `externalId` is set to the **normalized tax ID** derived from required **`taxId`**: letters and digits only, uppercase (no dots, dashes, or spaces). Example: `30-12345678-9` → `30123456789`. The **`taxId` column** is still saved in the [country display format](/en/api-reference/entities/tax-id-formats). Same auto-assignment rules as [Create an entity (person or company)](/en/api-reference/entities/create) when `taxId` is present. **Type**: `string` (optional) **depth** `number` (default: 0) How many levels of shareholders/relationships to automatically create: * `0` - Only create the main entity (no relationships) * `1` - Create direct shareholders/directors * `2` - Create shareholders and their shareholders * Maximum: `5` **Type**: `number` (min: 0, max: 5, default: 0) > [!WARNING] > > **Brazil + `depth > 0` fails the entire request** if the discovery enrichments are missing. The API checks this **before** creating the main entity: it does **not** create the person or company and then skip related records. > > * **Person:** both `br_bdc_related_companies_enrichment` **and** `br_bdc_related_persons_enrichment` must be in the **resolved** main-entity set (`autoExecuteIntegrations.enrichments`, or all **enabled** marketplace enrichments when `executeAllActiveEnrichments: true`). Both must be **enabled** for the organization. `executeAllActiveEnrichments: true` does **not** bypass this if either is disabled or listed in `excludeEnrichments`. > * **Company:** `br_bdc_shareholders_enrichment` must be in that same resolved set and **enabled**. > > If you cannot run those enrichments, send **`depth: 0`**. `autoExecuteIntegrationsShareholders` only controls enrichments **on children after they exist**; it does not satisfy this check. **relationships** `array` Declarative links to **existing** entities (`relatedEntityId` / `relatedTaxId` / `relatedExternalId` + `relationshipType` + `role`). Independent of enrichment `depth`. Max 10. Missing counterpart → `RELATED_ENTITY_NOT_FOUND` and the entity is not created. Same semantics as [Create entity](/en/api-reference/entities/create#param-relationships). **enrichDeclaredRelationships** `boolean` (default: false) When `true`, after linking the counterparts in `relationships`, also run `autoExecuteIntegrationsShareholders` enrichments on those **existing** entities (by related entity type: `company` vs `person` lists). Independent of `depth`. **Type**: `boolean` (optional, default: false) **isClient** `boolean` (default: false) Mark this entity as a client/customer for tracking purposes **Type**: `boolean` (default: false) **registrationDate** `string | number` Optional registration date for the **main** entity. ISO 8601 datetime string or epoch milliseconds. **Type**: `string (ISO datetime) | number` (optional) **runInBackground** `boolean` (default: false) When `true`, the creation is enqueued and the API responds immediately with **`202`** and `data.status: "processing"` plus a `jobId`; completion is reported over Socket.IO (see [WebSocket Events](#websocket-events)). When `false` (default), the request runs synchronously and returns the full result. **Type**: `boolean` (optional, default: false) **workflowId** `string` UUID of an automation with trigger `create_entity_flow` (or `entity_created` + automatic flow). When sent, the request becomes a **creation-flow** run: `autoExecuteIntegrations`, `autoExecuteIntegrationsShareholders`, and `depth` are **ignored**, only that automation runs (enrichments, risk matrix, conditions, and actions live in the workflow), and `entity_created` is **not** emitted. If the id is not a valid enabled `create_entity_flow` automation, the body flow is used instead. **Type**: `string` (uuid, optional) **riskMatrixId** `string | string[]` One or more risk matrix UUIDs (legacy: a single UUID string). After creation, active rules tied to those matrices run (unless `skipRulesExecution` is true). **Type**: `string | string[] | null` (optional) **riskMatrixIds** `string[]` Preferred for **multiple** matrices: ordered UUID list. Takes precedence over `riskMatrixId` when non-empty. **Type**: `string[]` (optional) **skipRulesExecution** `boolean` (default: false) Skip automatic rules execution after entity creation **Type**: `boolean` (optional, default: false) **status** `string` (default: under\_review) Initial status for the entity. Options: * `active` * `inactive` * `not_started` * `blocked` * `under_review` (default) * `pending_verification` - Awaiting KYC/KYB completion * `awaiting_information` - Waiting on client data (e.g. onboarding documents requested by email) * `suspended` * `expired` * `deleted` * `rejected` **Type**: `enum` - `'active' | 'inactive' | 'blocked' | 'under_review' | 'pending_verification' | 'awaiting_information' | 'suspended' | 'expired' | 'deleted' | 'rejected' | 'not_started'` (default: 'under\_review') **operationalHours** `object | null` Optional **main entity** operational hours (`timezone` + `weekly`). Persisted on automatic creation the same as manual entity creation. Not applied to shareholders or relationships created via `depth`. **autoExecuteIntegrations** `object` Configure automatic execution of integrations for the main entity. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes. **Type**: `object` (optional) **Properties:** * `executeAllActiveEnrichments` (boolean, optional, default: `false`) - Execute all active enrichment integrations * `enrichments` (array, optional, default: `[]`) - Array of specific enrichment provider codes to execute * `enrichmentGroupRefs` (array of strings, optional) - Marketplace enrichment group slugs (enrichments only). With `executeAllActiveEnrichments: false`, groups are resolved and merged with explicit `enrichments`. With `executeAllActiveEnrichments: true`, group refs are ignored (not resolved); explicit `enrichments` may still append after the active set. * `excludeEnrichments` (array, optional, default: `[]`) - Provider codes to omit from the final resolved set (e.g. run all active except listed codes). If the code is the basic-data source that would run (enabled primary or substitute), that creation skips it and uses the next chain member that is enabled and not excluded. ```typescript theme={null} { executeAllActiveEnrichments?: boolean; // default: false enrichments?: ValidProviderCodesEnum[]; // default: [] enrichmentGroupRefs?: string[]; excludeEnrichments?: ValidProviderCodesEnum[]; // default: [] } ``` **Example:** ```json theme={null} { "executeAllActiveEnrichments": true, "excludeEnrichments": ["br_bdc_shareholders_enrichment"], "enrichmentGroupRefs": ["my_marketplace_group_slug"] } ``` Do **not** enable a catalog fallback in Marketplace (and do **not** list it here) if you only want it when the primary fails. See [Marketplace fallbacks](/en/api-reference/enrichment/overview#marketplace-fallbacks). **autoExecuteIntegrationsShareholders** `object` Configure automatic execution of integrations for shareholders and related entities created during the hierarchy traversal. This allows you to specify different integrations for companies vs persons. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes. **Type**: `object` (optional) **Properties:** * `executeAllActiveEnrichments` (boolean, optional, default: `false`) - Execute all active enrichment integrations for all shareholders * `enrichments` (object, optional) - Specific enrichment provider codes by entity type: * `company` (array, optional, default: `[]`) - Enrichments for company shareholders * `person` (array, optional, default: `[]`) - Enrichments for person shareholders * `enrichmentGroupRefs` (array of strings, optional) - Same group slugs as on the main object; **applied to both** `company` and `person` child pipelines when `executeAllActiveEnrichments` is `false`. When `executeAllActiveEnrichments` is `true` on this object, group refs are ignored; explicit per-type `enrichments` may still append after each side’s active set. * `excludeEnrichments` (array, optional, default: `[]`) - Codes omitted from both `company` and `person` lists after merge. This also skips basic data for those related entities when the excluded code is the one that would run. ```typescript theme={null} { executeAllActiveEnrichments?: boolean; // default: false enrichments?: { company?: ValidProviderCodesEnum[]; // default: [] person?: ValidProviderCodesEnum[]; // default: [] }; enrichmentGroupRefs?: string[]; excludeEnrichments?: ValidProviderCodesEnum[]; // default: [] } ``` **Example:** ```json theme={null} { "executeAllActiveEnrichments": true, "excludeEnrichments": ["br_bdc_shareholders_enrichment"], "enrichmentGroupRefs": ["shareholder_pipeline_group_slug"] } ``` ## Required Enrichment Codes by Country > [!WARNING] > > Automatic creation needs **at least one** basic-data enrichment **enabled** in Marketplace for that country and entity type (company or person). The canonical primary runs first when it is active and not listed in `excludeEnrichments`. If it is off or excluded, the first substitute in its chain that is **enabled** and not excluded runs instead. If **none** of the chain is available, the request fails **before** the entity is created. > > `executeAllActiveEnrichments: true` only includes enrichments that are **enabled**. A disabled substitute does not count as a basic-data source. When the primary is active and fails, a substitute may still run with its card off if the catalog has `fallback_requires_activation: false`. That does not replace the requirement to have **one of them enabled** in order to start. > [!NOTE] > > When the whole chain is missing, the response is **HTTP 422** with `success: false` and `error.code` `BASIC_DATA_ENRICHMENT_REQUIRED`. The text in `error.message` and `data.errors.creationFailed[].error` is **the same** string as the API log (English, truncated at 500 characters). It is not the generic lookup message (`We could not complete the basic data lookup for this document.`). The text names the codes to activate, in catalog-chain order. > > ```json theme={null} > { > "success": false, > "error": { > "code": "BASIC_DATA_ENRICHMENT_REQUIRED", > "message": "Automatic creation requires at least one active basic-data enrichment for BR company. Activate one of: br_cpfcnpj_complete_company_enrichment, br_brasilapi_company_enrichment, br_cnpjws_company_enrichment, br_opencnpj_company_enrichment, br_bdc_basic_data_company_enrichment (marketplace)." > }, > "data": { > "entity": null, > "errors": { > "creationFailed": [ > { > "entityType": "company", > "level": 0, > "code": "BASIC_DATA_ENRICHMENT_REQUIRED", > "error": "Automatic creation requires at least one active basic-data enrichment for BR company. Activate one of: br_cpfcnpj_complete_company_enrichment, br_brasilapi_company_enrichment, br_cnpjws_company_enrichment, br_opencnpj_company_enrichment, br_bdc_basic_data_company_enrichment (marketplace)." > } > ] > } > } > } > ``` > > A person in Brazil uses the same sentence with `BR person` and the person codes in the table below. Argentina and Chile use the same sentence with their own chain. Bulk import in `automatic` mode stores that same text on the failed row. ### Brazil (BR) #### Main Entity | Entity Type | Primary (runs first when active) | Also accepted, in this order, when enabled | | - | - | - | | **Company** | `br_cpfcnpj_complete_company_enrichment` | `br_brasilapi_company_enrichment`, `br_cnpjws_company_enrichment`, `br_opencnpj_company_enrichment`, `br_bdc_basic_data_company_enrichment` | | **Person** | `br_bdc_basic_data_enrichment` | `br_cpfcnpj_complete_person_enrichment`, `br_cpfcnpj_complete_person_9_enrichment` | #### Shareholders / Related Entities (only when `depth > 0`) | Main Entity Type | Required Enrichment Code(s) | Description | | - | - | - | | **Company** | `br_bdc_shareholders_enrichment` | Required to discover the QSA. Missing → **the whole request fails**; the company is **not** created. | | **Person** | `br_bdc_related_companies_enrichment` **AND** `br_bdc_related_persons_enrichment` | **Both** required. If either is missing, disabled, or excluded → **the whole request fails**; the person is **not** created. | > [!WARNING] > > These codes must be on the **main entity** resolved set, not only on `autoExecuteIntegrationsShareholders`. Missing either related-person enrichment (or shareholders for companies) is a hard fail, not a partial create. > [!NOTE] > > The API runs those enrichments on the **main** entity to discover shareholders or related people/companies. `autoExecuteIntegrationsShareholders` only controls what runs **on each child after it is created**. ### Argentina (AR) #### Main Entity | Entity Type | Primary (runs first when active) | Also accepted when enabled | | - | - | - | | **Company** and **Person** | `ar_nosis_extended_verification_enrichment` | `ar_arca_contribuyente_enrichment` (one way only: ARCA does not fall back to the primary) | #### Shareholders / Related Entities > [!WARNING] > > Argentina does **not** support automatic shareholder/relationship creation yet. The `depth` parameter must be `0`. If `depth > 0` is provided, the request will fail with an error. ### Chile (CL) #### Main Entity | Entity Type | Primary (only code in the chain) | Catalog substitutes | | - | - | - | | **Company** | `cl_rutsinfo_info_company_enrichment` | None. If it is off, automatic company creation fails. | | **Person** | `cl_baseapi_basic_data_person_enrichment` | None. If it is off, automatic person creation fails. | #### Shareholders / Related Entities > [!WARNING] > > Chile does **not** support automatic shareholder/relationship creation yet. The `depth` parameter must be `0`. If `depth > 0` is provided, the request fails. **customData** `object` **Optional** — Client-provided values for the **main entity** that must **not** be replaced by registry enrichments. Does not apply to shareholders or related entities (`depth > 0`). After enrichments run, the API **re-applies** `customData` so values are preserved (e.g. automatic name sync from normalized data). **Persistence:** | `customData` field | Root (`entities`) | `entityData` | | - | - | - | | `name` | `name` | — | | `email` | `email` | `person.email` / `company.email` | | `phone` | `phone` | `person.phone` / `company.phone` | | `birthDate` | — | `person.dateOfBirth` only (person) | | `address` | — | `person.address` or `company.address` | | `gender` | — | `person.gender` (optional; closed enum: `M`, `F`, `male`, `female`, `other`, `unknown` — use **`other`** for non-binary; in **AR**, only `M`/`F` apply to CUIL derivation and RENAPER. See [Create entity — Person](/en/api-reference/entities/create#person-entity)) | **Documented properties:** `name`, `email`, `phone`, `birthDate` (person), `address` (string or object with `fullAddress`, `street`, `city`, …), `gender` (optional enum — `other` for non-binary). **Additional keys (API only):** any other key in `customData` is accepted and stored under `entityData.person` or `entityData.company` with the same overwrite protection. E.g. `firstName`, `occupation`, `tradeName`. The dashboard form only sends the documented fields; API integrations may extend the object. **Example (person):** ```json theme={null} { "taxId": "23450679909", "country": "AR", "type": "person", "customData": { "name": "JOHN DOE", "email": "client@company.com", "phone": "+541112345678", "birthDate": "1990-05-15", "address": "123 Main St, Buenos Aires" } } ``` **Example (company):** ```json theme={null} { "taxId": "30712345678", "country": "AR", "type": "company", "customData": { "name": "Acme Argentina S.A. (trade name)", "email": "contact@acme.com", "phone": "+541140000000", "address": { "fullAddress": "Av. del Libertador 100, Buenos Aires", "city": "Buenos Aires" } } } ``` **attributes** `object` **Optional** - Custom attributes as key-value pairs for the created entity. Applied only to the main entity (person or company created), not to shareholders/relationships. Useful for business segments, tags, internal IDs, or any metadata you want to associate at creation time. **Structure:** object with string keys and values of any type (string, number, boolean, array, etc.). **Example:** ```json theme={null} { "businessSegments": ["retail", "fintech"], "source": "onboarding_web", "tags": ["vip", "high_volume"] } ``` ## Query Parameters **refresh** `boolean` (default: false) Force re-enrichment of the main entity even if it already exists in the system. **Type**: `boolean` (query string: `"true"` or `"false"`) **Behavior**: * When `true`: Forces fresh data fetch from official registries and enrichment providers * When `false` or omitted: Uses cached enrichment data if available * Overrides organization setting `enrichmentsConfig.reEnrichExistingEntities` **Use Cases**: * Periodic compliance reviews requiring updated information * Re-validating entity data after regulatory changes * Updating company structure after known corporate changes * Manual refresh triggered by compliance officers **Example**: ```bash theme={null} POST http://api.gu1.ai/entities/automatic?refresh=true ``` **Cost Note**: May incur additional charges from third-party data providers. **reEnrichExistingChildEntities** `boolean` (default: false) Force re-enrichment of ALL shareholders and related entities in the corporate structure. **Type**: `boolean` (query string: `"true"` or `"false"`) **Behavior**: * When `true`: Forces fresh data fetch for the main entity AND all shareholders at all levels (up to `depth`) * When `false` or omitted: Only refreshes the main entity if `refresh=true`, shareholders use cached data * Works in combination with the `depth` parameter to determine how deep to refresh * Overrides organization setting for all related entities **Use Cases**: * Complete corporate structure audit * Due diligence requiring up-to-date ownership chain * Annual compliance reviews of entire corporate tree * Investigation of complex ownership structures **Example - Refresh entire structure**: ```bash theme={null} POST http://api.gu1.ai/entities/automatic?reEnrichExistingChildEntities=true&depth=3 ``` This will refresh the main company AND all shareholders up to 3 levels deep. **Performance Note**: * Setting this to `true` with high `depth` values (4-5) can take several minutes * May result in significant costs if the corporate structure is complex * Consider using selectively for high-risk entities only **Best Practice**: * Use `refresh=true` alone for single entity updates * Use `reEnrichExistingChildEntities=true` only when you need full ownership chain validation ## Response By default the endpoint executes synchronously and returns the complete result including the main entity and all related entities created. With **`runInBackground: true`** the response is **`202`** and the work continues in the background: ```json theme={null} { "success": true, "data": { "status": "processing", "jobId": "...", "taxId": "...", "type": "company" } } ``` **success** `boolean` Indicates if the entity was created successfully **data** `object` Complete information about the creation: * `entity` (object) - The main entity created with all its data * `shareholders` (array) - Child entities materialized in that run (companies only). Each item is `{ id, name, taxId, type }`. Percentage and roles are stored on the relationship; read them later with [Get materialized shareholders](/en/api-reference/entities/shareholders). * `relationships` (array) - Array of related entities created (for persons) * `summary` (object): * `entitiesCreated` (number) - Total number of entities created * `relationshipsCreated` (number) - Total number of relationships created * `errorsCount` (number) - Number of errors encountered * `errors` (object, optional) - Details of any errors that occurred: * `creationFailed` (array) - Failed entity creations * `enrichmentFailed` (array) - Extra enrichments that failed **after** the entity was persisted (`entityId` + `failedProviders`). Empty when basic-data fails and the entity is not created. Each `failedProviders` item has `providerCode`, `error` (English), and optional `code`. When the request asked for an enrichment the organization has not enabled, `code` is `INTEGRATION_NOT_ENABLED` (also `INTEGRATION_NOT_CONFIGURED`, `INTEGRATION_BLOCKED`, `INTEGRATION_GLOBALLY_DISABLED`, `CONTRACT_ACCESS_NOT_INCLUDED`, `INTEGRATION_NOT_FOUND`). Those codes are not retried. Other enrichments in the same request still run, and `success` stays `true` when the entity was created. * `enrichmentFailedDetails` (array, additive) - Each basic-data attempt that failed (primary + catalog fallbacks) when the entity was **not** created. Items: `providerCode` (marketplace code), `code` (semantic, e.g. `DOCUMENT_RESTRICTED`, `UPSTREAM_CREDITS_ERROR`), `errorMessage` (English). Also nested on the matching `creationFailed[]` row. For organizations where this setting is enabled, if the primary source identifies a person as a minor, the entity is immediately created as `Person ` with `attributes.isMinor: true`. Retries, fallbacks, and additional enrichments are skipped; risk analysis runs normally. This behavior is disabled by default. **rulesResult** `object` Result of rules execution (only present when rules ran, e.g. when **skipRulesExecution** is `false` and a risk matrix is configured via `riskMatrixId` or `riskMatrixIds`), or null. When present, includes: * **success** (boolean) - Whether rules executed successfully * **rulesTriggered** (number) - Number of rules that were triggered * **alerts** (array) - Alerts generated by rules * **riskScore** (number) - Final calculated risk score * **decision** (string) - Final decision (APPROVE, REJECT, HOLD, REVIEW\_REQUIRED) * **rulesExecutionSummary** (object) - Present when rules ran. See below for structure. **rulesExecutionSummary** `object` **At the root of the response** (same as transactions API). Same value as `rulesResult.rulesExecutionSummary`. **Only present when rules ran (e.g. skipRulesExecution is false and risk matrix was executed).** Summary of which rules matched (hit) vs did not match (no hit), executed actions, and total score. Omitted when rules did not run. See [Rules Execution Summary](/en/api-reference/rules-execution-summary) for the full structure and a complete example. * **rulesHit** (array) - Rules whose conditions were met. Each item: **name**, **description**, **score**, **priority**, **category**, **status** (e.g. `active`, `shadow`), **conditions** (array of `{ field, value, operator? }`), **actions** (alerts, suggestion, status, assignedUser). * **rulesNoHit** (array) - Rules that were evaluated but conditions were not met. Same structure as rulesHit (includes configured actions, not executed). * **actionsExecuted** (object) - Aggregated executed actions across all rules that hit: **alerts** (array of `{ name?, type?, severity?, description? }`), **suggestion** (`BLOCK` | `SUSPEND` | `FLAG`, highest weight), **status** (entity status applied, if any), **assignedUser** (`{ userId }`, if any), **customKeys** (array of strings, optional) — custom action keys from matched rules; for integrations/workflows. * **totalScore** (number) - Sum of **score** of all rules that hit and are **not** in `shadow` status. ## WebSocket Events The system emits real-time events during the creation process: ### `entity:creation-started` Emitted when the creation process begins. ```json theme={null} { "taxId": "12.345.678/0001-90", "type": "company", "userId": "user_id" } ``` ### `entity:creation-completed` Emitted when the entity and all relationships have been created. ```json theme={null} { "success": true, "mainEntity": { "id": "uuid", "name": "Company Name", "taxId": "12.345.678/0001-90" }, "stats": { "totalEntitiesCreated": 15, "companiesCreated": 8, "peopleCreated": 7, "relationshipsCreated": 14 } } ``` ### `entity:creation-failed` Emitted if the creation process fails. ```json theme={null} { "success": false, "error": "Error message", "taxId": "12.345.678/0001-90" } ``` ## Gu1 Sanctions Monitoring on Automatic Create For `POST /entities/automatic`: | Field | Applies to | | - | - | | `monitoring.main` | Root entity when enrichments run from `autoExecuteIntegrations`. | | `monitoring.relationships` | Each shareholder/related entity at `depth` > 0 when enrichments run from `autoExecuteIntegrationsShareholders`. | Today the only body-monitoring code is **`global_gueno_sanctions_enrichment`**. It must appear in the enrichment array for that level **and** in `main` or `relationships` with watchlist enabled. ```json theme={null} { "taxId": "30-71000001-2", "country": "AR", "type": "company", "depth": 1, "monitoring": { "main": { "global_gueno_sanctions_enrichment": { "watchlist": true } }, "relationships": { "global_gueno_sanctions_enrichment": { "watchlist": true, "riskMatrixId": null } } }, "autoExecuteIntegrations": { "executeAllActiveEnrichments": false, "enrichments": [ "ar_afip_registration_enrichment", "global_gueno_sanctions_enrichment" ] }, "autoExecuteIntegrationsShareholders": { "executeAllActiveEnrichments": false, "enrichments": { "company": ["global_gueno_sanctions_enrichment"], "person": ["global_gueno_sanctions_enrichment"] } } } ``` Registry enrichments (e.g. `ar_afip_registration_enrichment`) ignore `monitoring` and always run as one-off queries. > [!WARNING] > > This payload only illustrates **`monitoring`** and Gu1 enrichment codes. A real request must still include the **mandatory registry enrichments** for the chosen `country` and `type` (see **Required Enrichment Codes by Country** above), or automatic creation will fail. ## Examples ### Create Company with Shareholders (Depth 1) ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities/automatic \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taxId": "12.345.678/0001-90", "country": "BR", "type": "company", "depth": 1, "isClient": true, "autoExecuteIntegrations": { "executeAllActiveEnrichments": true, } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities/automatic', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ taxId: '12.345.678/0001-90', country: 'BR', type: 'company', depth: 1, isClient: true, autoExecuteIntegrations: { executeAllActiveEnrichments: true, } }) }); const data = await response.json(); console.log(data); // Listen for WebSocket events socket.on('entity:creation-completed', (result) => { console.log('Entity created:', result.mainEntity); console.log('Total entities created:', result.stats.totalEntitiesCreated); }); ``` ```python Python theme={null} import requests response = requests.post( 'http://api.gu1.ai/entities/automatic', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'taxId': '12.345.678/0001-90', 'country': 'BR', 'type': 'company', 'depth': 1, 'isClient': True, 'autoExecuteIntegrations': { 'executeAllActiveEnrichments': True, } } ) data = response.json() print(data) ``` ### Create Person (KYC) with Specific Integrations ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities/automatic \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taxId": "123.456.789-00", "country": "BR", "type": "person", "externalId": "customer_12345", "depth": 0, "autoExecuteIntegrations": { "enrichments": ["br_bdc_basic_data_enrichment"] } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities/automatic', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ taxId: '123.456.789-00', country: 'BR', type: 'person', externalId: 'customer_12345', depth: 0, autoExecuteIntegrations: { enrichments: ['br_bdc_basic_data_enrichment'] } }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://api.gu1.ai/entities/automatic', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'taxId': '123.456.789-00', 'country': 'BR', 'type': 'person', 'externalId': 'customer_12345', 'depth': 0, 'autoExecuteIntegrations': { 'enrichments': ['br_bdc_basic_data_enrichment'] } } ) data = response.json() ``` ### Create Argentine Company (No Shareholders Support) ```bash theme={null} curl -X POST http://api.gu1.ai/entities/automatic \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taxId": "30-12345678-9", "country": "AR", "type": "company", "depth": 0, "isClient": true, "riskMatrixId": "risk_matrix_uuid", "autoExecuteIntegrations": { "enrichments": ["ar_nosis_extended_verification_enrichment"] } }' ``` ### Create Brazilian Company with Shareholders and Selective Integrations ```bash theme={null} curl -X POST http://api.gu1.ai/entities/automatic \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taxId": "12.345.678/0001-90", "country": "BR", "type": "company", "depth": 2, "isClient": true, "riskMatrixId": "risk_matrix_uuid", "autoExecuteIntegrations": { "enrichments": ["br_cpfcnpj_complete_company_enrichment", "br_bdc_shareholders_enrichment"], "enrichmentGroupRefs": ["main_entity_group_slug"] }, "autoExecuteIntegrationsShareholders": { "enrichments": { "company": ["br_cpfcnpj_complete_company_enrichment"], "person": ["br_bdc_basic_data_enrichment"] }, "enrichmentGroupRefs": ["child_entities_group_slug"] } }' ``` ## Response Example ### Successful Company Creation with Shareholders ```json theme={null} { "success": true, "data": { "entity": { "id": "550e8400-e29b-41d4-a716-446655440000", "organizationId": "org_uuid", "type": "company", "name": "Tech Solutions LTDA", "taxId": "12345678000190", "countryCode": "BR", "status": "under_review", "riskScore": null, "entityData": { "company": { "legalName": "Tech Solutions LTDA", "tradeName": "Tech Solutions", "incorporationDate": "2020-01-15", "cnae": "6202-3/00", "cnaeDescription": "Development and licensing of customizable computer programs", "industry": "Development and licensing of customizable computer programs" } }, "createdAt": "2024-12-23T10:30:00.000Z", "updatedAt": "2024-12-23T10:30:00.000Z" }, "shareholders": [ { "id": "shareholder_1_uuid", "name": "João Silva", "taxId": "12345678900", "type": "person" }, { "id": "shareholder_2_uuid", "name": "Maria Santos", "taxId": "98765432100", "type": "person" } ], "summary": { "entitiesCreated": 3, "relationshipsCreated": 2, "errorsCount": 0 } }, "rulesResult": null } ``` For Brazilian companies, `entityData.company.cnae` and `cnaeDescription` contain the main economic activity from the normalized basic-data result. `industry` contains the same activity description for compatibility with existing entity profiles. ### Successful Person Creation ```json theme={null} { "success": true, "data": { "entity": { "id": "person_uuid", "organizationId": "org_uuid", "type": "person", "name": "João Silva", "taxId": "12345678900", "countryCode": "BR", "status": "under_review", "entityData": { "person": { "firstName": "João", "lastName": "Silva", "dateOfBirth": "1985-05-15" } }, "createdAt": "2024-12-23T10:30:00.000Z", "updatedAt": "2024-12-23T10:30:00.000Z" }, "relationships": [], "summary": { "entitiesCreated": 1, "relationshipsCreated": 0, "errorsCount": 0 } }, "rulesResult": null } ``` ## Error Responses ### 400 Bad Request - Invalid Tax ID ```json theme={null} { "success": false, "error": "Invalid CNPJ format for Brazil" } ``` ### 404 Not Found - Entity Not Found in Registry ```json theme={null} { "success": false, "error": "Entity not found in official registry", "details": { "taxId": "12.345.678/0001-90", "country": "BR", "registry": "Receita Federal" } } ``` ### 409 Conflict - Entity Already Exists Returned when the normalized `taxId` is already used by an **active** entity of a **different** type in the same organization (person vs company). Same-type matches are reused instead of failing. ```json theme={null} { "success": false, "error": { "code": "DUPLICATE_TAX_ID", "message": "This tax ID is already registered for a company in this organization (Entity ID: uuid).", "details": { "existingEntityId": "uuid", "existingEntityType": "company" } } } ``` ### 500 Internal Server Error ```json theme={null} { "success": false, "error": "Failed to create entity automatically", "details": { "message": "External API timeout" } } ``` ## Best Practices 1. **Use depth wisely**: Higher depth values (3-5) can create many entities and take longer to complete. Start with depth 0-1 for testing. 2. **Monitor WebSocket events**: While the API returns synchronously, WebSocket events are also emitted for real-time UI updates (`entity:creation-started`, `entity:creation-completed`, `entity:creation-failed`). 3. **Handle timeouts**: For complex hierarchies with high depth, the request can take several minutes. Configure appropriate HTTP timeout values in your client. 4. **Error handling**: Always check the `success` field and the `errors` object in the response. Some entities may be created successfully while others fail. 5. **Rate limiting**: Be mindful of rate limits when creating multiple entities in quick succession. The endpoint fetches data from external APIs which may have their own rate limits. ## Related Endpoints * [Create Entity Manually](/api-reference/entities/create) - Create entities with your own data * [Get Entity](/api-reference/entities/get) - Retrieve entity details * [List Entities](/api-reference/entities/list) - Query your entities # Entity Types Source: https://docs.gu1.ai/en/api-reference/entities/entity-types Available entity types in the universal entity system — in the gu1 universal entity model for KYC, KYB, and risk analysis, with examples for entity types use. ## Overview The Gu1 platform uses a universal entity system where different types of entities can be created, tracked, and monitored. All entities share the same base structure but have type-specific data fields. ## Core Entity Types ### Person Individual customers, employees, or any natural person. **Use Cases:** * Customer onboarding (KYC) * Employee screening * Beneficial owner identification * PEP screening **Example:** ```json theme={null} { "entityType": "person", "entityData": { "person": { "firstName": "John", "lastName": "Doe", "dateOfBirth": "1990-01-15", "nationality": "BR" } } } ``` ### Company Business entities, organizations, or legal entities. **Use Cases:** * Business verification (KYB) * Corporate due diligence * Supplier screening * Sanctions screening **Example:** ```json theme={null} { "entityType": "company", "entityData": { "company": { "legalName": "Tech Solutions Ltda", "registrationNumber": "12.345.678/0001-90", "incorporationDate": "2020-01-15" } } } ``` ## Financial Entity Types ### payment\_method Credit cards, bank accounts, wallets, or any payment instrument associated with a person or company. **Use Cases:** * Payment fraud detection * Card verification * Account monitoring * Transaction source tracking **Example:** ```json theme={null} { "entityType": "payment_method", "entityData": { "paymentMethod": { "type": "credit_card", "last4": "4242", "brand": "visa", "expiryMonth": "12", "expiryYear": "2025", "holderName": "John Doe", "issuerCountry": "BR" } } } ``` **Related Entities:** * Link to `person` or `company` owner * Link to `transaction` entities for usage history * Link to `device` for fraud detection ### account Bank accounts, wallets, or financial accounts. **Example:** ```json theme={null} { "entityType": "account", "entityData": { "account": { "accountNumber": "12345-6", "accountType": "checking", "bank": "Banco do Brasil", "currency": "BRL" } } } ``` ### card Specific card entities (alternative to payment\_method). ### transaction Financial transactions (can also use transactions table). ## Digital Entity Types ### device Devices used for transactions or account access. **Use Cases:** * Device fingerprinting * Fraud detection * Multi-device monitoring * Geographic anomaly detection **Example:** ```json theme={null} { "entityType": "device", "entityData": { "device": { "deviceId": "abc123", "type": "mobile", "os": "iOS", "osVersion": "17.1", "browser": "Safari", "ipAddress": "192.168.1.1" } } } ``` ### location Physical addresses, IP addresses, or GPS coordinates. **Example:** ```json theme={null} { "entityType": "location", "entityData": { "location": { "type": "physical_address", "street": "Av Paulista, 1000", "city": "São Paulo", "state": "SP", "country": "BR", "postalCode": "01310-100", "coordinates": { "lat": -23.561414, "lng": -46.655881 } } } } ``` ### document Documents associated with entities (IDs, passports, contracts). ## Compliance Entity Types ### alert System-generated alerts from rules engine (also tracked in alerts table). ### investigation Formal investigations created from alerts or manually. ### case Investigation cases for compliance review. ### incident Security or compliance incidents. ### review\_task Manual review tasks requiring human attention. ### kyc\_document KYC verification documents. ### compliance\_report Generated compliance reports. ### risk\_assessment Risk assessment results. ## Network Entity Types ### network Social networks, business networks, or relationship graphs. ### relationship Complex relationships between entities. ## How to Create Entities All entity types are created using the universal entities endpoint: ```bash theme={null} POST http://api.gu1.ai/entities ``` **Example: Create a payment method entity** ```bash theme={null} curl -X POST http://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entityType": "payment_method", "entityData": { "paymentMethod": { "type": "credit_card", "last4": "4242", "brand": "visa", "expiryMonth": "12", "expiryYear": "2025", "holderName": "John Doe" } }, "relationships": [ { "targetEntityId": "person-uuid-123", "relationshipType": "owns", "strength": 1.0 } ] }' ``` ## Entity Relationships Entities can be linked together using relationships: ```json theme={null} { "relationships": [ { "targetEntityId": "entity-uuid", "relationshipType": "owns|uses|manages|belongs_to", "strength": 0.0-1.0, "metadata": {} } ] } ``` **Common Relationship Patterns:** * `person` **owns** `payment_method` * `person` **uses** `device` * `company` **has** `person` (employee/director) * `payment_method` **used\_in** `transaction` * `person` **lives\_at** `location` ## See Also * [Create Entity](/en/api-reference/person/create) - Person entities * [Create Entity](/en/api-reference/company/create) - Company entities * [Entity Relationships](/en/api-reference/entities/materialize-relationships) - Managing relationships * [Analyze Entity](/en/api-reference/entities/analyze) - Risk analysis # Entities Overview Source: https://docs.gu1.ai/en/api-reference/entities/overview Use the gu1 Entities API to create, retrieve, and update companies, individuals, and transactions modeled across KYB, KYC, and AML workflows. ## What are Entities? Entities are the core objects in gu1 that represent the subjects of your risk analysis. An entity can be a company, an individual, a transaction, or any custom type relevant to your business. Each entity contains: * **Identity information** (name, external ID, type) * **Risk assessment** (risk score, status) * **Custom data** (flexible JSON for your specific fields) * **Relationships** (connections to other entities) * **Analysis results** (AI-powered insights) * **Timeline** (history of changes and events) ## Entity Types > [card] Company > > Corporate entities for KYB analysis > [card] Person > > Individual entities for KYC analysis > [card] Transaction > > Financial transactions for monitoring > [card] Custom > > Any custom entity type for your business ## Entity Lifecycle **1. Creation** Entity is created via API with basic information and optional custom data **2. Enrichment** Additional data is added through updates or integrations **3. Analysis** AI-powered risk analysis is automatically generated **4. Rule Evaluation** Risk rules are applied to calculate risk score and generate alerts **5. Investigation** Alerts trigger investigations for manual review **6. Resolution** Entity status is updated based on investigation outcomes ## Entity Status Person and company entities use the Postgres enum `entity_status`. There is **no forced transition graph**: after creation, a risk matrix label, a rule action (`updateEntityStatus`), an automation, or a manual PATCH can move the entity to **any** allowed status (unless `changeStatusManual` is locked). ### Default on create * If you omit `status` on create (manual or automatic), Gu1 sets **`under_review`**. * You may pass another value explicitly, for example `status: "not_started"`. That value replaces the default unless a later matrix/rule/automation changes it again. ### Canonical values | Status | Meaning | Typical use | | - | - | - | | **`not_started`** | Created, review/analysis **not started** yet | Opt-in equivalent of V2 `NOT_STARTED`. Pass on create when you do not want the default `under_review`. | | **`under_review`** | Under review / analysis in progress | **Default** on create. Also used when rules or labels require manual follow-up. | | **`pending_verification`** | Awaiting KYC/KYB completion | Identity or business verification still outstanding (docs/biometrics). Distinct from `under_review` (active compliance analysis). | | **`awaiting_information`** | Waiting on client data | The client was asked for information (typically onboarding documents by email) and has not finished submitting. Distinct from `pending_verification` (identity KYC/KYB). The onboarding agent sets this when the request is sent and restores the previous status after upload. | | **`active`** | Verified and operational (“approved”) | Client can operate normally after successful onboarding/review. | | **`inactive`** | Closed or dormant | End of relationship or long inactivity; historical queries only. | | **`suspended`** | Temporary hold | Operations blocked until resolved; reversible. | | **`blocked`** | Permanent high-risk block | Confirmed risk / sanctions / court order; operations blocked. | | **`rejected`** | Onboarding denied | Failed KYC/KYB or policy; no operations. Prefer `blocked` if the entity already had activity. | | **`expired`** | Data/documents expired | Refresh documentation required. | | **`deleted`** | Soft-deleted | Audit/archive; not used as a normal onboarding step. | > [!NOTE] > > There is **no** status named `approved`. Approval in product terms is **`active`**. **`pending_verification`** is a supported lifecycle status (awaiting KYC/KYB); **`awaiting_information`** is waiting on client data requested by operations (for example onboarding documents by email), not identity capture. Both are distinct from **`not_started`** (analysis not started) and **`under_review`** (compliance review in progress). Legacy V2 labels map as: `NOT_STARTED` → `not_started`, `IN_PROGRESS` → `under_review`, `APPROVED` → `active`, `DENIED` → `rejected`. ### Example flows (including risk matrix) There is **no mandatory intermediate status** between create and approval/denial. What happens depends on your matrix labels and rules: 1. **Create with `not_started`** → matrix/rules leave status unchanged → stays `not_started` until something updates it. 2. **Create with `not_started`** → matrix score band or rule sets `under_review` → needs manual analysis before you set `active` / `rejected` / etc. 3. **Create with `not_started`** → matrix/rule sets **`active`** directly → approved without passing through `under_review`. 4. **Create with `not_started`** → matrix/rule sets **`rejected`** or **`blocked`** directly → denied/blocked without an intermediate review status. 5. **Create with default `under_review`** → later matrix/manual change to `active` or `rejected`. Configure score→status bindings on risk matrix labels and/or `updateEntityStatus` rule actions to match your V2 behaviour. ### Operations guard Only **`blocked`**, **`suspended`**, and **`rejected`** block entity operations by default. `not_started`, `under_review`, `pending_verification`, and `awaiting_information` do **not** block operations the same way. ## Risk Scoring Every entity has a risk score (0-100) calculated based on: > [accordion] AI Analysis > > Machine learning models analyze entity behavior, patterns, and anomalies > [accordion] Rule-Based Scoring > > Custom rules evaluate specific conditions and assign risk points > [accordion] Compliance Checks > > Sanctions lists, PEPs, adverse media screening results > [accordion] Historical Behavior > > Transaction patterns, account activity, and changes over time > [accordion] Relationship Analysis > > Connected entities and their risk profiles **Risk Score Ranges:** * **0-25**: Low risk (green) * **26-50**: Medium risk (yellow) * **51-75**: High risk (orange) * **76-100**: Critical risk (red) ## Entity Data Structure ```json theme={null} { "id": "a7c4c07f-a1f5-49d6-8c17-1577d0787a2e", "type": "company", "name": "Acme Corporation", "externalId": "TAX123456789", "country": "US", "riskScore": 35, "status": "active", "entityData": { "industry": "Technology", "annual_revenue": 5000000, "employees": 50, "incorporation_date": "2010-01-15", "beneficial_owners": [ { "name": "John Doe", "ownership": 60, "isPEP": false } ], "compliance": { "kyb_completed": true, "sanctions_checked": true, "adverse_media_found": false } }, "organizationId": "org_abc123", "createdAt": "2025-10-03T12:00:00Z", "updatedAt": "2025-10-03T14:30:00Z" } ``` ## Core Fields | Field | Type | Required | Description | | - | - | - | - | | `type` | string | Yes | Entity type (company, person, transaction, custom) | | `name` | string | Yes | Entity name | | `externalId` | string | No | Your unique identifier for this entity | | `country` | string | No | ISO country code (e.g., "US", "UK") | | `entityData` | object | No | Flexible JSON for custom fields | | `riskScore` | number | No | Risk score 0-100 (auto-calculated) | | `status` | enum | No | Entity status (default: `"under_review"`) | ## Custom Entity Data The `entityData` field is a flexible JSON object where you can store any custom fields relevant to your use case: **KYB Example:** ```json theme={null} { "entityData": { "tax_id": "12-3456789", "industry": "Financial Services", "annual_revenue": 10000000, "employees": 150, "incorporation_date": "2015-03-20", "website": "https://example.com", "beneficial_owners": [...], "licenses": [...] } } ``` **KYC Example:** ```json theme={null} { "entityData": { "date_of_birth": "1985-06-15", "nationality": "US", "occupation": "Software Engineer", "annual_income": 120000, "identity_verified": true, "pep_status": false, "documents": [...] } } ``` **Transaction Example:** ```json theme={null} { "entityData": { "amount": 50000, "currency": "USD", "sender_account": "ACC123", "receiver_account": "ACC456", "transaction_type": "wire_transfer", "purpose": "Business payment", "timestamp": "2025-10-03T10:30:00Z" } } ``` ## Common Operations > [card] [Create Entity](/api-reference/entities/create) > > POST /entities - Create new entity > [card] [Get Entity](/api-reference/entities/get) > > GET /entities/:id - Retrieve entity details > [card] [List Entities](/api-reference/entities/list) > > GET /entities - Query entities with filters > [card] [Update Entity](/api-reference/entities/update) > > PUT /entities/:id - Update entity data > [card] [Delete Entity](/api-reference/entities/list) > > DELETE /entities/:id - Remove entity > [card] [Bulk Import](/en/api-reference/bulk-imports/import-entities) > > POST /entities/bulk - Import multiple entities ## Best Practices > [accordion] Use External IDs > > Always set `externalId` to your internal identifier for easy reconciliation and updates > [accordion] Consistent Entity Types > > Use consistent entity type values across your organization (e.g., "company" vs "corporate") > [accordion] Set Country Codes > > Always include ISO country codes for proper risk assessment and compliance checks > [accordion] Structure Entity Data > > Organize `entityData` with consistent field names and nested objects for complex data > [accordion] Track Updates > > Use the `updatedAt` timestamp to detect changes and sync with your systems > [accordion] Bulk Operations > > Use bulk import for creating multiple entities (>10) to improve performance ## Advanced Features ### AI-Powered Analysis Every entity can have AI-generated risk analysis: ```bash theme={null} POST /ai-analysis/entity/:entityId ``` Returns comprehensive analysis including: * Executive summary * Behavioral patterns * Risk factors identified * Recommendations * Confidence score [Learn more →](/api-reference/data-ingestion/overview) ### Entity Relationships Connect entities to show ownership, transactions, or other relationships: ```json theme={null} { "sourceEntityId": "entity_1", "targetEntityId": "entity_2", "relationshipType": "owns", "strength": 0.85 } ``` ### Document Attachments Attach documents (ID cards, licenses, contracts) to entities: ```bash theme={null} POST /documents/entity/:entityId/upload ``` [Learn more →](/en/api-reference/documents/upload) ## Example Workflows > [card] [KYB Onboarding](/use-cases/kyb/workflow) > > Complete company onboarding workflow > [card] [KYC Verification](/en/use-cases/kyc/complete-flow) > > Individual customer verification process > [card] [Transaction Monitoring](/en/use-cases/transaction-monitoring/fraud-detection) > > Real-time transaction screening > [card] [Ongoing Monitoring](/quickstart) > > Continuous entity monitoring setup ## Next Steps **1. Create Your First Entity** Follow the [Create Entity guide](/api-reference/entities/create) to add an entity **2. Setup Data Mapping** Use [Custom Schemas](/api-reference/data-ingestion/custom-schemas) for structured imports **3. Configure Rules** Apply risk rules through the dashboard to calculate risk scores **4. Monitor & Act** Setup webhooks to receive alerts when risk scores change # Tax ID Formats by Country Source: https://docs.gu1.ai/en/api-reference/entities/tax-id-formats Complete guide to accepted Tax ID formats for each country and entity type — in the gu1 universal entity model for KYC, KYB, and risk analysis. ## Overview This guide provides detailed information about the Tax ID formats accepted by the platform for each country and entity type. The system **automatically normalizes** all Tax IDs to the standard format for each country. > [!NOTE] > > **Important**: You can send Tax IDs with or without formatting characters (dots, dashes, slashes, spaces). The system will automatically clean and normalize them before validation. ## Birth date in tax IDs (rules) Some tax identifiers embed a birth date; others do not. This matters for **rule operators** `tax_id_age_*` (derive age from the field value and compare to a threshold). | Country | Format | Embeds birth date? | Rule operators | | - | - | - | - | | MX | RFC persona física (13 chars) | Yes (YYMMDD segment) | `tax_id_age_less_than`, `tax_id_age_greater_than_or_equal`, etc. | | MX | CURP (18 chars) | Yes (YYMMDD segment) | Same | | MX | RFC persona moral (12 chars) | Incorporation date, not person DOB | Not for person age rules | | AR | CUIT/CUIL/DNI | No (DNI is sequential, not DOB) | `tax_id_age_*` with `taxIdCountry: AR` — **estimated age** from DNI cohort (range midpoint; typical margin ±6–10 years). Does not use `dateOfBirth` or enrichment. | | BR | CPF | No | Use `dateOfBirth` or enrichment `age` | | CL | RUT persona | No | Use `dateOfBirth` or enrichment `age` | | CO / PE | Cédula / DNI | No | Use `dateOfBirth` or enrichment `age` | Applicable fields include `taxId`, `originTaxId`, `destinationTaxId`, `userEvent.taxId`, `userEvent.destinationCuit`, and custom paths such as `metadata.*` when the value is an MX RFC or CURP. *** ## 🇧🇷 Brazil (BR) ### Person - CPF **Document**: CPF (Cadastro de Pessoas Físicas) **Accepted digits**: **9, 10, or 11 digits** ```text Numbers only theme={null} ✅ 12345678901 (11 digits) ✅ 1234567890 (10 digits) ✅ 123456789 (9 digits) ``` ```text With format (dots and dashes) theme={null} ✅ 123.456.789-01 (11 digits formatted) ✅ 12.345.678-90 (10 digits formatted) ✅ 1.234.567-89 (9 digits formatted) ``` **Normalization format**: * 11 digits → `XXX.XXX.XXX-XX` * 10 digits → `XX.XXX.XXX-XX` * 9 digits → `X.XXX.XXX-XX` > [!TIP] > > **Can I send only numbers without dots or dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. > [!WARNING] > > **Important**: As of the latest update (January 2026), the system now accepts CPF with 9, 10, or 11 digits. Previously, only 10 or 11 digits were accepted. *** ### Company - CNPJ **Document**: CNPJ (Cadastro Nacional da Pessoa Jurídica) **Accepted digits**: **13 or 14 digits** ```text Numbers only theme={null} ✅ 12345678000190 (14 digits) ✅ 1234567000190 (13 digits) ``` ```text With format (dots, slash, and dashes) theme={null} ✅ 12.345.678/0001-90 (14 digits formatted) ✅ 1.234.567/0001-90 (13 digits formatted) ``` **Normalization format**: * 14 digits → `XX.XXX.XXX/XXXX-XX` * 13 digits → `X.XXX.XXX/XXXX-XX` > [!TIP] > > **Can I send only numbers without dots, slashes, or dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ## 🇦🇷 Argentina (AR) ### Person - DNI/CUIL #### DNI (Documento Nacional de Identidad) **Accepted digits**: **8 digits** ```text Numbers only theme={null} ✅ 12345678 (8 digits) ``` ```text With format (dots) theme={null} ✅ 12.345.678 (8 digits formatted) ``` **Normalization format**: 8 digits → `XX.XXX.XXX` *** #### CUIL (Código Único de Identificación Laboral) **Accepted digits**: **11 digits** ```text Numbers only theme={null} ✅ 20123456789 (11 digits) ``` ```text With format (dashes) theme={null} ✅ 20-12345678-9 (11 digits formatted) ``` **Normalization format**: 11 digits → `XX-XXXXXXXX-X` > [!TIP] > > **Can I send only numbers without dots or dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ### Company - CUIT **Document**: CUIT (Clave Única de Identificación Tributaria) **Accepted digits**: **11 digits** ```text Numbers only theme={null} ✅ 30123456789 (11 digits) ``` ```text With format (dashes) theme={null} ✅ 30-12345678-9 (11 digits formatted) ``` **Normalization format**: 11 digits → `XX-XXXXXXXX-X` > [!TIP] > > **Can I send only numbers without dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ## 🇲🇽 Mexico (MX) ### Person - RFC Persona Física **Document**: RFC (Registro Federal de Contribuyentes) **Accepted characters**: **13 alphanumeric characters** ```text Format Structure theme={null} ✅ AAAA######XXX └─┬─┘└──┬─┘└┬┘ │ │ └─ 3 characters (homoclave) │ └───── 6 numbers (date: YYMMDD) └────────── 4 letters (name/surnames) Example: GOCG850101A12 └─┬─┘└──┬─┘└┬┘ │ │ └─ A12 (homoclave) │ └───── 850101 (Jan 1, 1985) └────────── GOCG (García Ochoa Carlos Gerardo) ``` > [!WARNING] > > **Can I send only numbers without letters?** > > ❌ **NO** - RFC requires letters AND numbers in the specific format. You cannot send only numbers. *** ### Company - RFC Persona Moral **Document**: RFC (Registro Federal de Contribuyentes) **Accepted characters**: **12 alphanumeric characters** ```text Format Structure theme={null} ✅ AAA######XXX └┬┘└──┬─┘└┬┘ │ │ └─ 3 characters (homoclave) │ └───── 6 numbers (date: YYMMDD) └─────────3 letters (company name) Example: GOC850101A12 └┬┘└──┬─┘└┬┘ │ │ └─ A12 (homoclave) │ └───── 850101 (Jan 1, 1985) └─────────GOC (García Ochoa Company) ``` > [!WARNING] > > **Can I send only numbers without letters?** > > ❌ **NO** - RFC requires letters AND numbers in the specific format. *** ## 🇨🇱 Chile (CL) ### Person - RUT **Document**: RUT (Rol Único Tributario) **Accepted digits**: **7-8 digits + 1 verification digit** ```text Numbers and verifier theme={null} ✅ 12345678K (8 digits + verifier) ✅ 1234567K (7 digits + verifier) ✅ 123456789 (8 digits + numeric verifier) ``` ```text With format (dots and dash) theme={null} ✅ 12.345.678-K (8 digits formatted) ✅ 1.234.567-K (7 digits formatted) ``` **Normalization format**: * 8 digits → `XX.XXX.XXX-X` * 7 digits → `X.XXX.XXX-X` > [!NOTE] > > **Important**: The verification digit can be a number (0-9) or the letter **K** (uppercase or lowercase). > [!TIP] > > **Can I send only numbers without dots or dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ### Company - RUT Empresa **Document**: RUT (Rol Único Tributario) **Accepted digits**: **8-9 digits + 1 verification digit** ```text Numbers and verifier theme={null} ✅ 123456789K (9 digits + verifier) ✅ 12345678K (8 digits + verifier) ``` ```text With format (dots and dash) theme={null} ✅ 12.345.678-9 (8 digits formatted) ✅ 1.234.567-8 (7 digits formatted) ``` **Normalization format**: * 8 digits → `XX.XXX.XXX-X` * 7 digits → `X.XXX.XXX-X` > [!TIP] > > **Can I send only numbers without dots or dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ## 🇨🇴 Colombia (CO) ### Person - Cédula/NIT **Document**: Cédula de Ciudadanía or NIT **Accepted digits**: **6-10 digits** (variable length) ```text Numbers only (all valid) theme={null} ✅ 1234567890 (10 digits) ✅ 123456789 (9 digits) ✅ 12345678 (8 digits) ✅ 1234567 (7 digits) ✅ 123456 (6 digits) ``` > [!NOTE] > > **No special format** - Colombian personal IDs don't have a standard formatting pattern. > [!TIP] > > **Can I send only numbers?** > > ✅ **YES** - The system accepts pure numbers without any special formatting. *** ### Company - NIT **Document**: NIT (Número de Identificación Tributaria) **Accepted digits**: **9 digits + 1 verification digit** (10 total) ```text Numbers only theme={null} ✅ 1234567890 (10 digits - 9 + verifier) ``` ```text With format (dash) theme={null} ✅ 123456789-0 (9 digits + verifier with dash) ``` **Normalization format**: 10 digits → `XXXXXXXXX-X` > [!TIP] > > **Can I send only numbers without dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ## 🇵🇪 Peru (PE) ### Person - DNI **Document**: DNI (Documento Nacional de Identidad) **Accepted digits**: **8 digits** (fixed length) ```text Numbers only theme={null} ✅ 12345678 (8 digits) ``` > [!NOTE] > > **No special format** - Peruvian DNI doesn't use dots, dashes, or other formatting characters. > [!TIP] > > **Can I send only numbers?** > > ✅ **YES** - Only numbers, no special formatting required. *** ### Company - RUC **Document**: RUC (Registro Único de Contribuyentes) **Accepted digits**: **11 digits** (fixed length) ```text Numbers only theme={null} ✅ 20123456789 (11 digits) ``` > [!NOTE] > > **Format note**: The first 2 digits indicate the taxpayer type: > > * **20** = Companies (Personas Jurídicas) > * **10** = Natural persons with business activity > [!TIP] > > **Can I send only numbers?** > > ✅ **YES** - Only numbers, no special formatting required. *** ## 🇺🇾 Uruguay (UY) ### Person - CI **Document**: CI (Cédula de Identidad) **Accepted digits**: **7-8 digits** ```text Numbers only theme={null} ✅ 12345678 (8 digits) ✅ 1234567 (7 digits) ``` > [!NOTE] > > **No special format** - Uruguayan CI doesn't use formatting characters. > [!TIP] > > **Can I send only numbers?** > > ✅ **YES** - Only numbers, no special formatting required. *** ### Company - RUT **Document**: RUT (Registro Único Tributario) **Accepted digits**: **12 digits** (fixed length) ```text Numbers only theme={null} ✅ 212345670018 (12 digits) ``` > [!NOTE] > > **No special format** - Uruguayan RUT doesn't use formatting characters. > [!TIP] > > **Can I send only numbers?** > > ✅ **YES** - Only numbers, no special formatting required. *** ## 🇵🇾 Paraguay (PY) ### Person - CI **Document**: CI (Cédula de Identidad) **Accepted digits**: **6-8 digits** ```text Numbers only theme={null} ✅ 12345678 (8 digits) ✅ 1234567 (7 digits) ✅ 123456 (6 digits) ``` > [!NOTE] > > **No special format** - Paraguayan CI doesn't use formatting characters. > [!TIP] > > **Can I send only numbers?** > > ✅ **YES** - Only numbers, no special formatting required. *** ### Company - RUC **Document**: RUC (Registro Único de Contribuyentes) **Accepted digits**: **6-8 digits + 1 verification digit** ```text Numbers and verifier theme={null} ✅ 123456789 (8 digits + verifier) ✅ 12345678 (7 digits + verifier) ``` ```text With format (dash) theme={null} ✅ 12345678-9 (with dash) ``` **Normalization format**: With verifier → `XXXXXX-X` (minimum 6 digits) > [!TIP] > > **Can I send only numbers without dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ## 🇪🇸 Spain (ES) ### Person - DNI / NIE **Document**: DNI (nationals) or NIE (foreign residents) **Accepted formats**: * **DNI / NIF**: 8 digits + 1 letter (e.g. `12345678Z`) * **NIE**: `X`, `Y`, or `Z` + 7 digits + 1 letter (e.g. `X1234567L`) Letters are case-insensitive. The value is stored uppercase without separators. ### Company - CIF / NIF / NIE **Document**: CIF (incorporated companies), NIF (sole traders / autónomos), or NIE (foreign-resident autónomos) Spanish KYB entities of type `company` accept all three. Autónomos operate legally under a personal NIF or NIE, not a CIF. ```text CIF (legal person) theme={null} ✅ A12345678 (letter + 7 digits + letter or digit) ``` ```text NIF (autónomo) theme={null} ✅ 74387028Z (8 digits + letter) ``` ```text NIE (foreign resident) theme={null} ✅ X1234567L (X/Y/Z + 7 digits + letter) ``` **Normalization format**: uppercase alphanumeric, no punctuation. > [!WARNING] > > Sending a valid NIF such as `74387028Z` as `taxId` on an ES `company` must **not** return `INVALID_TAX_ID`. That identifier is valid for autónomos. *** ## 🇺🇸 United States (US) ### Company - EIN **Document**: EIN (Employer Identification Number) **Accepted digits**: **9 digits** (fixed length) ```text Numbers only theme={null} ✅ 123456789 (9 digits) ``` ```text With format (dash) theme={null} ✅ 12-3456789 (with dash) ``` **Normalization format**: 9 digits → `XX-XXXXXXX` > [!NOTE] > > **Format note**: EIN is issued by the IRS for business entities. The first 2 digits indicate the IRS campus where the EIN was issued. > [!TIP] > > **Can I send only numbers without dashes?** > > ✅ **YES** - The system accepts pure numbers and formats them automatically. *** ## 🇻🇪 Venezuela (VE) ### Company - RIF **Document**: RIF (Registro de Información Fiscal) **Accepted characters**: **1 letter + 9 digits** (10 total) ```text Letter + numbers theme={null} ✅ J123456789 (J/G/V/E/P + 9 digits) ``` ```text With format (dashes) theme={null} ✅ J-12345678-9 (with dashes) ``` **Normalization format**: Letter + 9 digits → `X-XXXXXXXX-X` **Valid letters** (first character): * **J** = Jurídico (Legal entities/companies) * **G** = Gobierno (Government entities) * **V** = Venezolano (Venezuelan natural persons) * **E** = Extranjero (Foreign persons) * **P** = Pasaporte (Passport) > [!TIP] > > **Can I send just the letter and numbers without dashes?** > > ✅ **YES** - The system accepts the format without dashes and formats it automatically. > [!WARNING] > > **Important**: The letter is **required**. You cannot send only numbers for Venezuelan RIF. *** ## 📊 Complete Summary Table | Country | Entity | Document | Digits/Format | Numbers Only | With Format | | - | - | - | - | - | - | | 🇧🇷 BR | Person | CPF | 9-11 digits | ✅ | ✅ dots and dashes | | 🇧🇷 BR | Company | CNPJ | 13-14 digits | ✅ | ✅ dots, slash, dashes | | 🇦🇷 AR | Person | DNI | 8 digits | ✅ | ✅ dots | | 🇦🇷 AR | Person | CUIL | 11 digits | ✅ | ✅ dashes | | 🇦🇷 AR | Company | CUIT | 11 digits | ✅ | ✅ dashes | | 🇲🇽 MX | Person | RFC PF | 13 alphanumeric | ❌ | ❌ Alphanumeric required | | 🇲🇽 MX | Company | RFC PM | 12 alphanumeric | ❌ | ❌ Alphanumeric required | | 🇨🇱 CL | Person | RUT | 7-8 + K | ✅ | ✅ dots and dash | | 🇨🇱 CL | Company | RUT | 8-9 + K | ✅ | ✅ dots and dash | | 🇨🇴 CO | Person | CC/NIT | 6-10 digits | ✅ | - | | 🇨🇴 CO | Company | NIT | 9 + 1 digits | ✅ | ✅ dash | | 🇵🇪 PE | Person | DNI | 8 digits | ✅ | - | | 🇵🇪 PE | Company | RUC | 11 digits | ✅ | - | | 🇺🇾 UY | Person | CI | 7-8 digits | ✅ | - | | 🇺🇾 UY | Company | RUT | 12 digits | ✅ | - | | 🇵🇾 PY | Person | CI | 6-8 digits | ✅ | - | | 🇵🇾 PY | Company | RUC | 6-8 + 1 digit | ✅ | ✅ dash | | 🇪🇸 ES | Person | DNI/NIE | 8 digits + letter, or X/Y/Z + 7 digits + letter | ❌ | ❌ Alphanumeric | | 🇪🇸 ES | Company | CIF/NIF/NIE | CIF, NIF (8 digits + letter), or NIE | ❌ | ❌ Alphanumeric | | 🇺🇸 US | Company | EIN | 9 digits | ✅ | ✅ dash | | 🇻🇪 VE | Company | RIF | 1 letter + 9 digits | ✅ | ✅ dashes | **Legend**: * ✅ = Format accepted * ❌ = Format not accepted * `-` = No special formatting *** ## ❓ Frequently Asked Questions > [accordion] Can I send the taxId with dots, dashes, and other formatting characters? > > ✅ **YES** - The system automatically cleans all formatting characters (dots, dashes, slashes, spaces) before validation. > > **Examples of accepted formats:** > > ``` > Brazil CPF: > ✅ 123.456.789-01 > ✅ 123-456-789-01 > ✅ 123 456 789 01 > ✅ 12345678901 > → All become: 123.456.789-01 > ``` > [accordion] Can I send the taxId with only numbers (no formatting)? > > ✅ **YES** - For most countries (except Mexico RFC and Venezuela RIF which require letters), you can send only numbers. > > **Exception countries (require letters):** > > * 🇲🇽 Mexico: RFC requires letters + numbers > * 🇻🇪 Venezuela: RIF requires 1 letter + numbers > [accordion] Does the system automatically normalize the format? > > ✅ **YES** - The system normalizes all taxIds to the standard format for each country. > > **Example for Brazil CPF:** > > ``` > You send: 12345678901 > Saved as: 123.456.789-01 > > You send: 123.456.789-01 > Saved as: 123.456.789-01 > > You send: 123-456-789-01 > Saved as: 123.456.789-01 > ``` > > **Example for Argentina CUIT:** > > ``` > You send: 30123456789 > Saved as: 30-12345678-9 > > You send: 30-12345678-9 > Saved as: 30-12345678-9 > ``` > [accordion] What happens if I send an invalid format? > > ❌ The system will reject the taxId with a validation error indicating: > > * The expected format > * The required number of digits > * Examples of valid formats > * The country-specific document name (CPF, CNPJ, CUIT, etc.) > > **Example error response:** > > ```json theme={null} > { > "success": false, > "error": { > "code": "VALIDATION_ERROR", > "message": "Invalid CPF format. Expected 9-11 digits.", > "details": { > "field": "taxId", > "taxIdName": "CPF", > "providedValue": "12345", > "expectedFormat": "9-11 digits (e.g., 123.456.789-01 or 12345678901)" > } > } > } > ``` > [accordion] Can I send a 9-digit CPF for Brazil? > > ✅ **YES** - As of the latest update (January 2026), the system accepts CPF with **9, 10, or 11 digits**. > > **Previously**: Only 10 or 11 digits were accepted. > > **Now accepted:** > > ``` > ✅ 123456789 (9 digits) → 1.234.567-89 > ✅ 1234567890 (10 digits) → 12.345.678-90 > ✅ 12345678901 (11 digits) → 123.456.789-01 > ``` > [accordion] Are verification digits validated? > > ⚠️ **Partial** - The system validates: > > ✅ **Format validation**: Checks that the Tax ID has the correct number of digits and structure > > ❌ **Checksum validation**: The system does NOT validate mathematical checksums (verification digits) for most countries > > **Why?** Checksum validation would reject valid but incorrectly typed IDs. Instead, the system relies on enrichment providers to validate the actual existence and validity of the document. > [accordion] What if my country is not listed? > > For countries not listed above, the system will accept Tax IDs without strict format validation. You can provide the Tax ID in any reasonable format, and it will be stored as-is without normalization. > > **Supported but not strictly validated countries include:** > > * 🇵🇹 Portugal (NIF) > * 🇪🇪 Estonia (Isikukood) > * 🇧🇴 Bolivia (NIT) > * 🇪🇨 Ecuador (RUC/Cédula) > * And others... *** ## 💡 Examples by Use Case ### Creating a Person in Brazil ```json With formatted CPF theme={null} { "type": "person", "name": "João Silva", "taxId": "123.456.789-01", "countryCode": "BR" } // ✅ System normalizes to: 123.456.789-01 ``` ```json With unformatted CPF theme={null} { "type": "person", "name": "João Silva", "taxId": "12345678901", "countryCode": "BR" } // ✅ System normalizes to: 123.456.789-01 ``` ```json With 9-digit CPF theme={null} { "type": "person", "name": "João Silva", "taxId": "123456789", "countryCode": "BR" } // ✅ System normalizes to: 1.234.567-89 ``` *** ### Creating a Company in Brazil ```json With formatted CNPJ theme={null} { "type": "company", "name": "Exemplo Ltda", "taxId": "12.345.678/0001-90", "countryCode": "BR" } // ✅ System normalizes to: 12.345.678/0001-90 ``` ```json With unformatted CNPJ theme={null} { "type": "company", "name": "Exemplo Ltda", "taxId": "12345678000190", "countryCode": "BR" } // ✅ System normalizes to: 12.345.678/0001-90 ``` *** ### Creating a Company in Argentina ```json With formatted CUIT theme={null} { "type": "company", "name": "Ejemplo SA", "taxId": "30-12345678-9", "countryCode": "AR" } // ✅ System normalizes to: 30-12345678-9 ``` ```json With unformatted CUIT theme={null} { "type": "company", "name": "Ejemplo SA", "taxId": "30123456789", "countryCode": "AR" } // ✅ System normalizes to: 30-12345678-9 ``` *** ### Creating a Person in Mexico ```json RFC with correct format theme={null} { "type": "person", "name": "García Ochoa Carlos Gerardo", "taxId": "GOCG850101A12", "countryCode": "MX" } // ✅ RFC must include letters ``` ```json ❌ INVALID - Numbers only theme={null} { "type": "person", "name": "García Ochoa Carlos Gerardo", "taxId": "850101012", "countryCode": "MX" } // ❌ ERROR: RFC requires letters AND numbers ``` *** ### Creating a Person in Chile ```json With formatted RUT theme={null} { "type": "person", "name": "María González", "taxId": "12.345.678-K", "countryCode": "CL" } // ✅ System normalizes to: 12.345.678-K ``` ```json With unformatted RUT theme={null} { "type": "person", "name": "María González", "taxId": "12345678K", "countryCode": "CL" } // ✅ System normalizes to: 12.345.678-K ``` ```json With numeric verifier theme={null} { "type": "person", "name": "María González", "taxId": "123456789", "countryCode": "CL" } // ✅ System normalizes to: 12.345.678-9 ``` *** ## 🔍 Best Practices > [card] Always Provide Country Code > > Always include the `countryCode` field when creating entities. This allows the system to apply the correct validation rules for that country. > [card] Send Clean Data > > While the system cleans formatting characters, sending clean data reduces processing time and potential errors. > [card] Handle Validation Errors > > Implement proper error handling for Tax ID validation errors. The error response includes helpful details about the expected format. > [card] Test Before Production > > Test your Tax ID inputs in the sandbox environment before going to production, especially for countries with strict format requirements. *** > [!NOTE] > > **Last updated**: January 28, 2026 • **Version**: 5.0 > > **Changes in this version**: > > * ✨ Added support for 9-digit CPF in Brazil > * 📋 Expanded coverage to include all Latin American countries > * 🔍 Added detailed format explanations and examples > * ❓ Enhanced FAQ section with common scenarios # Production & Sandbox Environments Source: https://docs.gu1.ai/en/api-reference/environments Understand how to use Production and Sandbox environments to test safely before going live — across gu1 production and sandbox accounts for safe testing. ## Overview gu1 provides **dual environments** for every organization, allowing you to test configurations and workflows safely before deploying to production: * **Production**: Your live environment with real data and integrations * **Sandbox**: A safe testing environment with simulated providers and mock data > [!NOTE] > > When you sign up, both environments are created automatically with the same team members and permissions. ## Understanding Organizations In gu1, an **Organization** represents your company account. Each organization has: * **Unique Organization ID**: A UUID that identifies your organization (e.g., `8e2f89ab-c216-4eb4-90eb-ca5d44499aaa`) * **Two Paired Environments**: Production and Sandbox, linked together but with separate data * **Team Members**: Users with specific roles (Owner, Admin, Member) synchronized across both environments * **Isolated Data**: All entities, rules, investigations, and configurations are scoped to the organization > [!NOTE] > > **Finding Your Organization IDs**: Navigate to [app.gu1.ai/api-keys](https://app.gu1.ai/api-keys) to see both your **Production** and **Sandbox** Organization IDs with convenient copy buttons. ### Why Organization IDs Matter When making API requests to [api.gu1.ai](https://api.gu1.ai), you **must** include the `X-Organization-ID` header to tell gu1 which organization and environment you're targeting: ```bash theme={null} # Production request (using Production Organization ID) curl -X GET https://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "X-Organization-ID: 8e2f89ab-c216-4eb4-90eb-ca5d44499aaa" # Sandbox request (using Sandbox Organization ID) curl -X GET https://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "X-Organization-ID: 86122d3c-6dfc-4afa-9c46-aaf841262c7e" ``` > [!WARNING] > > **Never hard-code Organization IDs in public repositories.** Store them as environment variables in your application. ## Key Differences > [card] Production Environment > > * Real provider integrations > * Actual costs for API calls > * Live data and transactions > * Blue "Live" badge in UI > * Full rate limits based on plan > [card] Sandbox Environment > > * Mock provider responses > * Zero costs (simulated data) > * Test data only > * Orange "Test" badge in UI > * Limited rate limits (100 req/h) > * 🧪 Global banner indicator ## How Environments Work **Important**: Production and Sandbox are **completely isolated** from each other: * **Separate Data**: Entities, rules, investigations, and configurations are independent * **Separate API Keys**: Each environment has its own API keys * **Same Team**: Team members and permissions are automatically synchronized * **No Cross-Talk**: Actions in Sandbox never affect Production data > [!NOTE] > > Think of them as two parallel universes: anything you do in Sandbox stays in Sandbox, and Production remains untouched. ## Switching Environments in the Dashboard You control which environment you're viewing through the **environment switcher** at [app.gu1.ai](https://app.gu1.ai): **1. Log in to app.gu1.ai** Access your dashboard at [app.gu1.ai](https://app.gu1.ai) **2. Locate the Switcher** Find the environment toggle in the top-right corner of the header **3. Click to Switch** Click to toggle between "Production" and "Sandbox" **4. Instant Update** The dashboard updates instantly to show data from the selected environment > [!WARNING] > > **Sandbox Indicator**: When in Sandbox mode, a global orange banner (🧪 Sandbox Mode) appears at the top of every page so you always know where you are. ## API Requests and Environments When making API requests to [api.gu1.ai](https://api.gu1.ai), the environment is determined by the **Organization ID** you send: ```bash theme={null} # This request goes to PRODUCTION (using Production Org ID) curl -X GET https://api.gu1.ai/entities \ -H "Authorization: Bearer gk_prod_..." \ -H "X-Organization-ID: 8e2f89ab-c216-4eb4-90eb-ca5d44499aaa" # This request goes to SANDBOX (using Sandbox Org ID) curl -X GET https://api.gu1.ai/entities \ -H "Authorization: Bearer gk_devel_..." \ -H "X-Organization-ID: 86122d3c-6dfc-4afa-9c46-aaf841262c7e" ``` > [!NOTE] > > The dashboard switcher at **app.gu1.ai** only affects what you see in the UI. For API requests to **api.gu1.ai**, use the correct Organization ID header. > [!TIP] > > **Finding Your Organization IDs**: Go to the **API Keys** page in your dashboard at [app.gu1.ai](https://app.gu1.ai) to see both Production and Sandbox Organization IDs with copy-to-clipboard buttons. ## API Keys per Environment API keys are **environment-specific** and their behavior depends on which **Organization** (Production or Sandbox) they belong to: ### Key Prefixes API key prefixes indicate the **infrastructure environment** where the gu1 platform is running, not whether the key belongs to a Production or Sandbox organization: * `gk_development_...` - Keys created when gu1 platform runs locally (development) * `gk_staging_...` - Keys created when gu1 platform runs on staging servers * `gk_production_...` - Keys created when gu1 platform runs on production servers (live gu1 platform) > [!WARNING] > > **Important**: The prefix does NOT indicate if your organization is Production or Sandbox. Both your Production and Sandbox organizations will have the same prefix based on where the gu1 platform is deployed. > [!NOTE] > > **Example**: When you create an API key at [app.gu1.ai](https://app.gu1.ai) (live platform), both your Production organization keys AND your Sandbox organization keys will have the `gk_production_...` prefix. The Organization ID in the `X-Organization-ID` header determines which data you access. ### Rate Limits Rate limits depend on the **Organization type**, not the key prefix: * **Sandbox Organizations**: Fixed at **100 requests/hour** (regardless of plan) * **Production Organizations**: Based on your plan: * Freemium: 60 req/min * Startup: 120 req/min * Growth: 600 req/min * Enterprise: 1,200+ req/min ### Provider Behavior * **Sandbox Organizations**: Always use mock providers (simulated responses, no real API costs) * **Production Organizations**: Use real provider integrations > [!NOTE] > > When creating an API key, the environment fields are **read-only** and automatically set to your current environment. The Organization ID determines whether it's a Sandbox or Production key. ## Mock Providers in Sandbox In Sandbox, all provider integrations return **simulated responses** instead of making real API calls: > [accordion] Compliance Screening (Sanctions, PEP, Adverse Media) > > * Returns varied risk profiles: clean, low, medium, high, critical > * Simulates realistic response times (100-2000ms) > * Includes mock person/entity data with aliases > * No actual costs incurred > [accordion] Webhooks > > * Webhooks are **simulated**, not sent to actual URLs > * All attempts are logged with simulated success/failure > * View logs in the Sandbox section > [accordion] Rule Actions > > * Actions like "Send email" or "Create task" are **simulated** > * All simulations are logged for review > * Allows testing complex workflows without side effects > [!TIP] > > Mock responses are designed to mimic production behavior closely, so your testing is as realistic as possible. ## Configuration Promotion Once you've tested and validated your configuration in Sandbox, you can **promote** it to Production: **1. Configure in Sandbox** Create and test your rules, field mappings, schemas, and data lists in Sandbox **2. Validate** Use the promotion validation endpoint to check for conflicts **3. Promote** Promote individual configurations or in bulk **4. Rollback if Needed** View promotion history and rollback if necessary > [!NOTE] > > Learn more about configuration promotion in the [Environments API Reference](/en/api-reference/environments). ## Best Practices > [accordion] Always Test in Sandbox First > > Before creating or modifying rules, test them thoroughly in Sandbox to avoid false positives or workflow issues in Production. > [accordion] Use Sandbox for Training > > Onboard new team members in Sandbox where they can experiment without affecting live data. > [accordion] Create Separate API Keys > > Use different API keys for Sandbox and Production in your codebase to avoid accidental cross-environment requests. > [accordion] Monitor the Global Banner > > The orange Sandbox banner is your reminder that you're in test mode. Always check before making important changes. > [accordion] Review Promotion History > > After promoting configurations, verify they work as expected in Production and check the promotion history for an audit trail. ## Sandbox Limitations > [!WARNING] > > Sandbox environments have the following limitations: > > * **Rate Limits**: 100 requests/hour (vs. plan-based in Production) > * **Data Retention**: Sandbox data may be cleared periodically > * **Expiry**: Depending on your plan, Sandbox may have an expiration date > * **Mock Data Only**: Cannot access real provider integrations by default ## FAQ > [accordion] Can I upgrade my Sandbox rate limits? > > Sandbox rate limits are fixed at 100 req/h to encourage testing in reasonable volumes. If you need higher limits for load testing, please contact support. > [accordion] Are team permissions synchronized? > > Yes! When you add or remove team members in either environment, the changes are automatically synchronized to the paired environment. > [accordion] Can I use real providers in Sandbox? > > By default, no. Sandbox uses mock providers to avoid costs. Contact support if you have a specific need to test real integrations in Sandbox. > [accordion] What happens when Sandbox expires? > > Depending on your plan, Sandbox may have an expiration date. You'll receive warnings before expiry, and you can extend or make it permanent by upgrading your plan. > [accordion] Can I delete my Sandbox? > > Sandbox and Production are paired environments. If you want to remove your Sandbox, please contact support. ## Related Resources > [card] [API Authentication](/en/api-reference/authentication) > > Learn how to authenticate with API keys > [card] [Configuration Promotion](/en/api-reference/environments) > > Promote configs from Sandbox to Production > [card] [Entities API](/en/api-reference/entities/overview) > > Create and manage entities in your environment > [card] [Rules Engine](/en/api-reference/rules) > > Configure risk rules per environment # Reactivate an onboarding request Source: https://docs.gu1.ai/en/api-reference/onboarding/document-reactivation Records that the business wants to continue a paused review. `POST /public/document-requests/reactivate` records the business intent and runs the onboarding analysis again. The signed token is delivered in the final notice link. The operation is idempotent: reusing the same link does not create duplicate runs. The entity remains inactive until an operator completes a later decision. ```json theme={null} { "token": "" } ``` A successful response returns `success: true`. An invalid token returns `401`; an expired token, `410`; and an unavailable request, `409`. # Change person external ID Source: https://docs.gu1.ai/en/api-reference/person/change-external-id POST /entities/change-external-id Assign a new external identifier to a person entity in gu1 with a mandatory audit reason; denormalized transaction and user event references are updated. ## Overview Use this endpoint when you need to change an entity's **external ID**. It is **not** possible to change `externalId` via `PATCH /entities/:id`, `PATCH /entities/by-external-id/:externalId`, or `PATCH /entities/by-tax-id/:taxId` — those routes ignore any `externalId` in the body. The operation: * Validates that the new external ID is unique within your organization. * Updates the entity row. * When the previous external ID was non-empty and differs from the new value, rewrites denormalized references on **transactions** (`origin_external_id` / `destination_external_id`) and **user events** (`entity_external_id`, including rows matched by `entity_id`). The entity row is saved immediately. The historical rows are updated in short batches, so a large history does not block the request. `externalIdPropagation` is `done` when that rewrite finished before the response, or `running` while it continues. New transactions already use the new external ID. Older rows still carrying the previous ID catch up while the field is `running`. You must send a **reason** (minimum 5 characters) for compliance and audit. The change is recorded via the unified audit service (metadata includes `externalIdChangeReason` and `source: change_external_id_endpoint`). ## Endpoint ``` POST https://api.gu1.ai/entities/change-external-id ``` ## Authentication ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Request Body Provide **exactly one** lookup field to identify the entity, plus the new value and reason. **entityId** `string (uuid)` Internal gu1 entity ID. Use this when you already store our UUID. **externalId** `string` **Lookup only**: the entity's **current** external ID (not the new value). Use when you identify entities by your own ID in daily operations. **taxId** `string` **Lookup only**: tax ID of an entity that **already has** a non-empty tax ID stored. Matching uses the same alphanumeric normalization as elsewhere (ignores punctuation). If more than one entity matches, the API returns `409` with code `AMBIGUOUS_TAX_ID_LOOKUP` — use `entityId` or `externalId` instead. **newExternalId** `string` *required* The new external identifier (trimmed on the server). Must not be in use by another entity in the organization. **reason** `string` *required* Audit reason, **at least 5 characters** (after trim), max 4000. ## Response **success** `boolean` `true` when the request completed successfully. **changed** `boolean` `false` if `newExternalId` equals the current value (no-op); `true` if the entity was updated. **entity** `object` Current entity snapshot after the operation. **externalIdPropagation** `string` Present when `changed` is `true`. `done` means historical transaction and user-event references already use the new external ID. `running` means the entity is updated and the historical rewrite is still in progress. New transactions use the new ID either way. ## Errors | HTTP | Code / shape | Meaning | | - | - | - | | 400 | `VALIDATION_ERROR`, `INVALID_LOOKUP` | Zero or more than one lookup field, or invalid body | | 404 | `NOT_FOUND` | No entity matches the lookup | | 409 | `DUPLICATE_EXTERNAL_ID` | Another entity already uses `newExternalId` | | 409 | `AMBIGUOUS_TAX_ID_LOOKUP` | Several entities share the normalized tax ID | ## Example ```bash theme={null} curl -X POST "https://api.gu1.ai/entities/change-external-id" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entityId": "550e8400-e29b-41d4-a716-446655440000", "newExternalId": "crm_customer_8842", "reason": "CRM migration — align ID with Salesforce Account Id" }' ``` Lookup by current external ID: ```json theme={null} { "externalId": "legacy_key_001", "newExternalId": "unified_key_001", "reason": "Consolidating duplicate external keys after data cleanup" } ``` Lookup by tax ID: ```json theme={null} { "taxId": "20-12345678-9", "newExternalId": "ar_person_maria_01", "reason": "Standardize external IDs for Argentina retail onboarding" } ``` # Create a person entity Source: https://docs.gu1.ai/en/api-reference/person/create POST /entities Create a new person with custom data — for person entities in the gu1 KYC and risk analysis platform, with examples for create use cases. ## Overview Creates a new person entity with the specified attributes. Person entities represent individual customers that you want to analyze for risk and compliance (KYC). ## Endpoint ``` POST http://api.gu1.ai/entities ``` ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Request Body **type** `string` *required* Must be `person` for creating a person entity **externalId** `string` Your unique identifier for this person in your system (optional but recommended) **name** `string` *required* Display name for the person **countryCode** `string` *required* ISO 3166-1 alpha-2 country code (e.g., "US", "BR", "AR") **taxId** `string` Tax identification number (validated based on country) > [!TIP] > > 📋 See [Tax ID Formats by Country](/en/api-reference/entities/tax-id-formats) for accepted formats and validation rules for each country. **operationalHours** `object | null` Optional root **operational hours** for KYT rules (`outside_entity_operational_hours` on `transactedAt`). Same shape as [Create entity](/en/api-reference/entities/create): `timezone` + `weekly` slots. **Timezone enum:** [Transaction Time Zone Enum](/en/api-reference/transactions/time-zone-enum). **attributes** `object` **Optional** - Custom attributes as key-value pairs for flexible metadata Use this for custom fields that don't fit in the standard schema (e.g., internal IDs, tags, flags) **entityData** `object` **Optional** - Person-specific data structure (see below) > [!NOTE] > > **When to use entityData?** > > * **Optional for basic entity creation** - You can create a person with just `type`, `name`, `taxId`, and `countryCode` > * **Required for enrichment and risk analysis** - If you want to run compliance checks, you'll need to provide relevant fields > * **Can be populated later** - You can create a minimal person first, then update it with full data before running risk analysis > > **Minimal Example:** > > ```json theme={null} > { > "type": "person", > "name": "John Doe", > "taxId": "12345678", > "countryCode": "US" > // No entityData needed for basic creation > } > ``` > > **Full Example (with KYC data):** > > ```json theme={null} > { > "type": "person", > "name": "John Doe", > "taxId": "12345678", > "countryCode": "US", > "entityData": { > "person": { > "firstName": "John", > "lastName": "Doe", > "dateOfBirth": "1980-01-15", > "email": "john@example.com", > "phone": "+1234567890" > } > } > } > ``` **registrationDate** `string` Person registration date in ISO 8601 datetime format (e.g., "2024-01-15T10:30:00Z") **isClient** `boolean` (default: false) Mark this person as a client/customer for tracking purposes **riskMatrixId** `string | string[]` One or more risk matrix UUIDs (legacy: a single UUID string). If provided, after creation the system evaluates this person **only** against active rules tied to those matrices (unless `skipRulesExecution` is true). Same semantics as `riskMatrixIds` when you send a single id as a string. See [Risk Matrix Execution](#risk-matrix-execution) below. **riskMatrixIds** `string[]` Preferred way to pass **multiple** matrices: ordered list of UUIDs belonging to your organization. When present and non-empty, it takes precedence over `riskMatrixId`. **skipRulesExecution** `boolean` (default: false) Skip automatic rules execution after person creation. Use this to create the entity first and manually trigger rules later. **status** `string` (default: under\_review) Initial status for the person. Options: * `active` - Person is active * `inactive` - Person is inactive * `not_started` - Analysis not started yet (optional initial state; default remains `under_review`) * `blocked` - Person is blocked * `under_review` - Person is under review (default) * `pending_verification` - Awaiting KYC/KYB completion * `awaiting_information` - Waiting on client data (e.g. onboarding documents requested by email) * `suspended` - Person is suspended * `expired` - Person record has expired * `deleted` - Soft deleted * `rejected` - Person was rejected **autoExecuteIntegrations** `object` Configure automatic execution of enrichments when creating the person. **Structure:** ```json theme={null} { "executeAllActiveEnrichments": false, "enrichments": [ "ar_renaper_data_enrichment", "ar_repet_person_enrichment", "global_gueno_sanctions_enrichment" ], "excludeEnrichments": [] } ``` **Properties:** * `executeAllActiveEnrichments` (boolean) - Run all active org enrichments * `enrichments` (string\[]) - Enrichment codes to run after create * `enrichmentGroupRefs` (string\[], optional) - Marketplace group slugs * `excludeEnrichments` (string\[], optional) - Codes to drop from the final set `*_check` codes are no longer part of the create contract; legacy payloads that send them are ignored at parse time. See [Person provider codes](/en/api-reference/integrations/person-provider-codes) and [Create entity](/en/api-reference/entities/create). **monitoring** `object` Optional. Only affects enrichments that support **ongoing monitoring** (today: **`global_gueno_sanctions_enrichment`**). Same semantics as [Create entity — monitoring](/en/api-reference/entities/create#example-gu1-sanctions-monitoring-on-create): `monitoring.main[code]` with `{ "watchlist": true }` (or legacy `true`), the code in `enrichments`, and org monitoring ON in Marketplace. ## Gu1 sanctions monitoring (person) ```json theme={null} { "type": "person", "externalId": "cust_screening_001", "name": "María González", "countryCode": "AR", "taxId": "27-12345678-1", "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "nationality": "AR" } }, "monitoring": { "main": { "global_gueno_sanctions_enrichment": true } }, "autoExecuteIntegrations": { "executeAllActiveEnrichments": false, "enrichments": ["global_gueno_sanctions_enrichment"] } } ``` ## Person Entity Data Structure The `entityData.person` object should contain: ```json theme={null} { "person": { "firstName": "string", "lastName": "string", "dateOfBirth": "YYYY-MM-DD", "nationality": "string", "occupation": "string", "income": number, "incomeCurrency": "string", "address": "string | object (see Address Format note)", "city": "string", "state": "string", "country": "string", "postalCode": "string", "email": "string", "phone": "string", "alternativePhone": "string", "idType": "national_id | passport | drivers_license | tax_id | other", "idNumber": "string", "isPep": boolean, "pepPosition": "string", "pepCountry": "string" } } ``` > [!NOTE] > > **Address Format**: The `address` field supports both formats: > > * **String format** (simple): `"Av. Paulista, 1000, São Paulo, SP, Brazil"` > * **Object format** (structured): > ```json theme={null} > { > "street": "Av. Paulista", > "number": "1000", > "complement": "Suite 200", > "neighborhood": "Bela Vista", > "city": "São Paulo", > "state": "SP", > "country": "Brazil", > "postalCode": "01310-100" > } > ``` *** ## Risk Matrix Execution You can automatically execute one or more risk matrices (KYC compliance rules) when creating a person by providing `riskMatrixId` or `riskMatrixIds`. ### How It Works 1. **Get your Risk Matrix ID(s)** from the gu1 dashboard (format: UUID) 2. **Include `riskMatrixId` or `riskMatrixIds` in your creation request** 3. The system will: * Create the person entity * Execute all KYC rules in the matrix * Calculate risk score * Generate compliance alerts if needed * Update person status based on results ### Example with Risk Matrix ```json theme={null} { "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskMatrixId": "550e8400-e29b-41d4-a716-446655440000", "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "occupation": "Software Engineer" } } } ``` ### Example with multiple risk matrices ```json theme={null} { "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskMatrixIds": [ "550e8400-e29b-41d4-a716-446655440000", "660e8400-e29b-41d4-a716-446655440001" ], "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15" } } } ``` ### Combined with enrichments and Gu1 monitoring Risk matrix + local enrichments + Gu1 sanctions watchlist (same pattern as [Create entity](/en/api-reference/entities/create#example-gu1-sanctions-monitoring-on-create)): ```json theme={null} { "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskMatrixId": "550e8400-e29b-41d4-a716-446655440000", "autoExecuteIntegrations": { "executeAllActiveEnrichments": false, "enrichments": [ "ar_renaper_data_enrichment", "ar_repet_person_enrichment", "global_gueno_sanctions_enrichment" ] }, "monitoring": { "main": { "global_gueno_sanctions_enrichment": { "watchlist": true } } }, "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15" } } } ``` **Flow:** 1. Person is created 2. Listed enrichments run (RENAPER, REPET, Gu1 sanctions) 3. Gu1 sanctions uses **op 1** (watchlist) only when `monitoring` and Marketplace allow it 4. Risk matrix rules evaluate collected data 5. Score and alerts per rules *** ## Response **success** `boolean` Indicates if the person was created successfully **entity** `object` The created person object including: * `id` - gu1's internal ID * `externalId` - Your external ID * `organizationId` - Your organization ID * `type` - Always "person" * `name` - Person name * `riskScore` - Initial risk score (0-100) * `status` - Person status * `entityData` - Person-specific data * `attributes` - Custom attributes * `createdAt` - Creation timestamp * `updatedAt` - Last update timestamp **rulesResult** `object` Result of rules execution (only present when rules ran, e.g. when **skipRulesExecution** is `false` and a risk matrix is configured), including: * **success** (boolean) - Whether rules executed successfully * **rulesTriggered** (number) - Number of rules that were triggered * **alerts** (array) - Alerts generated by rules * **riskScore** (number) - Final calculated risk score * **decision** (string) - Final decision (APPROVE, REJECT, HOLD, REVIEW\_REQUIRED) * **rulesExecutionSummary** (object) - Present when rules ran. See below for structure. **rulesExecutionSummary** `object` **At the root of the response** (same as transactions API). Same value as `rulesResult.rulesExecutionSummary`. **Only present when rules ran (e.g. skipRulesExecution is false).** Summary of which rules matched (hit) vs did not match (no hit), executed actions, and total score. Omitted when rules did not run. * **rulesHit** (array) - Rules whose conditions were met. Each item: **name**, **description**, **score**, **priority**, **category**, **status** (e.g. `active`, `shadow`), **conditions** (array of `{ field, value, operator? }`), **actions** (alerts, suggestion, status, assignedUser). * **rulesNoHit** (array) - Rules that were evaluated but conditions were not met. Same structure as rulesHit (includes configured actions, not executed). * **actionsExecuted** (object) - Aggregated executed actions across all rules that hit: **alerts**, **suggestion** (`BLOCK` | `SUSPEND` | `FLAG`, highest weight), **status** (entity status applied, if any), **assignedUser** (`{ userId }`, if any), **customKeys** (array of strings, optional) — custom action keys from matched rules; for integrations/workflows. * **totalScore** (number) - Sum of **score** of all rules that hit and are **not** in `shadow` status. ## Example Request ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "person", "externalId": "customer_12345", "name": "María González", "countryCode": "AR", "taxId": "20-12345678-9", "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "nationality": "AR", "occupation": "Software Engineer", "income": 85000, "incomeCurrency": "USD", "email": "maria.gonzalez@example.com", "phone": "+54 11 1234-5678", "address": "Av. Corrientes 1234", "city": "Buenos Aires", "state": "CABA", "country": "Argentina", "postalCode": "C1043" } }, "attributes": { "customerSince": "2024-01-15", "accountType": "premium" } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'person', externalId: 'customer_12345', name: 'María González', countryCode: 'AR', taxId: '20-12345678-9', entityData: { person: { firstName: 'María', lastName: 'González', dateOfBirth: '1985-03-15', nationality: 'AR', occupation: 'Software Engineer', income: 85000, incomeCurrency: 'USD', email: 'maria.gonzalez@example.com', phone: '+54 11 1234-5678', address: 'Av. Corrientes 1234', city: 'Buenos Aires', state: 'CABA', country: 'Argentina', postalCode: 'C1043' } }, attributes: { customerSince: '2024-01-15', accountType: 'premium' } }) }); const data = await response.json(); console.log(data.entity); ``` ```python Python theme={null} import requests response = requests.post( 'http://api.gu1.ai/entities', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'type': 'person', 'externalId': 'customer_12345', 'name': 'María González', 'countryCode': 'AR', 'taxId': '20-12345678-9', 'entityData': { 'person': { 'firstName': 'María', 'lastName': 'González', 'dateOfBirth': '1985-03-15', 'nationality': 'AR', 'occupation': 'Software Engineer', 'income': 85000, 'incomeCurrency': 'USD', 'email': 'maria.gonzalez@example.com', 'phone': '+54 11 1234-5678', 'address': 'Av. Corrientes 1234', 'city': 'Buenos Aires', 'state': 'CABA', 'country': 'Argentina', 'postalCode': 'C1043' } }, 'attributes': { 'customerSince': '2024-01-15', 'accountType': 'premium' } } ) entity = response.json()['entity'] print(entity) ``` ## Response Example ```json theme={null} { "success": true, "entity": { "id": "550e8400-e29b-41d4-a716-446655440000", "externalId": "customer_12345", "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa", "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskScore": 25, "status": "active", "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "nationality": "AR", "occupation": "Software Engineer", "income": 85000, "incomeCurrency": "USD", "email": "maria.gonzalez@example.com", "phone": "+54 11 1234-5678", "address": "Av. Corrientes 1234", "city": "Buenos Aires", "state": "CABA", "country": "Argentina", "postalCode": "C1043" } }, "attributes": { "customerSince": "2024-01-15", "accountType": "premium" }, "createdAt": "2024-10-03T14:30:00.000Z", "updatedAt": "2024-10-03T14:30:00.000Z" } } ``` ## Error Responses ### 400 Bad Request - Invalid Tax ID ```json theme={null} { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Invalid CUIT format. Please check the format and try again.", "details": { "field": "taxId", "taxIdName": "CUIT", "providedValue": "20-12345678-9" } }, "entity": null } ``` ### 400 Bad Request - Missing Required Fields ```json theme={null} { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Missing required fields for person creation", "details": { "missingFields": ["firstName", "lastName"], "requiredFields": ["firstName", "lastName", "dateOfBirth"], "countryCode": "AR" } }, "entity": null } ``` ### 409 Conflict - Duplicate Entity ```json theme={null} { "success": false, "error": { "code": "DUPLICATE_ENTITY", "message": "Entity with this external_id already exists", "details": { "field": "external_id", "value": "customer_12345", "constraint": "entities_organization_external_id_unique" } }, "entity": null } ``` ### 401 Unauthorized ```json theme={null} { "error": "Invalid or missing API key", "code": "INVALID_KEY" } ``` ## Next Steps After creating a person, you can: 1. [Get Person Details](/en/api-reference/person/get) - Retrieve complete person information 2. [List Persons](/en/api-reference/person/list) - Query your persons 3. [Update Person](/en/api-reference/person/update) - Modify person data 4. [Create KYC Validation](/en/use-cases/kyc/create-validation) - Start KYC verification process # Create a person automatically with enrichment Source: https://docs.gu1.ai/en/api-reference/person/create-automatic POST /entities/automatic Automatically create person with enriched data from registries — for person entities in the gu1 KYC and risk analysis platform, with examples for create. ## Overview The automatic person creation endpoint allows you to create persons by providing minimal information (tax ID and country). The system automatically: * Fetches person data from official registries * Enriches the person with additional information * Executes enrichments automatically This is ideal for KYC (Know Your Customer) processes where you want to onboard customers with complete information automatically. ## Endpoint ``` POST http://api.gu1.ai/entities/automatic ``` ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Request Body **taxId** `string` *required* Tax identification number of the person (e.g., CPF for Brazil, CURP for Mexico, CUIT for Argentina) > [!TIP] > > 📋 See [Tax ID Formats by Country](/en/api-reference/entities/tax-id-formats) for accepted formats and validation rules for each country. **country** `string` *required* ISO 3166-1 alpha-2 country code (e.g., "BR", "MX", "AR", "CL") **type** `string` *required* Must be set to `person` **externalId** `string` Your unique identifier for this person (optional, will be auto-generated if not provided) **isClient** `boolean` (default: false) Mark this person as a client/customer for tracking purposes **riskMatrixId** `string | string[]` One or more risk matrix UUIDs (legacy: a single UUID string). After creation, active rules tied to those matrices run (unless `skipRulesExecution` is true). **riskMatrixIds** `string[]` Preferred for **multiple** matrices: ordered UUID list. Takes precedence over `riskMatrixId` when non-empty. **skipRulesExecution** `boolean` (default: false) Skip automatic rules execution after person creation **status** `string` (default: under\_review) Initial status. Default `under_review`. Optional: `not_started`, `active`, `inactive`, `blocked`, `under_review`, `pending_verification`, `awaiting_information`, `suspended`, `expired`, `deleted`, `rejected`. See [Entities overview — Entity Status](/en/api-reference/entities/overview#entity-status). **operationalHours** `object | null` Optional **main entity** operational hours (`timezone` + `weekly`). Persisted on automatic creation the same as manual entity creation. Not applied to shareholders or relationships created via `depth`. **depth** `number` (default: 0) Depth of relationship extraction (0-5). Controls how many levels of relationships to automatically fetch and create. * `0`: No relationships (only main entity) * `1`: Direct relationships only * `2`: Relationships + their relationships * `3-5`: Additional levels (use with caution - can create many entities) > [!WARNING] > > **Brazil + `depth > 0` fails the entire request** if both discovery enrichments are missing. The API checks this **before** creating the person: it does **not** create the main entity and then skip related records. > > * **Required enrichments:** `br_bdc_related_companies_enrichment` **and** `br_bdc_related_persons_enrichment` — **both**. > * **Where:** in the **resolved** main-entity set (`autoExecuteIntegrations.enrichments`, or all **enabled** marketplace enrichments when `executeAllActiveEnrichments: true`), and **enabled** for the organization. > * **`executeAllActiveEnrichments: true` does not bypass this** if either is disabled or listed in `excludeEnrichments`. > * **`autoExecuteIntegrationsShareholders` does not satisfy** this check: it only controls enrichments **on children after they exist**. > > If you cannot run those enrichments, send **`depth: 0`** — the API creates **only the person**. **autoExecuteIntegrations** `object` Configure automatic execution of integrations for the main person entity. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes. **Type**: `object` (optional) **Properties:** * `executeAllActiveEnrichments` (boolean, optional, default: `false`) - Execute all active enrichment integrations * `enrichments` (array, optional, default: `[]`) - Array of specific enrichment provider codes to execute * `enrichmentGroupRefs` (array of strings, optional) - Marketplace enrichment group slugs (enrichments only). With `executeAllActiveEnrichments: false`, groups are resolved and merged with explicit `enrichments`. With `executeAllActiveEnrichments: true`, group refs are ignored (not resolved); explicit `enrichments` may still append after the active set. ```typescript theme={null} { executeAllActiveEnrichments?: boolean; // default: false enrichments?: ValidProviderCodesEnum[]; // default: [] enrichmentGroupRefs?: string[]; } ``` **Example:** ```json theme={null} { "executeAllActiveEnrichments": false, "enrichments": ["br_bdc_basic_data_enrichment"], "enrichmentGroupRefs": ["my_marketplace_group_slug"], } ``` **autoExecuteIntegrationsShareholders** `object` Configure automatic execution of integrations for discovered relationships. Useful when using `depth > 0`. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes. **Type**: `object` (optional) **Properties:** * `executeAllActiveEnrichments` (boolean, optional, default: `false`) - Execute all active enrichments on related entities * `enrichments` (object, optional) - Specific enrichments by entity type * `company` (array, default: `[]`) - Enrichments for company relationships * `person` (array, default: `[]`) - Enrichments for person relationships * `enrichmentGroupRefs` (array of strings, optional) - Same slugs as on the main object; applied to **both** `company` and `person` when `executeAllActiveEnrichments` is `false`. When `executeAllActiveEnrichments` is `true` on this object, group refs are ignored; explicit per-type `enrichments` may still append after each side’s active set. ```typescript theme={null} { executeAllActiveEnrichments?: boolean; enrichments?: { company?: ValidProviderCodesEnum[]; person?: ValidProviderCodesEnum[]; }; enrichmentGroupRefs?: string[]; } ``` **Example:** ```json theme={null} { "enrichments": { "person": ["br_cpfcnpj_complete_person_enrichment"], "company": ["br_cpfcnpj_complete_company_enrichment"] }, "enrichmentGroupRefs": ["related_entities_group_slug"] } ``` ## Required Enrichment Codes by Country > [!WARNING] > > The person is created only if **at least one** of these codes is **enabled** in Marketplace. The primary runs when it is active; otherwise the first enabled substitute runs: > > * Brazil: `br_bdc_basic_data_enrichment`, then `br_cpfcnpj_complete_person_enrichment`, `br_cpfcnpj_complete_person_9_enrichment` > * Argentina: `ar_nosis_extended_verification_enrichment`, then `ar_arca_contribuyente_enrichment` when that one is enabled > * Chile: `cl_baseapi_basic_data_person_enrichment` only > > If none is enabled, the response is HTTP 422 with `error.code` `BASIC_DATA_ENRICHMENT_REQUIRED`. `error.message` and `data.errors.creationFailed[].error` carry the same English sentence as the API log (`Activate one of: …`). Full body: [Automatic entity creation](/en/api-reference/entities/create-automatic#required-enrichment-codes-by-country). ### Brazil (BR) | Scenario | Required Enrichment Code(s) | Description | | - | - | - | | **Main entity** | `br_bdc_basic_data_enrichment` | Primary. Also accepted, in that order, when enabled: `br_cpfcnpj_complete_person_enrichment`, `br_cpfcnpj_complete_person_9_enrichment`. | | **Relationships** (`depth > 0`) | `br_bdc_related_companies_enrichment` **AND** `br_bdc_related_persons_enrichment` | **Both** required in the **resolved** main-entity set. If either is missing, disabled, or excluded → **the whole request fails**; the person is **not** created. | > [!WARNING] > > These codes must be on the **main person** resolved set, not only on `autoExecuteIntegrationsShareholders`. Missing either related enrichment is a hard fail, not a partial create. > [!NOTE] > > The API runs those enrichments on the **main** person to discover related people/companies. `autoExecuteIntegrationsShareholders` only controls what runs **on each child after it is created**. ### Argentina (AR) | Scenario | Required Enrichment Code | Description | | - | - | - | | **Main entity** | `ar_nosis_extended_verification_enrichment` | Primary. `ar_arca_contribuyente_enrichment` also satisfies the gate when it is enabled. | > [!WARNING] > > Argentina does **not** support automatic relationship creation yet. The `depth` parameter must be `0`. **customData** `object` **Optional** — Client values for the **main person** that must not be replaced by enrichments. Full reference (root vs `entityData`): [Automatic entity creation](/en/api-reference/entities/create-automatic). Fields: `name`, `email`, `phone`, `birthDate` → `entityData.person.dateOfBirth`, `address` → `entityData.person.address`, `gender` (enum: `M` | `F` | `male` | `female` | `other` | `unknown` — use `other` for non-binary; see [Create entity](/en/api-reference/entities/create#person-entity)). **Example:** ```json theme={null} { "taxId": "23450679909", "country": "AR", "type": "person", "customData": { "name": "JOHN DOE", "email": "client@company.com", "phone": "+541112345678", "birthDate": "1990-05-15", "address": "123 Main St, Buenos Aires" } } ``` **attributes** `object` **Optional** - Custom attributes as key-value pairs for the created entity. Applied only to the main entity (the person created), not to relationships/shareholders. Useful for business segments, tags, internal IDs, or any metadata you want to associate at creation time. **Structure:** object with string keys and values of any type (string, number, boolean, array, etc.). **Example:** ```json theme={null} { "businessSegments": ["retail", "fintech"], "source": "onboarding_web", "tags": ["vip", "high_volume"] } ``` ## Response **success** `boolean` Indicates if the person was created successfully **data** `object` Complete information about the creation: * `entity` (object) - The person created with all data * `summary` (object) - Creation summary * `errors` (object, optional) - Details of any errors **rulesResult** `object` Result of rules execution (only present when rules ran, e.g. when **skipRulesExecution** is `false` and a risk matrix is configured via `riskMatrixId` or `riskMatrixIds`), or null. When present, includes: * **success** (boolean) - Whether rules executed successfully * **rulesTriggered** (number) - Number of rules that were triggered * **alerts** (array) - Alerts generated by rules * **riskScore** (number) - Final calculated risk score * **decision** (string) - Final decision (APPROVE, REJECT, HOLD, REVIEW\_REQUIRED) * **rulesExecutionSummary** (object) - Present when rules ran. See below for structure. **rulesExecutionSummary** `object` **At the root of the response** (same as transactions API). Same value as `rulesResult.rulesExecutionSummary`. **Only present when rules ran (e.g. skipRulesExecution is false and risk matrix was executed).** Summary of which rules matched (hit) vs did not match (no hit), executed actions, and total score. Omitted when rules did not run. See [Rules Execution Summary](/en/api-reference/rules-execution-summary) for the full structure and a complete example. * **rulesHit** (array) - Rules whose conditions were met. Each item: **name**, **description**, **score**, **priority**, **category**, **status** (e.g. `active`, `shadow`), **conditions** (array of `{ field, value, operator? }`), **actions** (alerts, suggestion, status, assignedUser). * **rulesNoHit** (array) - Rules that were evaluated but conditions were not met. Same structure as rulesHit (includes configured actions, not executed). * **actionsExecuted** (object) - Aggregated executed actions across all rules that hit: **alerts**, **suggestion** (`BLOCK` | `SUSPEND` | `FLAG`, highest weight), **status** (entity status applied, if any), **assignedUser** (`{ userId }`, if any), **customKeys** (array of strings, optional) — custom action keys from matched rules; for integrations/workflows. * **totalScore** (number) - Sum of **score** of all rules that hit and are **not** in `shadow` status. ## Examples ### Create Person with All Active Integrations ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities/automatic \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taxId": "123.456.789-00", "country": "BR", "type": "person", "isClient": true, "autoExecuteIntegrations": { "executeAllActiveEnrichments": true, } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities/automatic', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ taxId: '123.456.789-00', country: 'BR', type: 'person', isClient: true, autoExecuteIntegrations: { executeAllActiveEnrichments: true, } }) }); const data = await response.json(); console.log('Person created:', data.data.entity); ``` ```python Python theme={null} import requests response = requests.post( 'http://api.gu1.ai/entities/automatic', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'taxId': '123.456.789-00', 'country': 'BR', 'type': 'person', 'isClient': True, 'autoExecuteIntegrations': { 'executeAllActiveEnrichments': True, } } ) data = response.json() print('Person created:', data['data']['entity']) ``` ### Create Person with Specific Integrations ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities/automatic \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taxId": "123.456.789-00", "country": "BR", "type": "person", "externalId": "customer_12345", "autoExecuteIntegrations": { "enrichments": ["br_bdc_basic_data_enrichment"] } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities/automatic', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ taxId: '123.456.789-00', country: 'BR', type: 'person', externalId: 'customer_12345', autoExecuteIntegrations: { enrichments: ['br_bdc_basic_data_enrichment'] } }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://api.gu1.ai/entities/automatic', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'taxId': '123.456.789-00', 'country': 'BR', 'type': 'person', 'externalId': 'customer_12345', 'autoExecuteIntegrations': { 'enrichments': ['br_bdc_basic_data_enrichment'] } } ) data = response.json() ``` ## Response Example ```json theme={null} { "success": true, "data": { "entity": { "id": "person_uuid", "organizationId": "org_uuid", "type": "person", "name": "João Silva", "taxId": "12345678900", "countryCode": "BR", "status": "under_review", "entityData": { "person": { "firstName": "João", "lastName": "Silva", "dateOfBirth": "1985-05-15", "nationality": "BR" } }, "createdAt": "2024-12-23T10:30:00.000Z", "updatedAt": "2024-12-23T10:30:00.000Z" }, "summary": { "entitiesCreated": 1, "relationshipsCreated": 0, "errorsCount": 0 } }, "rulesResult": null } ``` ## Error Responses ### 400 Bad Request - Invalid Tax ID ```json theme={null} { "success": false, "error": "Invalid CPF format for Brazil" } ``` ### 404 Not Found - Person Not Found in Registry ```json theme={null} { "success": false, "error": "Entity not found in official registry", "details": { "taxId": "123.456.789-00", "country": "BR", "registry": "Receita Federal" } } ``` ### 409 Conflict - Person Already Exists ```json theme={null} { "success": false, "error": "Entity with this tax ID already exists", "details": { "existingEntityId": "uuid", "taxId": "123.456.789-00" } } ``` ## Best Practices 1. **Error handling**: Always check the `success` field in the response 2. **Rate limiting**: Be mindful of rate limits when creating multiple persons 3. **Integration selection**: Choose specific integrations for better control over cost and performance ## Next Steps * [Get Person](/en/api-reference/person/get) - Retrieve person details * [Create Person Manually](/en/api-reference/person/create) - Create persons with your own data * [Create KYC Validation](/en/use-cases/kyc/create-validation) - Start identity verification # Get a person by ID Source: https://docs.gu1.ai/en/api-reference/person/get GET /entities/{id} Retrieve detailed information about a person — for person entities in the gu1 KYC and risk analysis platform, with examples for get use cases. ## Overview Retrieves complete details for a specific person, including current evaluation status and risk assessment. You can fetch a person in three ways: | Method | Endpoint | Use when | | - | - | - | | **By ID** | `GET /entities/{id}` | You have gu1's internal entity UUID | | **By external ID** | `GET /entities/by-external-id/{externalId}` | You use your own identifier (e.g. `customer_12345`) | | **By tax ID** | `GET /entities/by-tax-id/{taxId}` | You have the person's tax ID (e.g. CUIT, CPF) and want to look them up | All three return the same person object. The organization scope is enforced by your API key. ## Endpoints ### Get by ID ``` GET http://api.gu1.ai/entities/{id} ``` **id** `string` *required* The unique gu1 ID (UUID) of the person to retrieve ### Get by external ID ``` GET http://api.gu1.ai/entities/by-external-id/{externalId} ``` **externalId** `string` *required* Your external identifier for this person (e.g. the value you sent when creating the entity) ### Get by tax ID ``` GET http://api.gu1.ai/entities/by-tax-id/{taxId} ``` **taxId** `string` *required* The person's tax identification number (format depends on country: CUIT for Argentina, CPF for Brazil, etc.). Must match the entity's stored tax ID within your organization. ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Response Returns the complete person object with the following fields: **id** `string` gu1's internal entity ID **externalId** `string` Your external identifier for this person **organizationId** `string` Your organization ID **type** `string` Always "person" **name** `string` Person display name **taxId** `string` Tax identification number **countryCode** `string` ISO 3166-1 alpha-2 country code **riskScore** `number` Calculated risk score from 0 (low risk) to 100 (high risk) **riskFactors** `array` Array of identified risk factors contributing to the risk score **status** `string` Person status: `active`, `inactive`, `not_started`, `under_review`, `pending_verification`, `awaiting_information`, `rejected`, `suspended`, `blocked`, `expired`, `deleted` **kycVerified** `boolean` Whether KYC verification has been completed **kycProvider** `string` Name of the KYC provider used (if applicable) **kycData** `object` KYC verification data from the provider **entityData** `object` Person-specific data structure **attributes** `object` Custom attributes as key-value pairs **currentEvaluation** `object` Latest AI evaluation results (null if no evaluation exists) * `id` - Evaluation ID * `entityId` - Entity ID * `evaluationType` - Type of evaluation performed * `result` - Evaluation result * `confidence` - Confidence score (0-1) * `evaluatedAt` - Timestamp of evaluation **createdAt** `string` ISO 8601 timestamp of person creation **updatedAt** `string` ISO 8601 timestamp of last update **deletedAt** `string` ISO 8601 timestamp of soft deletion (null if not deleted) ## Examples ### Get by ID (UUID) ```bash cURL theme={null} curl -X GET http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const person = await response.json(); console.log(person); ``` ```python Python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', headers={ 'Authorization': 'Bearer YOUR_API_KEY' } ) person = response.json() print(person) ``` ### Get by external ID ```bash cURL theme={null} curl -X GET "http://api.gu1.ai/entities/by-external-id/customer_12345" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const externalId = 'customer_12345'; const response = await fetch( `http://api.gu1.ai/entities/by-external-id/${encodeURIComponent(externalId)}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const person = await response.json(); ``` ```python Python theme={null} import requests external_id = "customer_12345" response = requests.get( f"http://api.gu1.ai/entities/by-external-id/{external_id}", headers={"Authorization": "Bearer YOUR_API_KEY"} ) person = response.json() ``` ### Get by tax ID ```bash cURL theme={null} curl -X GET "http://api.gu1.ai/entities/by-tax-id/20-12345678-9" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const taxId = '20-12345678-9'; // e.g. CUIT (AR) const response = await fetch( `http://api.gu1.ai/entities/by-tax-id/${encodeURIComponent(taxId)}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const person = await response.json(); ``` ```python Python theme={null} import requests tax_id = "20-12345678-9" # e.g. CUIT (AR) response = requests.get( f"http://api.gu1.ai/entities/by-tax-id/{tax_id}", headers={"Authorization": "Bearer YOUR_API_KEY"} ) person = response.json() ``` ### Response Example ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "externalId": "customer_12345", "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa", "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskScore": 25, "riskFactors": [ { "factor": "new_customer", "impact": 15, "description": "Customer registered within last 30 days" }, { "factor": "high_income_occupation", "impact": -10, "description": "Professional occupation with verified income" } ], "status": "active", "kycVerified": true, "kycProvider": "gueno_ai", "kycData": { "verificationDate": "2024-10-03T14:30:00Z", "documentsVerified": ["national_id", "proof_of_address"], "livenessCheck": "passed", "overallStatus": "approved" }, "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "nationality": "AR", "occupation": "Software Engineer", "income": 85000 } }, "attributes": { "email": "maria.gonzalez@example.com", "phone": "+54 11 1234-5678", "customerSince": "2024-01-15", "accountTier": "premium" }, "currentEvaluation": { "id": "eval_abc123", "entityId": "550e8400-e29b-41d4-a716-446655440000", "evaluationType": "risk_assessment", "result": { "overallRisk": "low", "amlRisk": "low", "fraudRisk": "low", "complianceScore": 95, "recommendation": "approve" }, "confidence": 0.92, "evaluatedAt": "2024-10-03T14:35:00Z" }, "createdAt": "2024-10-03T14:30:00.000Z", "updatedAt": "2024-10-03T14:35:00.000Z", "deletedAt": null } ``` ## Error Responses ### 404 Not Found ```json theme={null} { "error": "Entity not found" } ``` ### 401 Unauthorized ```json theme={null} { "error": "Invalid or missing API key" } ``` ### 500 Internal Server Error ```json theme={null} { "error": "Failed to fetch entity" } ``` ## Use Cases ### KYC Verification Check Retrieve a customer to check their KYC status before approving a transaction: ```javascript theme={null} const person = await fetch(`http://api.gu1.ai/entities/${customerId}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }).then(res => res.json()); if (person.kycVerified && person.status === 'active') { // Proceed with transaction console.log('Customer verified, risk score:', person.riskScore); } else { // Request additional verification console.log('KYC verification required'); } ``` ### Risk Score Monitoring Check the current risk score and factors for ongoing monitoring: ```python theme={null} person = requests.get( f'http://api.gu1.ai/entities/{person_id}', headers={'Authorization': 'Bearer YOUR_API_KEY'} ).json() if person['riskScore'] > 70: # High risk - trigger enhanced due diligence print(f"High risk person detected: {person['riskScore']}") print("Risk factors:", person['riskFactors']) elif person['riskScore'] > 40: # Medium risk - apply additional monitoring print(f"Medium risk person: {person['riskScore']}") ``` ## Next Steps * [Update Person](/en/api-reference/person/update) - Modify person attributes * [List Persons](/en/api-reference/person/list) - Query multiple persons * [Create KYC Validation](/en/use-cases/kyc/create-validation) - Start identity verification # List persons Source: https://docs.gu1.ai/en/api-reference/person/list GET /entities Query and filter persons in your organization — for person entities in the gu1 KYC and risk analysis platform, with examples for list use cases. ## Overview Retrieves a list of persons with optional filtering by country, tax ID, or external ID. Returns up to 100 persons per request. ## Endpoint ``` GET http://api.gu1.ai/entities?type=person ``` ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Query Parameters **type** `string` *required* Must be set to `person` to retrieve only persons **country** `string` Filter by ISO 3166-1 alpha-2 country code (e.g., "US", "BR", "AR") **taxId** `string` Filter by exact tax identification number **externalId** `string` Filter by your external identifier ## Response **entities** `array` Array of person objects, each containing: * `id` - gu1's internal ID * `externalId` - Your external ID * `organizationId` - Your organization ID * `type` - Always "person" * `name` - Person name * `taxId` - Tax ID * `countryCode` - Country code * `riskScore` - Risk score (0-100) * `riskFactors` - Array of risk factors * `status` - Person status * `kycVerified` - KYC verification status * `kycProvider` - KYC provider name * `kycData` - KYC verification data * `entityData` - Person-specific data * `attributes` - Custom attributes * `createdAt` - Creation timestamp * `updatedAt` - Last update timestamp * `deletedAt` - Deletion timestamp (null if active) ## Examples ### List All Persons ```bash cURL theme={null} curl -X GET "http://api.gu1.ai/entities?type=person" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities?type=person', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }); const data = await response.json(); console.log(`Found ${data.entities.length} persons`); ``` ```python Python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities', headers={ 'Authorization': 'Bearer YOUR_API_KEY' }, params={'type': 'person'} ) data = response.json() print(f"Found {len(data['entities'])} persons") ``` ### Filter by Country ```bash cURL theme={null} curl -X GET "http://api.gu1.ai/entities?type=person&country=BR" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities?type=person&country=BR', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); console.log(`Found ${data.entities.length} Brazilian customers`); ``` ```python Python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities', headers={'Authorization': 'Bearer YOUR_API_KEY'}, params={ 'type': 'person', 'country': 'BR' } ) brazilian_customers = response.json()['entities'] print(f"Found {len(brazilian_customers)} Brazilian customers") ``` ### Find by External ID ```bash cURL theme={null} curl -X GET "http://api.gu1.ai/entities?type=person&externalId=customer_12345" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities?type=person&externalId=customer_12345', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); const person = data.entities[0]; // External IDs should be unique console.log('Found person:', person.name); ``` ```python Python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities', headers={'Authorization': 'Bearer YOUR_API_KEY'}, params={ 'type': 'person', 'externalId': 'customer_12345' } ) entities = response.json()['entities'] if entities: print(f"Found person: {entities[0]['name']}") ``` ### Find by Tax ID ```bash cURL theme={null} curl -X GET "http://api.gu1.ai/entities?type=person&taxId=20-12345678-9" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities?type=person&taxId=20-12345678-9', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); if (data.entities.length > 0) { console.log('Person found:', data.entities[0].name); } ``` ```python Python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities', headers={'Authorization': 'Bearer YOUR_API_KEY'}, params={ 'type': 'person', 'taxId': '20-12345678-9' } ) entities = response.json()['entities'] if entities: print(f"Person found: {entities[0]['name']}") ``` ## Response Example ```json theme={null} { "entities": [ { "id": "550e8400-e29b-41d4-a716-446655440000", "externalId": "customer_12345", "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa", "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskScore": 25, "riskFactors": [ { "factor": "new_customer", "impact": 15, "description": "Customer registered within last 30 days" } ], "status": "active", "kycVerified": true, "kycProvider": "gueno_ai", "kycData": { "verificationDate": "2024-10-03T14:30:00Z", "overallStatus": "approved" }, "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "nationality": "AR", "occupation": "Software Engineer", "income": 85000 } }, "attributes": { "email": "maria.gonzalez@example.com", "phone": "+54 11 1234-5678" }, "createdAt": "2024-10-03T14:30:00.000Z", "updatedAt": "2024-10-03T14:35:00.000Z", "deletedAt": null } ] } ``` ## Use Cases ### High Risk Customer Monitoring Query all persons and filter by risk score: ```javascript theme={null} const response = await fetch('http://api.gu1.ai/entities?type=person', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }); const data = await response.json(); const highRiskCustomers = data.entities.filter(e => e.riskScore > 70); console.log(`Found ${highRiskCustomers.length} high-risk customers requiring review`); highRiskCustomers.forEach(person => { console.log(`- ${person.name} (Risk: ${person.riskScore})`); }); ``` ### KYC Compliance Dashboard Get all unverified customers for compliance dashboard: ```python theme={null} import requests response = requests.get( 'http://api.gu1.ai/entities', headers={'Authorization': 'Bearer YOUR_API_KEY'}, params={'type': 'person'} ) persons = response.json()['entities'] unverified = [p for p in persons if not p['kycVerified']] print(f"Unverified customers: {len(unverified)}") for person in unverified: print(f"- {person['name']} ({person['externalId']})") ``` ## Error Responses ### 401 Unauthorized ```json theme={null} { "error": "Invalid or missing API key" } ``` ### 500 Internal Server Error ```json theme={null} { "error": "Failed to search entities" } ``` ## Limits * **Maximum results per request**: 100 persons * **Query parameters**: Can be combined for advanced filtering * **Rate limits**: Apply based on your plan tier ## Next Steps * [Get Person Details](/en/api-reference/person/get) - Retrieve complete information for a specific person * [Create Person](/en/api-reference/person/create) - Add new persons to your organization * [Update Person](/en/api-reference/person/update) - Modify person attributes # Update a person entity Source: https://docs.gu1.ai/en/api-reference/person/update PATCH /entities/{id} Update attributes and data for an existing person — for person entities in the gu1 KYC and risk analysis platform, with examples for update use cases. ## Overview Updates an existing person's attributes and data. This endpoint automatically triggers a re-evaluation of the person's risk score and emits real-time update events. ## Endpoint ``` PATCH http://api.gu1.ai/entities/{id} ``` ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Path Parameters **id** `string` *required* The gu1 ID of the person to update ## Request Body All fields are optional - only include the fields you want to update. **name** `string` Update the person's display name > [!NOTE] > > **External ID** cannot be updated with this endpoint. Use [Change external ID](/en/api-reference/person/change-external-id) (`POST /entities/change-external-id`) with a mandatory `reason` (min. 5 characters). **taxId** `string` Update tax identification number **countryCode** `string` Update ISO 3166-1 alpha-2 country code **attributes** `object` Update custom attributes (merges with existing attributes) **entityData** `object` Update person-specific data (merges with existing entityData) **status** `string` Update person status. Canonical values (see [Entities overview](/en/api-reference/entities/overview#entity-status)): * `not_started` - Created; analysis not started yet * `under_review` - Under review (also the default on create) * `pending_verification` - Awaiting KYC/KYB completion * `awaiting_information` - Waiting on client data (e.g. onboarding documents requested by email) * `active` - Verified / operational (product “approved”) * `inactive` - Closed or dormant * `suspended` - Temporarily suspended * `blocked` - Permanently blocked * `rejected` - Onboarding denied * `expired` / `deleted` - Expired data or soft-deleted **Note**: All status changes require a `reason` for audit. Operations are blocked for `suspended`, `blocked`, and `rejected`. **reason** `string` Required when changing status to `suspended`, `blocked`, or `rejected`. Provides audit trail for status changes. **riskMatrixId** `string` UUID of the risk matrix to associate with this person. Updates which rules are used for risk evaluation. ## Response **entity** `object` The updated person object with all current values **evaluation** `object` Newly created evaluation triggered by the update * `id` - Evaluation ID * `entityId` - Entity ID * `decision` - "PENDING" (awaiting processing) * `evaluationType` - "SYSTEM" * `reasons` - Array with "Re-evaluation triggered by attribute change" **previousEntity** `object` The person state before the update (for audit/comparison) > [!NOTE] > > This endpoint does **not** return `rulesResult` or `rulesExecutionSummary`. The rules engine is not executed on update; those fields are only returned by endpoints that run rules (create, create-automatic, enrich, refresh, analyze). ## Behavior When you update a person, the system automatically: 1. **Records the change** in the entity events log with a before/after snapshot 2. **Triggers re-evaluation** to recalculate risk score based on new data 3. **Emits real-time event** to notify connected clients of the update 4. **Maintains audit trail** for compliance and review purposes ## Examples ### Update Person Income and Occupation ```bash cURL theme={null} curl -X PATCH http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entityData": { "person": { "income": 95000, "occupation": "Senior Software Engineer" } } }' ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', { method: 'PATCH', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ entityData: { person: { income: 95000, occupation: 'Senior Software Engineer' } } }) } ); const result = await response.json(); console.log('Updated person:', result.entity); console.log('Re-evaluation triggered:', result.evaluation.id); ``` ```python Python theme={null} import requests response = requests.patch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'entityData': { 'person': { 'income': 95000, 'occupation': 'Senior Software Engineer' } } } ) result = response.json() print(f"Updated person: {result['entity']['name']}") print(f"Re-evaluation ID: {result['evaluation']['id']}") ``` ### Update Contact Information ```bash cURL theme={null} curl -X PATCH http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entityData": { "person": { "email": "new.email@example.com", "phone": "+54 11 9876-5432", "address": "Av. Libertador 2500, Buenos Aires" } } }' ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', { method: 'PATCH', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ entityData: { person: { email: 'new.email@example.com', phone: '+54 11 9876-5432', address: 'Av. Libertador 2500, Buenos Aires' } } }) } ); const result = await response.json(); console.log('Contact information updated'); ``` ```python Python theme={null} import requests response = requests.patch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'entityData': { 'person': { 'email': 'new.email@example.com', 'phone': '+54 11 9876-5432', 'address': 'Av. Libertador 2500, Buenos Aires' } } } ) result = response.json() print("Contact information updated") ``` ### Update Custom Attributes Only ```bash cURL theme={null} curl -X PATCH http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "attributes": { "accountTier": "premium", "loyaltyPoints": 15000, "lastLoginDate": "2024-10-03T14:00:00Z" } }' ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', { method: 'PATCH', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { accountTier: 'premium', loyaltyPoints: 15000, lastLoginDate: '2024-10-03T14:00:00Z' } }) } ); const result = await response.json(); console.log('Attributes updated:', result.entity.attributes); ``` ```python Python theme={null} import requests response = requests.patch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'attributes': { 'accountTier': 'premium', 'loyaltyPoints': 15000, 'lastLoginDate': '2024-10-03T14:00:00Z' } } ) result = response.json() print(f"Attributes updated: {result['entity']['attributes']}") ``` ### Update Person Status ```bash cURL theme={null} curl -X PATCH http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "status": "suspended", "reason": "Suspicious activity detected - pending investigation" }' ``` ```javascript JavaScript theme={null} const response = await fetch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', { method: 'PATCH', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'suspended', reason: 'Suspicious activity detected - pending investigation' }) } ); const result = await response.json(); console.log('Status updated to:', result.entity.status); ``` ```python Python theme={null} import requests response = requests.patch( 'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'status': 'suspended', 'reason': 'Suspicious activity detected - pending investigation' } ) result = response.json() print(f"Status updated to: {result['entity']['status']}") ``` ## Response Example ```json theme={null} { "entity": { "id": "550e8400-e29b-41d4-a716-446655440000", "externalId": "customer_12345", "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa", "type": "person", "name": "María González", "taxId": "20-12345678-9", "countryCode": "AR", "riskScore": 22, "riskFactors": [...], "status": "active", "kycVerified": true, "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "nationality": "AR", "occupation": "Senior Software Engineer", "income": 95000 } }, "attributes": { "email": "maria.gonzalez@example.com", "phone": "+54 11 1234-5678", "accountTier": "premium" }, "createdAt": "2024-10-03T14:30:00.000Z", "updatedAt": "2024-10-03T16:45:00.000Z", "deletedAt": null }, "evaluation": { "id": "eval_new_123", "entityId": "550e8400-e29b-41d4-a716-446655440000", "decision": "PENDING", "evaluationType": "SYSTEM", "reasons": ["Re-evaluation triggered by attribute change"], "rules": [], "entitySnapshot": {...} }, "previousEntity": { "id": "550e8400-e29b-41d4-a716-446655440000", "entityData": { "person": { "occupation": "Software Engineer", "income": 85000 } }, "updatedAt": "2024-10-03T14:35:00.000Z" } } ``` ## Error Responses ### 404 Not Found ```json theme={null} { "error": "Entity not found" } ``` ### 400 Bad Request - Invalid Data ```json theme={null} { "error": "Validation failed", "details": ["Invalid country code format"] } ``` ### 400 Bad Request - Missing Reason for Status Change ```json theme={null} { "error": "Changing status to 'suspended' requires a reason for audit purposes." } ``` ### 401 Unauthorized ```json theme={null} { "error": "Invalid or missing API key" } ``` ### 500 Internal Server Error ```json theme={null} { "error": "Failed to update entity" } ``` ## Use Cases ### Update After KYC Verification ```javascript theme={null} // After completing KYC verification, update the person const response = await fetch(`http://api.gu1.ai/entities/${personId}`, { method: 'PATCH', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { kycVerified: true, kycVerificationDate: new Date().toISOString(), kycProvider: 'manual_review' } }) }); ``` ### Progressive Profile Enrichment ```python theme={null} # Enrich customer profile as more information becomes available def update_customer_info(person_id, new_data): response = requests.patch( f'http://api.gu1.ai/entities/{person_id}', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'entityData': { 'person': new_data }, 'attributes': { 'lastDataUpdate': datetime.now().isoformat(), 'dataCompleteness': calculate_completeness(new_data) } } ) return response.json() ``` ## Best Practices 1. **Partial Updates**: Only send the fields you want to change - no need to send the entire person 2. **Monitor Re-evaluations**: Check the returned evaluation ID to track risk score recalculation 3. **Audit Trail**: Use the `previousEntity` in the response to maintain change history 4. **Real-time Sync**: Updates emit WebSocket events for real-time UI synchronization 5. **Idempotency**: Safe to retry - updates with same data will not create duplicate events ## Next Steps * [Get Person](/en/api-reference/person/get) - View updated person details * [List Persons](/en/api-reference/person/list) - Query persons with filters * [Upsert Person](/en/api-reference/person/upsert) - Create or update in one operation # Update a person by external ID Source: https://docs.gu1.ai/en/api-reference/person/update-by-external-id PATCH /entities/by-external-id/:externalId Update a person entity in gu1 using your external identifier rather than the internal UUID, helpful when integrating with existing customer databases. ## Overview This endpoint allows you to update an entity using your own external identifier instead of our internal UUID. This is useful when you don't store our UUIDs in your system and only track your own external IDs. The functionality is identical to `PATCH /entities/:id`, but uses `externalId` as the identifier. ## Path Parameters **externalId** `string` *required* Your unique external identifier for the entity ## Request Body **name** `string` Entity name (person full name or company name) **taxId** `string` Tax identification number (SSN, EIN, VAT, RFC, etc.) **nationality** `string | null` Root-level nationality (ISO 3166-1 alpha-2 when persisted). Omit to leave unchanged; send `null` to clear. Updating `nationality` inside `entityData` in the same request may recalculate the root field. **status** `string` Entity status. Canonical values (see [Entities overview](/en/api-reference/entities/overview#entity-status)): * `not_started`, `under_review`, `pending_verification`, `awaiting_information`, `active`, `inactive`, `suspended`, `blocked`, `rejected`, `expired`, `deleted` **Note**: All status changes require a `reason` for audit. Operations are blocked for `blocked`, `suspended`, and `rejected`. **reason** `string` Required when changing status to `blocked`, `suspended`, or `rejected`. Provides audit trail for the status change. **riskMatrixId** `string (uuid)` Risk matrix ID to assign to this entity. The risk matrix determines which rules will be executed for risk evaluation. **entityData** `object` Entity-specific data structure. For person entities, use `entityData.person`. For company entities, use `entityData.company`. **Person fields**: * `firstName`: First name * `lastName`: Last name * `middleName`: Middle name * `dateOfBirth`: Date of birth (YYYY-MM-DD) * `nationality`: Nationality (ISO 3166-1 alpha-2) * `email`: Email address * `phone`: Phone number * `address`: Address object (street, city, state, country, postalCode) **Company fields**: * `legalName`: Legal company name * `tradingNames`: Array of trading names * `registrationNumber`: Company registration number * `incorporationDate`: Date of incorporation (YYYY-MM-DD) * `industry`: Industry/sector * `employees`: Number of employees * `website`: Company website * `address`: Address object **attributes** `object` Custom key-value attributes for flexible entity data storage **metadata** `object` System metadata (usually set by the system, but can be updated) ## Immutable Fields The following fields **cannot** be changed after entity creation: * `type`: Entity type (person or company) * `countryCode`: Entity country code (ISO 3166-1 alpha-2) ## Response Returns the updated entity object. **entity** `object` The updated entity object with all current values **evaluation** `object | null` Evaluation object (currently null - re-evaluation feature temporarily disabled) **previousEntity** `object` The entity state before the update (for audit purposes) ## Example Request ```bash theme={null} curl -X PATCH https://api.gueno.ai/entities/by-external-id/customer-12345 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "John Michael Doe", "status": "active", "entityData": { "person": { "firstName": "John", "middleName": "Michael", "lastName": "Doe", "email": "john.doe@example.com", "phone": "+1-555-0123" } }, "riskMatrixId": "matrix-uuid-here" }' ``` ## Example Response ```json theme={null} { "entity": { "id": "entity-uuid", "organizationId": "org-uuid", "externalId": "customer-12345", "type": "person", "name": "John Michael Doe", "taxId": "123-45-6789", "countryCode": "US", "nationality": "US", "status": "active", "riskScore": "35.00", "riskMatrixId": "matrix-uuid-here", "entityData": { "person": { "firstName": "John", "middleName": "Michael", "lastName": "Doe", "email": "john.doe@example.com", "phone": "+1-555-0123" } }, "createdAt": "2025-12-20T10:00:00Z", "updatedAt": "2025-12-24T15:30:00Z" }, "evaluation": null, "previousEntity": { "id": "entity-uuid", "name": "John Doe", "status": "pending", ... } } ``` ## Status Change with Reason When changing status to `blocked`, `suspended`, or `rejected`, you **must** provide a reason: ```bash theme={null} curl -X PATCH https://api.gueno.ai/entities/by-external-id/customer-12345 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "status": "blocked", "reason": "Failed sanctions screening - OFAC match detected" }' ``` ## Use Cases ### 1. Update Customer Information Update customer data from your CRM or user management system: ```json theme={null} { "name": "Jane Smith-Johnson", "entityData": { "person": { "lastName": "Smith-Johnson", "email": "jane.smithjohnson@example.com", "address": { "street": "456 New St", "city": "Seattle", "state": "WA", "country": "US", "postalCode": "98101" } } } } ``` ### 2. Assign Risk Matrix Assign or change the risk matrix for an entity: ```json theme={null} { "riskMatrixId": "high-risk-matrix-uuid" } ``` After updating the risk matrix, you should trigger a re-analysis using `POST /entities/:entityId/analyze` to re-evaluate the entity with the new rules. ### 3. Block Entity After Investigation Block an entity after compliance investigation: ```json theme={null} { "status": "blocked", "reason": "Investigation revealed connections to sanctioned entities" } ``` ### 4. Sync Company Data Update company information from business registry: ```json theme={null} { "entityData": { "company": { "employees": 250, "revenue": 50000000, "website": "https://company-new-domain.com" } } } ``` ## Events and Webhooks ### Real-time Events After a successful update, the following real-time event is emitted via WebSocket: ```json theme={null} { "event": "entity.updated", "entityId": "entity-uuid", "externalId": "customer-12345", "updatedFields": ["name", "entityData"], "previousValues": {...}, "newValues": {...} } ``` ### Webhook Triggers If you change **only** the `status` field (without other field changes), a webhook is triggered: **Event**: `entity.status_changed` ```json theme={null} { "event": "entity.status_changed", "entityId": "entity-uuid", "externalId": "customer-12345", "oldStatus": "active", "newStatus": "blocked", "reason": "Failed sanctions screening", "changedBy": "user-uuid", "timestamp": "2025-12-24T15:30:00Z" } ``` **Note**: If you update status **along with other fields**, the webhook is NOT triggered (assumes bulk entity edit rather than standalone status change). ## Audit Trail Every entity update creates an `ATTRIBUTE_CHANGED` event in the entity events log with: * Before state (all changed fields) * After state (all changed fields) * User who made the change * Timestamp * Source (API, dashboard, etc.) Query audit trail: ```bash theme={null} GET /entity-events?entityId=:entityId&eventType=ATTRIBUTE_CHANGED ``` ## Error Responses **404 Not Found** `error` Entity with the specified `externalId` not found in your organization ```json theme={null} { "error": "Entity not found" } ``` **400 Bad Request** `error` Invalid request data or validation error ```json theme={null} { "error": "Changing status to 'blocked' requires a reason for audit purposes." } ``` **400 Bad Request** `error` Attempting to change immutable fields ```json theme={null} { "error": "Field 'type' cannot be changed after entity creation" } ``` ## Best Practices 1. **Always Set External ID on Creation**: Set `externalId` when creating entities via `POST /entities` to enable updates by external ID. 2. **Use for System Integration**: This endpoint is ideal for integrations where you sync data from external systems (CRM, ERP, etc.) using your own IDs. 3. **Provide Reasons for Status Changes**: Always include meaningful reasons when blocking, suspending, or rejecting entities for compliance audit trail. 4. **Re-analyze After Risk Matrix Change**: After assigning a new risk matrix, trigger `POST /entities/:entityId/analyze` to re-evaluate with new rules. 5. **Handle 404 Gracefully**: If entity not found by external ID, you may need to create it first using `POST /entities`. 6. **Batch Updates**: For updating multiple entities, call this endpoint concurrently with different external IDs for better performance. ## Related Endpoints * [Create Entity](/en/api-reference/entities/create) - Create new entity * [Update Entity by UUID](/en/api-reference/entities/update) - Update using internal UUID * [Get Entity](/en/api-reference/entities/get) - Retrieve entity details * [Analyze Entity](/en/api-reference/entities/analyze) - Trigger risk analysis # Upsert a person entity Source: https://docs.gu1.ai/en/api-reference/person/upsert PUT /entities/upsert Create or update a person entity in gu1 with duplicate detection on external ID, national ID, email, and phone to avoid duplicate KYC records. ## Overview The upsert endpoint intelligently creates a new person or updates an existing one based on configurable duplicate detection strategies. It automatically handles conflicts and prevents duplicate records using exact matching, fuzzy matching, or AI-powered similarity detection. ## Endpoint ``` PUT http://api.gu1.ai/entities/upsert ``` ## Authentication Requires a valid API key in the Authorization header: ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` ## Request Body **entity** `object` *required* The person data (same structure as Create Person endpoint) **options** `object` Configuration options for upsert behavior **options.conflictResolution** `enum` How to handle conflicts when an existing person is found: * `source_wins` - New data overwrites existing data * `target_wins` - Keep existing data, ignore new data * `manual_review` - Flag for manual review without updating * `smart_merge` (default) - Intelligently merge both datasets **options.deduplicationStrategy** `enum` Strategy for detecting duplicate persons: * `exact_match` - Match by externalId and taxId (case-insensitive) * `fuzzy_match` - Similarity matching on name and taxId (80% threshold) * `ai_similarity` - AI-powered semantic similarity detection * `hybrid` (recommended) - Exact match with fuzzy fallback **options.createRelationships** `boolean` (default: true) Whether to automatically create relationships between entities ## Response **success** `boolean` Indicates if the operation succeeded **action** `string` The action performed: `created` or `updated` **entity** `object` The final person state after upsert **previousEntity** `object` The person state before update (null if newly created) **confidence** `number` Confidence score (0-1) for the duplicate detection match **reasoning** `string` Explanation of why the person was created/updated **conflicts** `array` Array of field-level conflicts detected during merge (if any) ## Examples ### Simple Upsert (Default Behavior) ```bash cURL theme={null} curl -X PUT http://api.gu1.ai/entities/upsert \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entity": { "type": "person", "externalId": "customer_12345", "name": "María González", "countryCode": "AR", "taxId": "20-12345678-9", "entityData": { "person": { "firstName": "María", "lastName": "González", "dateOfBirth": "1985-03-15", "occupation": "Software Engineer", "income": 85000 } } } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://api.gu1.ai/entities/upsert', { method: 'PUT', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ entity: { type: 'person', externalId: 'customer_12345', name: 'María González', countryCode: 'AR', taxId: '20-12345678-9', entityData: { person: { firstName: 'María', lastName: 'González', dateOfBirth: '1985-03-15', occupation: 'Software Engineer', income: 85000 } } } }) }); const result = await response.json(); console.log(`Action: ${result.action}`); // 'created' or 'updated' console.log(`Confidence: ${result.confidence}`); ``` ```python Python theme={null} import requests response = requests.put( 'http://api.gu1.ai/entities/upsert', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'entity': { 'type': 'person', 'externalId': 'customer_12345', 'name': 'María González', 'countryCode': 'AR', 'taxId': '20-12345678-9', 'entityData': { 'person': { 'firstName': 'María', 'lastName': 'González', 'dateOfBirth': '1985-03-15', 'occupation': 'Software Engineer', 'income': 85000 } } } } ) result = response.json() print(f"Action: {result['action']}") print(f"Confidence: {result['confidence']}") ``` ### Upsert with Fuzzy Matching ```bash cURL theme={null} curl -X PUT http://api.gu1.ai/entities/upsert \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entity": { "type": "person", "externalId": "customer_new_123", "name": "Maria Gonzales", "countryCode": "AR", "taxId": "20-12345678-9", "entityData": { "person": { "firstName": "Maria", "lastName": "Gonzales" } } }, "options": { "deduplicationStrategy": "fuzzy_match", "conflictResolution": "smart_merge" } }' ``` ```javascript JavaScript theme={null} // Will match "Maria Gonzales" with existing "María González" // due to 80%+ similarity threshold const response = await fetch('http://api.gu1.ai/entities/upsert', { method: 'PUT', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ entity: { type: 'person', externalId: 'customer_new_123', name: 'Maria Gonzales', // Slight variation in spelling countryCode: 'AR', taxId: '20-12345678-9', entityData: { person: { firstName: 'Maria', lastName: 'Gonzales' } } }, options: { deduplicationStrategy: 'fuzzy_match', conflictResolution: 'smart_merge' } }) }); const result = await response.json(); console.log(`Matched with confidence: ${result.confidence}`); console.log(`Reasoning: ${result.reasoning}`); ``` ```python Python theme={null} import requests # Will match "Maria Gonzales" with existing "María González" response = requests.put( 'http://api.gu1.ai/entities/upsert', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'entity': { 'type': 'person', 'externalId': 'customer_new_123', 'name': 'Maria Gonzales', # Slight variation 'countryCode': 'AR', 'taxId': '20-12345678-9', 'entityData': { 'person': { 'firstName': 'Maria', 'lastName': 'Gonzales' } } }, 'options': { 'deduplicationStrategy': 'fuzzy_match', 'conflictResolution': 'smart_merge' } } ) result = response.json() print(f"Matched with confidence: {result['confidence']}") print(f"Reasoning: {result['reasoning']}") ``` ## Response Examples ### Created New Person ```json theme={null} { "success": true, "action": "created", "entity": { "id": "550e8400-e29b-41d4-a716-446655440000", "externalId": "customer_12345", "type": "person", "name": "María González", ... }, "previousEntity": null, "confidence": 1.0, "reasoning": "No existing entity found matching criteria. Created new entity.", "conflicts": [] } ``` ### Updated Existing Person ```json theme={null} { "success": true, "action": "updated", "entity": { "id": "550e8400-e29b-41d4-a716-446655440000", "externalId": "customer_12345", "type": "person", "name": "María González", "entityData": { "person": { "income": 95000 } }, ... }, "previousEntity": { "id": "550e8400-e29b-41d4-a716-446655440000", "entityData": { "person": { "income": 85000 } }, ... }, "confidence": 1.0, "reasoning": "Exact match found on externalId. Updated existing entity with smart merge.", "conflicts": [ { "field": "entityData.person.income", "oldValue": 85000, "newValue": 95000, "resolution": "source_wins" } ] } ``` ## Use Cases ### Data Import from CRM ```javascript theme={null} // Import customer data from CRM, avoiding duplicates async function importCustomer(crmData) { const response = await fetch('http://api.gu1.ai/entities/upsert', { method: 'PUT', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ entity: { type: 'person', externalId: crmData.customerId, name: crmData.fullName, countryCode: crmData.country, taxId: crmData.taxId, entityData: { person: { firstName: crmData.firstName, lastName: crmData.lastName, income: crmData.annualIncome } }, attributes: { source: 'crm_import', importDate: new Date().toISOString() } }, options: { deduplicationStrategy: 'hybrid', conflictResolution: 'smart_merge' } }) }); return response.json(); } ``` ### Progressive Data Enrichment ```python theme={null} def enrich_person_data(external_id, new_data): """Progressively add data to person as it becomes available""" response = requests.put( 'http://api.gu1.ai/entities/upsert', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={ 'entity': { 'type': 'person', 'externalId': external_id, 'name': new_data.get('name'), 'countryCode': new_data.get('country'), 'entityData': new_data.get('details', {}), 'attributes': new_data.get('attributes', {}) }, 'options': { 'deduplicationStrategy': 'exact_match', 'conflictResolution': 'smart_merge' # Merge new with existing } } ) result = response.json() if result['action'] == 'updated': print(f"Enriched existing person with new data") return result ``` ## Best Practices 1. **Choose the Right Strategy**: * `exact_match` for clean, structured data with reliable IDs * `fuzzy_match` for user-entered data with potential typos * `hybrid` for most production scenarios 2. **Handle Conflicts Gracefully**: * Use `smart_merge` for automatic resolution * Use `manual_review` for critical data * Check `conflicts` array in response for important changes 3. **Monitor Confidence Scores**: * Scores below 0.7 may indicate weak matches * Log low-confidence updates for review ## Error Responses ### 400 Bad Request ```json theme={null} { "error": "Invalid tax ID format for country" } ``` ### 500 Internal Server Error ```json theme={null} { "error": "Failed to upsert entity" } ``` ## Next Steps * [List Persons](/en/api-reference/person/list) - Query upserted persons * [Update Person](/en/api-reference/person/update) - Make targeted updates * [Get Person](/en/api-reference/person/get) - Retrieve full person details # Changelog Source: https://docs.gu1.ai/en/changelog Latest updates and improvements to gu1 documentation — covering new endpoints, dashboard features, and bug fixes, with examples for changelog use cases. *** *** *** *** *** **2026-11-06** Change external ID rewrites historical references in batches ## Change external ID on large histories `POST /entities/change-external-id` still updates the entity immediately and returns the same `success`, `changed` and `entity` fields. Historical `transactions` (`origin_external_id`, `destination_external_id`) and `user_events` (`entity_external_id`) are rewritten in short batches instead of one database transaction. The response adds `externalIdPropagation`: `done` or `running`. While it is `running`, new transactions already use the new external ID and older rows catch up. A repeated call with the same new ID is still a no-op on the entity. See [Change person external ID](/en/api-reference/person/change-external-id). **2026-11-06** Rules: regex on free text ignores case and accents; CNAE and other code fields match across formats ## Rules: text and code matching * `regex` / `not_regex` on free-text fields (`description`, `title`, `comment`, `note`, for example `mediaMentions.$.description`) now ignore case and accents, so `corrup[cç][aã]o` or `Fraude` match `CORRUPCAO` and `fraude`. A `description` or `descriptions` leaf does this even on a code path: `cnaes.$.description` and `mainCNAE.description` match `Farmácia` with `farmacia`. Any other leaf on a code path, including `mainCNAE.code` and `zipcode.value`, stays exact. Other fields keep the exact, case-sensitive regex. Accented character classes such as `[áéíóú]` are not folded. `(?i)` is still not valid and the condition stays `false`. * A field is a code when the path ends in `.code`, contains `cnae`, `ncm`, `cst` or `cfop` (case-insensitive substrings), or contains `code.` / `codes.` anywhere in the path (for example `postalCode.value` or `zipcode.value`), not only as its own segment. On those fields `in`, `not_in`, `contains_any_from_*_list` and `not_contains_any_from_*_list` treat `12.34-5`, `12345` and `12.34/5` as the same code. For lists it is full-code equality, so `17` does not match `4771-7/01`. * **Fire less:** `not_regex` on free text, `not_in` on codes and `not_contains_any_from_*_list` on codes return `false` for values that now match. Positive operators (`regex`, `in`, `contains_any_from_*_list`) only gain matches. * Unchanged: `eq_strict`, `ne_strict`, `starts_with`, `ends_with`, numeric comparisons, `in_custom_list`, `in_global_list` and `add_field_to_custom_list`. See [Rule conditions](/en/api-reference/rules/conditions). **2026-11-03** Change transaction status by externalId ## Change transaction status by externalId `PATCH /transactions/external/:externalId/changeStatus` updates an existing transaction with the same body as `PATCH /transactions/:id/changeStatus`: `status` (required) and `reason` (optional, free text, 2000 characters). The key needs `transactions:edit`. Open statuses are `CREATED`, `PROCESSING` and `SUSPENDED`. Final statuses are `SENT`, `EXPIRED`, `DECLINED`, `REFUNDED` and `SUCCESSFUL`; a final status does not reopen. `POST /transactions` only creates a transaction. A repeated `externalId` returns `409` `DUPLICATE_TRANSACTION_EXTERNAL_ID`. See [Change transaction status](/en/use-cases/transaction-monitoring/change-status-api). **2026-11-03** Organization setting requires a sent origin or destination link ## Required sent entity link Organization settings → Transactions adds **Require a sent origin or destination link to exist**, off by default. When on, single create, batch, and file upload reject the transaction if a sent origin or destination identifier has no matching entity. `linkEntityStrict=false` does not turn that off. When the setting is off, the API behaves as before. See [Create a transaction](/en/api-reference/transactions/create). **2026-10-28** CPF corpus coverage ## CPF corpus coverage `GET /api/integration-services/ar_gueno_cpf_service/corpus/coverage` returns the files this instance has finished loading and the occurrence-date range. Do not send `tenant`. It is free. Lookups are not clipped to that range. A file still queued does not appear. See [Coverage](/en/api-reference/services/ar-gueno-cpf/coverage). **2026-10-28** Upload a CPF workbook ## CPF workbook upload `POST /api/integration-services/ar_gueno_cpf_service/corpus/upload` accepts one `.xlsx` file (32 MB max). Gu1 stores it for the instance. Send only the `file` field. The upload is not billed as a lookup and requires `services:upload` in addition to `services:execute`. Lookups stay on `services:execute`. `200` means stored (`loaded` or `already_loaded`). `202` means the file is queued. A name that already exists with different content returns `409`. See [Upload workbook](/en/api-reference/services/ar-gueno-cpf/upload). **2026-10-19** Loan lifecycle user events ## Loan user events `POST /events/user` accepts `LOAN_REQUEST`, `LOAN_APPROVED`, and `LOAN_REJECTED` as `eventType` values for a submitted loan application and its result. Existing event types are unchanged. Use `OTHER_EVENT` only when no specific type applies. See [Create an event](/en/api-reference/events/create). **2026-10-13** Typed findings when closing an investigation ## `closureFindings` when closing an investigation `PATCH /intelligence/investigations/{id}/status` accepts `closureFindings` when moving to `CLOSED`. Each item has `categoryCode` and one determination: `confirmed`, `not_confirmed`, or `inconclusive`. If the field is omitted, the closure stays unclassified. If it is sent, at least one item is required and the code must exist in the organization catalog. `not_confirmed` does not mark alerts as false positives. See [Update status](/en/api-reference/investigations/update-status). **2026-10-09** Rule condition for whether origin or destination has a record ## Party record existence on transaction rules A transaction rule can compare `originEntityExists` or `destinationEntityExists` with `eq` and value `true` or `false`. `true` means a person or company record exists for that side. Lookup order is entity id, then external id, then tax id. `false` means no identifier was sent or no record matched. An external id on the transaction is not enough to treat the record as existing. See [Rule conditions](/en/api-reference/rules/conditions). **2026-10-09** Manual entity import without a tax id ## Optional `tax_id` on manual entity import On `POST /batch-import/import/entities` with `entityImportMode=manual` (the default), `tax_id` may be empty. The entity is created without a tax id, same as a single manual create. `suggested_name` stays required. **Automatic** mode still requires `tax_id` on every row. A filled `tax_id` is stored as the tax id. Custom mapping (`mappingId`) still requires a column mapped to tax id. See [Import entities](/en/api-reference/bulk-imports/import-entities). **2026-10-05** Sandbox simulation of transaction create errors ## Sandbox error simulation for `POST /transactions` In **sandbox** organizations only, you can force create failures without writing a transaction: use an `externalId` prefixed with `SIMULATE-ERROR-` and/or `metadata.sandboxErrorCode` (alias `metadata.error_code`). Catalog includes validation, duplicate, archived entity, quota, 503 unavailable, and a capped timeout (**504**, \~3s). Production ignores these triggers. See [Sandbox error simulation](/en/use-cases/transaction-monitoring/sandbox-error-simulation) and [Create transaction](/en/api-reference/transactions/create). **2026-10-02** Read materialized shareholders without running enrichment again ## Materialized shareholders `GET /entities/{id}/shareholders` and `GET /entities/by-tax-id/{taxId}/shareholders` return owners and other relationships already stored for an entity. The call does not run enrichment. `shareholders` includes ownership links (`shareholder`, `owns`, `controls`) with percentage, roles and `riskScore`. Other links are in `relationships`. `depth` (default `1`, max `5`) walks nested owners. Optional filters on `shareholders` combine with AND and apply before pagination: `type`, `taxId` (digits only), `minRiskScore`, `maxRiskScore`, `minOwnershipPercentage`, `maxOwnershipPercentage`. A null score or percentage is excluded when that bound is set. `taxId` in the response is `null` without `entities:read_sensitive`. `totalShareholders` and `totalRelationships` are the counts before `limit` / `offset`. `POST /entities/automatic` still returns `data.shareholders` as `{ id, name, taxId, type }` for children created in that run. Use the new GET to read them later. See [Get materialized shareholders](/en/api-reference/entities/shareholders). **2026-09-24** Archived entities are read-only except restore ## Archived entities are read-only When `deletedAt` is set, mutations on that entity (update, enrich, relationships, KYC/docs, agents, monitoring, and using it as a transaction origin/destination) return **403** with `error.code` `ENTITY_ARCHIVED`. Restore remains `PATCH /entities/{id}/restore`. Background jobs skip archived rows without failing the batch. Active entities (`deletedAt` null) keep the same API behavior as before. See [Update an entity](/en/api-reference/entities/update) and [Create a transaction](/en/api-reference/transactions/create). **2026-09-24** Holder Intelligence now separates the consultation date from the holder's last stock change ## Snapshot and last change dates `snapshotDate` now represents the UTC date when Gu1 performed the consultation. The new `lastChangedDate` field reports when that holder's CBU/CVU totals last changed. See [Accounts Count by CUIT](/en/api-reference/services/ar-gueno-holder-intelligence/accounts-count) and [CUIT Exists](/en/api-reference/services/ar-gueno-holder-intelligence/exists). **2026-09-23** Rules can compare dates with exact minute precision ## Minute-level recency for temporal conditions Date conditions now include `minutes_since`, `minutes_since_lt`, `minutes_since_lte`, `minutes_since_gt`, and `minutes_since_gte`. In transaction rules, the difference is calculated against `transactedAt` without rounding. This supports controls such as “the account was opened three minutes ago or less” with `originEntityData.registrationDate` and `minutes_since_lte: 3`. See [Rule conditions](/en/api-reference/rules/conditions). **2026-09-22** Transactional email responses now include a delivery ID and delivery events can be queried ## Email delivery tracking Successful `POST /marketplace/messaging/send-email` responses now include `deliveryId`. Use `GET /marketplace/messaging/email-deliveries` to query sent, delivered, opened, clicked, bounced, and failed timestamps for the authenticated organization. Existing SendGrid domains remain compatible. See [Send email](/en/api-reference/messaging/send-email#delivery-tracking). **2026-09-21** KYC usage is recorded when the session starts and is not refunded on cancellation ## KYC session usage New KYC sessions consume the execution when they start. Cancelling, abandoning, or allowing a validation to expire closes the link but does not refund that usage. Sessions started before this change retain their previous behavior. See [Cancel KYC Validation](/en/use-cases/kyc/cancel-validation). **2026-09-18** The newest KYC validation remains current unless explicitly cancelled ## Current KYC reference When a new validation starts, that session is the `isCurrent` reference in every status, including `expired` and `abandoned`. Only an explicit cancellation restores the most recent prior validation whose status is not `cancelled`. This behavior keeps entity profiles, API reads, and transaction rules aligned. See [Create KYC Validation](/en/use-cases/kyc/create-validation). **2026-09-16** Organization KYC warning policy can force in review or rejected per code ## Per-code KYC warning policy In organization settings, each document-check warning code can **do not intervene**, **force in review**, or **force rejected**. The heaviest status wins; a code with no rule keeps the document-check result. The adjustment is audited on `metadata.kycWarningEscalation`. See [KYC warning risk codes](/en/use-cases/kyc/warning-risk-codes). **2026-09-14** KYC and biometric sessions can use an explicit or organization-default UI language ## Configurable validation language `POST /api/kyc/validations` now accepts the optional `language` field, matching biometric session creation. A request-level language takes precedence over the organization's default; when neither is set, the hosted UI keeps device language detection. See [Create KYC Validation](/en/use-cases/kyc/create-validation) and [Embedded Biometric Session](/en/use-cases/kyc/embedded-biometric). **2026-09-14** New configurable reminder, closure, and reactivation lifecycle for onboarding ## Secure onboarding reactivation Document requests can use automatic reminders and an operator-approved final closure. The **Continue onboarding** link records intent and runs the analysis again without directly reactivating the entity. [View the reactivation endpoint](/en/api-reference/onboarding/document-reactivation). **2026-09-10** Parent organizations can share live risk matrices, data lists, and webhooks with direct child channels ## Share matrices, lists, and webhooks with channels Holdings can explicitly select which **direct child organizations** in the same environment receive each risk matrix, tenant data list, or webhook. A selected child sees the **same UUID** (and the same list items or webhook secret). Catalog fields: `origin` (`local` | `parent`), `readOnly`, `sharedEnabled`. Assigning or running a parent matrix, and dispatching a parent webhook, require the channel opt-in (`POST /risk-matrices/{id}/child-share`, `POST /data-lists/{id}/child-share`, and `POST /webhook-config/{id}/child-share`). Writes on a parent row return `403` `SHARED_RESOURCE_READ_ONLY`. Webhook payloads keep `organizationId` of the **channel**. See [List risk matrices](/en/api-reference/risk-matrix/list), [List data lists](/en/api-reference/data-lists/list), and [Webhook configuration](/en/webhooks/configuration). **2026-09-09** Transactions can now be reported manually under an investigation category ## Manual transaction risk reports Analysts can use [Report Transaction Risk](/en/api-reference/transactions/report-risk) to classify a transaction under an active category such as Fraud or AML. Gu1 creates a rule-less alert; the analyst chooses to create an investigation or consolidate into a compatible one for the selected subject. The decision is audited, the reason is optional, the financial status remains unchanged, and no risk analysis audit is fabricated. The transaction keeps alert and investigation IDs, blocks duplicate reports, and links back to the case. **2026-09-09** Holder intelligence accounts-count returns CUIT demographics estimates ## CUIT demographics on accounts-count [Accounts count](/en/api-reference/services/ar-gueno-holder-intelligence/accounts-count) now includes an additive `cuitDemographics` object (age cohort, probable foreigner, inferred gender / contributor type). Values are computed at response time from CUIT digits — low confidence; not proof of age or nationality. Existing account totals and rule paths under `services.holder_intelligence.*` are unchanged. Rule Builder also adds `tax_id_demographics_matches` on CUIT fields: one configurator can combine age range (overlap or fully contained) and probable foreigner (medium or high confidence). It is evaluated locally, does not query or charge Holder Intelligence, and does not change existing `tax_id_age_*` operators. Holder Intelligence templates expose this as an optional preconfiguration filter; when left empty, their original conditions remain unchanged. **2026-09-07** Brazilian automatic company creation now returns the main CNAE ## Main CNAE in Brazilian company profiles [Automatic entity creation](/en/api-reference/entities/create-automatic) now copies the normalized main economic activity into `entityData.company.cnae`, `cnaeDescription`, and the compatible `industry` description. Integrators no longer need an additional enrichment read to obtain the main CNAE after company creation. **2026-09-03** Read persisted enrichment: normalized dossier and current mapped/raw ## GET normalized enrichment and current enrichment data Two **read** endpoints are now documented with the persisted enrichments (they already existed; this is documentation, not a new contract): * [Get normalized enrichment](/en/api-reference/enrichment/get-normalized) — `GET /entities/{id}/normalized-enrichment`. Gu1 `NormalizeType` dossier (`RootData` + consolidators + summaries). **404** `NOT_FOUND` if the entity has no normalized row yet. * [Get current enrichment data](/en/api-reference/enrichment/get-current-data) — `GET /entities/{id}/enrichment-data`. Last `mapped` / `raw` payloads keyed by integration code. If the entity exists but has no snapshot, HTTP **200** with `hasEnrichmentData: false`. Neither call re-runs integrations or consumes enrichment credits. [Get entity](/en/api-reference/entities/get) still does not replace these responses. Permission: `entities:read`. **2026-09-01** Operation statuses on the CPF in-list checks ## `statusIds` on the CPF in-list checks CPF membership checks now return the operation statuses alongside `count` and the amounts: * [CUIT in-list](/en/api-reference/services/ar-gueno-cpf/cuits-in-list): `statusIds`, `asRecipientStatusIds`, `asInitiatorStatusIds`. * [Account in-list](/en/api-reference/services/ar-gueno-cpf/accounts-in-list): `statusIds`. These are the unique, non-empty, sorted statuses across **all** matching operations: `1` (case filed), `2` (case confirmed as fraud), `3` (genuine transaction). They are computed in the same pass as the COUNT, so expected cost and latency are unchanged. With `availableCount=false` they arrive as `null`, just like `count`. The fields are **additive**: an integrator sending yesterday's request gets the same response plus these keys. In rules, `services.cpf.status_ids` (and its per-role and per-account variants) no longer requires the full lookup: it resolves from the same in-list as `count`. On top of that, the membership conditions (`services.cpf.in_list`, `services.cpf.hit`, `services.cpf.cbu.in_list`, `services.cpf.cvu.in_list`, `services.cpf.account.in_list`, `services.cpf.account.hit`) accept the optional **`serviceCpfStatusIds`** modifier in the condition body: ```json theme={null} { "field": "services.cpf.in_list", "operator": "eq", "value": true, "serviceCuitFieldPath": "destinationTaxId", "serviceCpfMode": "both", "serviceCpfStatusIds": ["2"] } ``` The condition matches only when the CPF appearance has at least one operation in one of those statuses, with **a single** service call and no second condition. Empty or absent means any status, and a negative check (`value: false`) is never narrowed. It is additive: an existing rule without the field behaves the same. **2026-08-31** Automatic entity creation errors are English ## Integrator-facing `error` strings On automatic entity creation (sync, proxy/webhook, and `creationFailed[]`), the `error` field is always **English**. Use `code` (for example `UPSTREAM_CREDITS_ERROR`, `DOCUMENT_RESTRICTED`, `INVALID_TAX_ID`) for branching. The dashboard still localizes the same codes for operators. When basic-data fails and the entity is **not** created, `enrichmentFailed` stays `[]` (that array is only for extra enrichments on a **persisted** entity). The additive field **`enrichmentFailedDetails`** lists each attempt (primary + fallbacks) with `providerCode`, `code`, and `errorMessage`. The same list is nested on the `creationFailed[]` row. Gu1 can now explicitly enable minor creation with a provisional `Person ` name. When the primary source identifies a minor, the entity is immediately created with `attributes.isMinor: true`, without retries, fallbacks, or additional enrichments. Risk analysis runs normally. The setting is off by default. **2026-08-28** Entity accounts CRUD by externalId and taxId ## Account routes by external ID and tax ID `GET`/`POST` `/entities/{id}/accounts` and `PATCH`/`DELETE` `/entities/{id}/accounts/{accountId}` still use the Gu1 entity UUID. The same operations are available as: * `/entities/by-external-id/{externalId}/accounts` * `/entities/by-tax-id/{taxId}/accounts` (plus `/{accountId}` on PATCH/DELETE). `{accountId}` remains the Gu1 account UUID. Tax ID lookup strips punctuation and is case-insensitive (same alphanumeric key as org-level tax uniqueness). See [Entity accounts](/en/api-reference/entities/accounts). **2026-08-28** Spain company taxId accepts NIF and NIE besides CIF ## Spain KYB tax IDs (autónomos) For `countryCode: ES` and `type: company`, `taxId` now accepts **NIF** (8 digits + letter, e.g. `74387028Z`) and **NIE** (`X`/`Y`/`Z` + 7 digits + letter) in addition to **CIF**. Sole traders were previously rejected with `INVALID_TAX_ID` / "Invalid CIF format". See [Country requirements](/en/api-reference/entities/country-requirements) and [Tax ID formats](/en/api-reference/entities/tax-id-formats). **2026-08-28** Register multi-currency accounts on person and company entities ## Entity accounts Person and company entities can now hold multiple financial accounts in currencies such as USD, ARS, and BRL. The new CRUD endpoints support client account IDs, account status, CBU/CVU, IBAN, generic account numbers, aliases, and a primary account per currency. The dashboard includes an **Accounts** tab, country and account-type selectors, and translated account events in the timeline. `accountType` is now a canonical enum covering bank, savings, checking, wallet, payment, investment, credit, and institutional accounts. `POST` and `PATCH` return `400 VALIDATION_ERROR` for unknown values. Historical values outside the enum are retained in `metadata.legacyAccountType` and normalized to `other`. See [Entity accounts](/en/api-reference/entities/accounts). **2026-08-27** 429 rate limit message includes minutes until reset ## Rate limit wait in the 429 body When an API key exceeds its quota, `message` includes how many minutes remain (e.g. `Try again in 17 minutes.`). The JSON also adds **`retryAfterMinutes`** (ceil of `retryAfter` seconds). `retryAfter` and `Retry-After` are still in seconds. The window still starts at the first request of the cycle, not at clock-hour boundaries. See [Authentication](/en/api-reference/authentication). **2026-08-26** Entity bulk: when basic data fails vs extra enrichments ## Automatic vs manual entity rows [Import entities](/en/api-reference/bulk-imports/import-entities) now documents that **`automatic`** is the same pipeline as [Create entity automatically](/en/api-reference/entities/create-automatic): if the **basic-data** step fails, the row is not created and the job continues (unless `stopOnFirstError`). Extra enrichments that fail after a successful basic-data step do not roll back the entity. **`manual`** still creates from `suggested_name` first; optional enrichment failures leave the entity in place. See also [Bulk imports overview](/en/api-reference/bulk-imports/overview). **2026-08-26** Entity bulk cap 20k, one live job per org, global slots ## Batch import concurrency and entity row cap Entity CSV imports are capped at **20,000 rows** per request (plan limits still apply below that; `BULK_AUTOMATIC_ENTITY_MAX_ITEMS` can only lower the cap). Transaction files stay at up to 5 × 100,000. Each organization may have **one live job** (`queued` or `running`) **per import type**. A second POST of the same type returns **`409`** `JOB_IN_PROGRESS` with `jobId`. At most **one job may wait** (`queued`) per organization: if a job of either type is already queued, POST of the other type returns **`409`** `JOB_ALREADY_WAITING`. Transactions and entities **cannot run at the same time** in one organization: a POST of the other type returns **`202`** `queued` with `code: "QUEUED_WAITING_PREVIOUS_JOB"` and `queue.waitingForOrgJob: true` **only when the other type is running and nothing is already waiting**. It starts when the current job finishes. At most **two** organizations process the same type at once; additional orgs receive **`202`** with `code: "QUEUED_WAITING_SLOT"` and `queue: { globalSlots, running, waitingAhead, waitingForOrgJob }` — never 409 for the global cap. The 202 body includes `code` (`QUEUED_WAITING_PREVIOUS_JOB` or `QUEUED_WAITING_SLOT`) and `message`. The same reason is stored on the **job row** as `metadata.queueWaitReason` (`previous_job` or `global_slot`) so import history can show it while status stays `queued`. It is not a field on the 202 JSON itself. Transaction jobs remain `running` until queued rule evaluation finishes when `executeRules` is true. User-event imports are unchanged. See [Bulk imports overview](/en/api-reference/bulk-imports/overview) and [Import entities](/en/api-reference/bulk-imports/import-entities). **2026-08-25** Entity and transaction export files no longer expire ## Per-file retention in export history Export job responses now include nullable `fileExpiresAt`. A `null` value means the stored file has no expiration; `linkExpiresAt` still only describes the signed email link. New entity and transaction exports remain available in history without expiration. Other export kinds keep their existing retention period, and existing files keep their previous expiration. See [Bulk entity export](/en/api-reference/entities/export-jobs-email) and [Report export jobs](/en/api-reference/entities/report-export-jobs). **2026-08-24** Post-import matrix over a previous entity batch ## Closing related imports `postImportActions.run_risk_matrix_filtered` now accepts `sourceImportJobId`. After the current file completes, Gu1 can run the matrix on `created` entities from a selected previous import, including entities without a relationship in the current file. The previous batch is validated within the same organization and must have its full report available. The new `onlyWithoutRiskMatrixExecution=true` scope runs the matrix on every entity of the selected type without a recorded matrix execution. Once processed, those entities are not selected by later imports. This is an optional additive field and cannot be combined with `relatedEntitiesOfCreatedEntitiesOnly=true`. See [Import entities](/en/api-reference/bulk-imports/import-entities). **2026-08-20** Device context for investigations ## Devices for an entity and its direct relationships The new `GET /devices/entity/{entityId}/investigation-context` endpoint returns devices grouped by entity for investigation views. Set `includeRelatedEntities=true` to include active direct relationships in either direction; the default remains the investigated entity only. This is an additive endpoint. Existing device listing requests are unchanged. See [List devices for an entity](/en/api-reference/devices/list). **2026-08-20** New bulk import job failure codes ## `jobFailure.code`: `ARTIFACT_UPLOAD_FAILED` and `QUEUE_ERROR` When a batch was registered but died before starting — either because its payload/source file could not be stored, or because the queue rejected the enqueue — the job ended as `failed` with `jobFailure.code: "WORKER_ERROR"`, and the actual reason only lived in the free-text message. Those two cases now have their own codes: * **`ARTIFACT_UPLOAD_FAILED`** — the payload or source file could not be stored, so the worker had nothing to resume from. * **`QUEUE_ERROR`** — the queue rejected the enqueue and the job never started. In both cases **no rows were imported** and the upload should be retried. The codes show up in `jobFailure.code` on job status and `failures` (JSON), and match the `error.code` the import POST already returned. Additive change: if you `switch` on `jobFailure.code`, these values previously arrived as `WORKER_ERROR`. Existing jobs are not rewritten. See [Batch import failure codes](/en/api-reference/bulk-imports/batch-import-failure-codes). **2026-08-19** Richer transaction warnings in validate-csv ## `validate-csv`: row-level warnings for transaction mappings The preflight for **transaction** mappings now reads the whole file (up to 50,000 data rows) instead of the first 50, and checks the closed value sets of `type`, `status`, `paymentMethod` and `reason` — previously an unmapped enum only surfaced once the import job was already running. Additive changes to the `200` response, no breaking change: * New top-level `totalRows` alongside the existing `sampledRows`. * Each entry of `warnings` may now carry `field`, `value`, `allowedValues` and `occurrences`. Existing `code`, `message`, `row` and `column` are unchanged. * New warning code `INVALID_ENUM_VALUE`. Handle unknown codes by falling back to `message`. * Warnings are **grouped by problem** instead of emitted per row: one entry reports the first affected row plus `occurrences`. If you counted `warnings.length` as "bad rows", read `occurrences` instead. `ok` stays `true` for transaction mappings and the import is still allowed. Nothing changes in what gets imported. See [Validate CSV](/en/api-reference/bulk-imports/validate-csv). **2026-08-19** New entity status awaiting\_information ## New entity status: `awaiting_information` Person/company entities accept a new lifecycle value **`awaiting_information`** (waiting on client data — typically documents requested during onboarding). It is **not** `pending_verification` (identity KYC/KYB still outstanding). * You may send `status: "awaiting_information"` on create or PATCH like any other lifecycle value. * The onboarding analyst sets this status when it **sends** the merchant document-request email, storing the previous status on the request. After the merchant **submits** the documents (or the operator accepts/discards intake), Gu1 restores that previous status — unless an operator changed or locked status while waiting. * `awaiting_information` does **not** block operations the way `blocked` / `suspended` / `rejected` do. See [Entities overview — Entity Status](/en/api-reference/entities/overview#entity-status). **2026-08-18** Marketplace service: Fraud Prevention Center (CPF) ## Marketplace service: Central de Prevención de Fraude (CPF) New integration code **`ar_gueno_cpf_service`**. Gu1 proxies CPF lookups (CUIT + recipient CBU/CVU) including cheap **in-list** checks, full lookups, batches, and operation detail. * Base path: `/api/integration-services/ar_gueno_cpf_service` * Rules: `services.cpf.*` (CUIT via `serviceCuitFieldPath`) * In-list (`availableCount=true`): also returns accumulated amounts (`totalAmount`, role amounts) * Distinct from BCRA Central de Deudores enrichment See [Fraud Prevention Center (CPF)](/en/api-reference/services/ar-gueno-cpf/overview). **2026-08-12** Entity report: auditable manual risk and normalized AML screening ## Entity report: explicit current risk and AML screening **`GET /entities/{id}/export-data`** adds two objects and changes the meaning of `checks[]`. The PDF (dashboard download, `POST /entities/{id}/export` and the email delivery) reflects the same data. * **`riskSummary`** (new): the risk the report presents as current. `mode` is `manual`, `automatic` or `not_evaluated`. When a manual override is active, `effective` carries the manual score, `manual` includes justification, user, date and previous score, and `automatic.supersededByManual` flags the matrix score as historical. Previously the report showed the matrix score even when the operator had set the risk by hand. * **`amlScreening`** (new): one row per watchlist data source with `matchStatus`, `totalHits` / `relevantHits`, `listNames`, `reportedRiskLevel` (raw value as received, including `unknown` when that is what was returned) and `effectiveRiskLevel` + `riskLevelSource` (level derived from matches when needed internally). The PDF shows `reportedRiskLevel` when present. * **`checks[]`**: adds `screeningType`, `executionStatus` (`completed` / `failed`), `matchStatus` and optional `effectiveRiskLevel`. `matchStatus` can be **`undetermined`**: a check without normalized screening is no longer presented as “No Match”. * **Integrator impact:** the fields are additive and existing ones are unchanged. If you inferred “no matches” from `checks[]`, read `amlScreening` or `checks[].matchStatus` and treat `undetermined` as inconclusive. See [Entity PDF report by email](/en/api-reference/entities/report-export-email). **2026-08-07** destinationDetails.mcc accepts 3 or 4 digits ## Transactions: MCC length relaxed `destinationDetails.mcc` on transaction create now accepts **3 or 4** characters (previously exactly 4). Integrators may send values such as `"742"` or `"0742"`. Preferred form remains the ISO 18245 4-digit string when available. See [Create transaction](/en/api-reference/transactions/create). **2026-08-07** AML Crypto API parity (checkId + history) ## AML Crypto: client-flow parity Gu1 AML Crypto (`/api/aml-crypto`) now matches the product flow for wallet/transaction screening: * Execute endpoints return `{ success, data }` with optional **`checkId`** when a history snapshot is stored. * **`GET /aml-crypto/checks`** supports filters + pagination (`total`, `limit`, `offset`). * **`GET /aml-crypto/checks/:id`** returns a single org-scoped check. * Permissions: `aml_crypto:read` (history) and `aml_crypto:execute` (lookups). See [AML Crypto overview](/en/api-reference/aml-crypto/overview). **2026-08-07** Templates always create disabled automations ## `POST /automations/from-template` always creates disabled Automations created from a template are now **always** persisted with `enabled: false`, regardless of the `enabled` value in the template definition. Previously most catalog templates were created **active** and could fire on the next matching event before you reviewed recipients, risk matrix, or filters. * **Impact for integrators:** after `from-template`, activate explicitly with `POST /automations/:id/toggle`. * No request/response fields changed. See [List templates](/en/api-reference/automations/templates). **2026-08-07** Entity monitoring automation template ## Automation template: entity monitoring (scheduled) * New system template **`entity_monitoring_scheduled`**: cron → `fetch_entities` (preconfigurable filters) → `run_risk_matrix` (chosen matrix). Created **disabled**. * Preconfig knobs: schedule frequency/time/timezone, entity filter builder, fetch limit, `riskMatrixId`. See [List templates](/en/api-reference/automations/templates). **2026-08-07** Automation templates preconfig + alert→email ## Automation templates: preconfig params + alert → email * **`GET /automations/templates`** may include **`parameterDefinitions`** (path + optional `mirrorPaths`) for catalog knobs. * **`POST /automations/from-template`** accepts optional **`paramValues`**. Required params return **400** when missing. * New system template **`alert_created_email_notify`**: on `alert_created`, send email via `send_push_notification` (configure rules, severities, recipients, message template). Created **disabled**. See [List templates](/en/api-reference/automations/templates). **2026-08-06** Editable presets, preview, and CSV/PDF ## Editable presets + preview + CSV/PDF Report presets are now **updatable** via **`PATCH /report-presets/:id`** (`name`, `description`, `params`; `templateCode` fixed). **`POST /report-templates/:code/preview`** returns sample CSV/PDF, and the catalog supports **CSV/PDF** on bulk templates and `alerts_by_rules`. See [Presets](/en/api-reference/entities/report-presets) and [Templates](/en/api-reference/entities/report-templates). **2026-08-06** Report generate is async (S3 + Descargables) ## Report generate → async S3 + Descargables **Generate** (template or preset run) always queues a background export to object storage and returns **202** with `jobId`. Download from Reporting **Descargables** via [Report export jobs](/en/api-reference/entities/report-export-jobs) (`GET /report-export-jobs`). * **`alerts_by_rules`** no longer returns a sync XLSX or `contentBase64` in the run response. * Automation **`send_report` / Generar reporte** prefers **`reportPresetId`**; set optional **`sendEmail`** (+ `recipientEmails`) to also email the file. * **Investigations**, **entity PDF profile**, and **Metrics Hub** with `delivery: "download"` no longer return `skipped` for missing recipients: they queue the job and the file lands in Descargables. Profile and metrics reports are listed as `kind: "documents"`. See [Report templates](/en/api-reference/entities/report-templates), [Report presets](/en/api-reference/entities/report-presets), and [Report export jobs](/en/api-reference/entities/report-export-jobs). **2026-08-06** Org-scoped immutable report presets ## Report presets API Organizations can save frozen Gu1 template configs via **`GET/POST /report-presets`**, **`GET/DELETE /report-presets/:id`**, and **`POST /report-presets/:id/run`**. Presets are immutable after create (delete only), capped at 50 per org, and power one-click download plus scheduled `send_report` automations. See [Report presets](/en/api-reference/entities/report-presets). **2026-08-06** Operational report templates and alerts-by-rules export ## Report templates API Gu1 now exposes **`GET /report-templates`**, **`GET /report-templates/:code`**, and **`POST /report-templates/:code/run`**. Reports for alerts, entities, transactions, and investigations expose `field → operator → value` conditions, including Tax ID custom-list membership, age, PEP, sanctions, adverse media, MEI, and criminal legal proceedings. Conditions can be frozen in org presets. Ambiguous portfolio/holder-variation templates are not part of the catalog. See [Report templates](/en/api-reference/entities/report-templates). **2026-08-06** investigation\_status\_changed now covers every transition and exposes the previous status ## Automations on investigation status change The **`investigation_status_changed`** trigger is now emitted on **every** case status transition, not only when the status is changed through the API. * **New origins that trigger automations:** moving forward or back a stage (In progress ↔ Pending review and close by stage), reopening a closed case, agent actions, the `change_status` / `start_investigation` action of another automation, and the automated resolution pipeline. None of these emitted the event before, so automations on `PENDING_REVIEW` never ran. * **No longer emitted when the status does not change:** resending the current status (for example `CLOSED` on an already closed case) no longer produces duplicate notifications. * **Previous status in the context:** new condition `investigation.previousStatus` and new template variable `{{investigation.previousStatus}}`, plus `investigation.transitionSource` to know where the change came from. * **New system email templates** per status: `investigation_in_progress_email_*`, `investigation_pending_review_email_*`, `investigation_closed_email_*` and `investigation_reopened_email_*` (es / en / pt). * The status picker in conditions now offers the four real statuses of the flow, including **Pending review**. Details: [Triggers](/en/workflows/triggers#investigation_status_changed-in-detail). > [!WARNING] > > If you already had automations on this trigger, they may now run on transitions that previously went unnoticed. Review your status conditions before enabling customer-facing notifications. **2026-08-04** Entity status not\_started + clearer status docs ## New entity status: `not_started` Person/company entities accept a new lifecycle value **`not_started`** (V2 `NOT_STARTED` equivalent). * **Default on create stays `under_review`** for existing integrations. * Pass `status: "not_started"` on create (manual, automatic, or bulk) to opt in. * Risk matrix labels and `updateEntityStatus` rules can move from `not_started` to **`under_review`**, **`active`**, **`rejected`**, **`blocked`**, etc. — there is **no mandatory intermediate step**. * Full table and example flows: [Entities overview — Entity Status](/en/api-reference/entities/overview#entity-status). **2026-08-04** Holder intelligence metrics: total delta and % change ## Total CBU+CVU delta and percent change on metrics `GET /integration-services/ar_gueno_holder_intelligence_service/cuits/:cuit/metrics` now exposes derived totals on `data.metrics`: * `totalDelta` — `cbuDelta + cvuDelta` * `totalPctChange` — % change over combined start stock (`null` when start = 0) * `totalAccountsStart` / `totalAccountsEnd` — CBU+CVU stock at window bounds Rules engine paths: `services.holder_intelligence.metrics.total_delta`, `total_pct_change`. Existing channel fields are unchanged. **2026-08-03** Enrichments outside the entity country are skipped ## `autoExecuteIntegrations.enrichments` is filtered by country and entity type When creating an entity (manual or automatic), enrichment codes whose catalog entry does not cover the entity `countryCode` (or `GLOBAL`) and `type` are now **ignored** instead of being executed. An Argentine tax-registry enrichment can never resolve a Brazilian CNPJ, so the call only produced a guaranteed failure in the entity audit trail. * Applies to `enrichments`, `enrichmentGroupRefs` and `executeAllActiveEnrichments` on both the main entity and related entities (`autoExecuteIntegrationsShareholders`). * Org enablement, integration blocks and fallback chains are unchanged: only country / entity-type coverage is checked here. * **Impact:** requests that mixed codes from another country stop returning those providers under `enrichment` errors. Any provider valid for the entity country behaves exactly as before. **2026-08-02** Manual entity notes via API + UI ## Create notes on an entity dossier Operators can now add **multiple** notes on a person/company entity from the Entity Builder notes dialog (not only via contextual-agent HITL). * **`POST /entities/{id}/notes`** — body: `content` (required, max 8000), optional `noteType` (`general` | `analysis` | `finding` | `recommendation`), optional `isImportant` (boolean). Requires `entities:edit` (legacy `entities:write`). * Each note stores **`source`**: `manual` (UI) or `agent` (HITL / contextual agent). * Audit timeline event **`note_added`** records `source`, `noteType`, `noteId`, and content. * **`GET /entities/{id}/notes`** is unchanged (list, newest first). **Impact:** clients can document decisions without opening an agent flow; existing HITL-created notes keep `source=agent` (legacy `agent_contextual` rows are renamed by migration). **2026-08-02** Transaction batch rejects spreadsheet-rounded ids ## New row failure code: `SCIENTIFIC_NOTATION_ID` Transaction batch rows are now rejected when an id field arrives in scientific notation (e.g. `5,04E+13`), which happens when a CSV with long numeric ids (CPF, CNPJ, account numbers) is opened and re-saved in Excel or Google Sheets. Only three significant digits survive the rounding, so the id cannot be recovered and silently breaks any rule that groups by it. * Checked fields: `externalId`, `originExternalId`, `destinationExternalId`, `originTaxId`, `destinationTaxId`. * The row fails with code **`SCIENTIFIC_NOTATION_ID`** in `failures.csv` / JSON `failures[]`; `identifier_type` lists the offending fields. * Behaviour follows `batchErrorHandling` like any other row failure (`rollback_all` aborts the file, `continue_collect_errors` creates the valid rows). * **Impact:** files that used to import with corrupted ids now report those rows as failures. Re-export the CSV keeping id columns as text. See [Batch import failure codes](/en/api-reference/bulk-imports/batch-import-failure-codes). **2026-08-02** Transaction batch: skip invalid entity refs + failures.csv in S3 ## Row error policy and S3 artifacts for transaction batch * **`batchErrorHandling=rollback_all`** is the **default** (UI + multipart upload when omitted): aborts the file on invalid refs/amounts or insert failures; detail goes to **`failures.csv`** (S3), without giant jsonb arrays. * Clients can choose **`continue_collect_errors`** (skip invalid rows and create valid ones) or **`stop_keep_success`**. * The error-policy selector is also available on **non-mapper** imports (transactions and entities). * Failures CSV columns: `external_id,code,error,role,identifier_type,value`. * New **`GET /batch-import/jobs/{jobId}/payload`**: download the processed `payload.json` when stored (authenticated attachment). * **Alignment:** user-event and entity batch jobs now follow the same S3-first failures model as transactions (`item_failures` / terminal `item_results` cleared; JSON samples hydrate from CSV). Entity kind in responses is **`entity_batch`**; **`entity_automatic`** remains an accepted input alias. See [Batch import failure codes](/en/api-reference/bulk-imports/batch-import-failure-codes), [Transaction batch failures](/en/api-reference/bulk-imports/get-transaction-batch-failures), and [Download batch job payload](/en/api-reference/bulk-imports/get-batch-job-payload). **2026-07-31** Filter transactions by their latest rules evaluation date ## Latest rules evaluation date filter **`GET /transactions`** now accepts the optional inclusive ISO timestamp filters `lastRiskEvaluationFrom` and `lastRiskEvaluationTo`. They can be combined to select transactions whose latest successful rules evaluation falls within a date range. Transactions evaluated before this field existed are matched using their risk analysis history, and list items now return `lastRiskEvaluationAt`. See [List transactions](/en/api-reference/transactions/list). **2026-07-31** Legacy entity webhooks now include score and document number ## Additional fields in legacy flat entity webhooks Legacy flat entity webhook payloads now include the additive fields `riskScore` and `documentNumber`. Existing status values and mappings remain unchanged. See [Entity webhook events](/en/webhooks/events/entity-events). **2026-07-31** Download which transactions were skipped as duplicates ## Skipped rows report for transaction batches New endpoint **`GET /batch-import/transaction-jobs/{jobId}/skips.csv`** lists the transactions a batch did not insert because the `externalId` already existed (columns `external_id,reason`). Until now `skipped` was only a counter, which made a duplicate re-upload look like a silent failure. * Available for jobs run with the default `skipDuplicates=true`; with `skipDuplicates=false` duplicates are resolved by the database and only counted, so the endpoint returns `SKIPS_NOT_AVAILABLE`. * Jobs finished before this release have no stored report (`SKIPS_NOT_AVAILABLE`). * Also available as a download button in the bulk imports history. See [Transaction batch failures](/en/api-reference/bulk-imports/get-transaction-batch-failures). **2026-07-24** Bulk: apply declared relationships when entity already exists ## Declared relationships on duplicate `tax_id` (bulk) In **manual** bulk import, when a row’s `tax_id` already exists and creation is skipped, Gu1 still applies that row’s declared `relationships` / CSV `related_*` columns (same as **automatic** create). Existing edges (same source → target + type) are skipped idempotently. See [Import entities (bulk)](/en/api-reference/bulk-imports/import-entities). **2026-07-23** Declarative relationships on entity create + bulk import ## Link to existing entities on create and bulk import You can declare relationships to entities that **already exist** (`relatedEntityId` / `relatedTaxId` / `relatedExternalId` + `relationshipType` + `role`) without relying on enrichment `depth`: * **`POST /entities`** and **`POST /entities/automatic`**: optional `relationships[]` body (max 10). * **Platform bulk CSV**: columns `related_tax_id` / `related_external_id` / `related_entity_id`, `relationship_type`, `relationship_role`, `relationship_as_source` (one relationship per row). * Missing counterpart → **`RELATED_ENTITY_NOT_FOUND`** and the entity is **not** created. See [Create entity](/en/api-reference/entities/create), [Create automatically](/en/api-reference/entities/create-automatic), and [Import entities (bulk)](/en/api-reference/bulk-imports/import-entities). **2026-07-23** Security webhook: environment access changed ## `security.member.environment_changed` When an admin updates a member's production/sandbox access from Teams (roster) in **one** assignment, Gu1 emits a single webhook instead of multiple grant/revoke events: * **Event:** `security.member.environment_changed` * **`context.fromAccess` / `context.toAccess`:** `"both"` | `"production"` | `"sandbox"` | `"none"` * **`changes.environmentAccess`:** `{ previous, current }` with the same values Existing `security.member.environment_granted` / `.environment_revoked` remain for single-environment grant/revoke flows. See [Security webhook events](/en/webhooks/events/security-events). **2026-07-22** linkEntityStrict + soft-link without breaking batch defaults ## Entity link: soft-link always, strict default unchanged for batch Transaction create / batch **always tries to auto-link** when a match exists (entityId → externalId → taxId). * **Batch default (BC):** omitting flags stays **strict** — `validateExistingEntity` still defaults to **`true`**. Unresolved refs → **400** `INVALID_ENTITY_REFERENCES` (same as before for clients that omit the field). * **`linkEntityStrict=true`**: force hard-fail (body or query). * **`linkEntityStrict=false`**: force soft-link (do not fail if missing), even if `validateExistingEntity` would otherwise be true. * **`validateExistingEntity=false`**: soft-link (and still attaches when found — previously soft mode skipped linking on batch). Single `POST /transactions` keeps `validateExistingEntity` default **`false`**. See [Create batch](/en/api-reference/transactions/create-batch). **2026-07-13** Creation contract quota error code rename ## Error code: `CREATION_CONTRACT_QUOTA_EXCEEDED` When an organization **contract creation quota** is exhausted (entities, transactions, user events), Gu1 APIs now return **`429`** with code **`CREATION_CONTRACT_QUOTA_EXCEEDED`** (replacing `CREATION_QUOTA_EXCEEDED`). * Same HTTP status and payload shape (`module`, `remainingTotal`, `periodKey`, `requested`). * Batch import row failures emit **`CREATION_CONTRACT_QUOTA_EXCEEDED`**; the old code remains accepted as a deprecated alias for historical `failures.csv`. See [Batch import failure codes](/en/api-reference/bulk-imports/batch-import-failure-codes). **2026-07-10** Entity taxId uniqueness across person and company ## Tax ID uniqueness (org-wide) An active **`taxId`** (normalized alphanumeric) may belong to **only one** entity per organization, whether `person` or `company`. * **Same type** already exists → automatic creation **reuses** that entity (`alreadyExisted`). * **Other type** already holds the tax ID → **`409`** with code **`DUPLICATE_TAX_ID`** (no new row). * Applies to manual create, automatic create, tax ID PATCH, and soft-delete restore. * Historical duplicate rows are not deleted; new conflicting writes are blocked in app and via a database trigger. See [Create entity automatically](/en/api-reference/entities/create-automatic) and [Create entity](/en/api-reference/entities/create). **2026-07-08** addFieldToCustomList rule action ## New rule action: `addFieldToCustomList` **Transaction**, **person**, and **company** rules may include `addFieldToCustomList`. On match, the engine extracts one or more fields from the evaluation context and appends them to tenant **custom lists** (`type: custom`, active, non-global). ```json theme={null} { "type": "addFieldToCustomList", "addFieldToCustomList": { "mappings": [ { "fieldPath": "originTaxId", "listId": "uuid-list-123" }, { "fieldPath": "metadata.phone", "listId": "uuid-list-456" } ], "reason": "Optional item reason" } } ``` Empty values are skipped; duplicate `primaryValue` entries are ignored. Available on universal rule `POST`/`PUT` and in the Rule Builder. **2026-07-08** Entity creation list enforcement ## Creation blocklist (risk analysis settings) Organizations can configure **creation blocklist rules** in **Organization settings → Risk analysis**: map an entity field (e.g. `taxId`) to a custom list. If the value is found in the list, **entity creation is blocked**: the request fails with **`422`** and error code **`ENTITY_CREATION_LIST_BLOCK`** (`details` include `ruleId`, `listId`, `fieldPath`, `scope`, `matchedValue`). The blocked attempt is recorded in the audit log as evidence. Applies to **`POST /entities`**, **`POST /entities/automatic`**, bulk import, upsert create path, and SDK auto-entity creation. Shareholder/UBO checks run during automatic creation when scope is configured; if a shareholder is blocked, the entities created in that automatic run are rolled back. **2026-07-03** PATCH /entities/\{id}/attributes ## Dedicated attributes update endpoint **`PATCH /entities/{id}/attributes`** — update only custom attributes without touching other entity fields. * **`mode: merge`** (default) — sent keys overwrite or create; omitted keys are **kept** * **`mode: replace`** — body `attributes` becomes the full map (`{}` clears all) * Nested category buckets supported on write (same as entity update) * Triggers **`entity.updated`** webhook and risk matrices with **`entity_updated`** trigger when configured See [Update entity attributes](/en/api-reference/entities/attributes-update). **2026-07-03** Entity attributes: verbatim storage + categories ## Custom attributes stored verbatim (API) **Additive.** `attributes` are stored **exactly as sent** on create/update/upsert/automatic import paths — nested input is no longer flattened. * **Uncategorized:** scalar/array values at the root (e.g. `{ "phone": "..." }`) — unchanged. * **Categorized:** a top-level object groups its inner keys under that category (e.g. `{ "contact": { "phone": "..." } }`). The object key *is* the category; in the dashboard it renders as a category card. * **Read:** `GET` returns the same shape that was written (no flattening). * **Rules / webhooks:** read the stored shape — `attributes.phone` for flat, `attributes.contact.phone` for nested. Use identifier-safe category keys. See [Get entity](/en/api-reference/entities/get) and [Update entity](/en/api-reference/entities/update). **2026-07-03** Entity country activations API + webhook ## Per-merchant country activation (operational flag) **Additive.** Activate or deactivate supported countries per entity without changing entity profile data: * **`GET /entities/{id}/country-activations`** — lists AR, BR, CL, CO, MX, US; missing rows = `deactivated` (opt-in). * **`PATCH /entities/{id}/country-activations/{countryCode}`** — body `{ "status": "deactivated" | "activation_requested" | "activation_in_progress" | "activated" }`; requires `entities:edit`. Free-form transitions. Idempotent when status unchanged (no webhook). * **Webhook `entity.country_activation_changed`** — emitted on every real status change; includes `activeCountryCodes`, full `countries` snapshot, and per-country `timeline`; subscribe via existing webhook config. See [List country activations](/en/api-reference/entities/country-activations-list), [Update country activation](/en/api-reference/entities/country-activations-update), and [Entity webhook events](/en/webhooks/events/entity-events). **2026-07-01** Bulk import: user events error policy parity ## User event batch import — row error policy **Additive.** User event CSV imports now match entity and transaction batch behavior: * **`POST /batch-import/import/user-events`** accepts optional multipart field **`batchErrorHandling`**: `continue_collect_errors` (default), `rollback_all`, or `stop_keep_success`. * **`202`** responses include **`preflightFailures`** when invalid rows are skipped under continue policy. * **`POST /batch-import/validate-csv`** validates **each row** when the mapping target is **`user_event`** (`rowErrors`, `validRowCount`, `invalidRowCount`). See [Import user events](/en/api-reference/bulk-imports/import-user-events) and [Validate CSV](/en/api-reference/bulk-imports/validate-csv). **2026-07-01** Rules create: mandatory AI review + provenance ## `POST /rules` — synchronous AI review on every create * New rules are always stored as **`in_progress`** with **`enabled: false`**; request `status` / `enabled` on create are ignored. * The response includes **`aiReview`** (verification summary) and may take several seconds. * Optional body **`creationProvenance`** records origin (`user`, `agent`, `import_json`, `template`, `bundle`, `api`) and optional agent chat ids. * AI review is audited but **not debited** from the AI token wallet. See [Create Rule](/en/api-reference/rules/create). **2026-06-26** Security webhooks: invitation context fields ## `security.member.invited` / `security.member.created` — richer `payload.context` **Additive.** Invitation lifecycle webhooks now include correlation and access metadata in `payload.context`: * `invitationId` — correlate `invited` → `created` * `granularRoleIds`, `granularRoleIdsSandbox` * `includeProduction`, `includeSandbox` * `teamId`, `teamIdSandbox` * `hasEnvironmentAccess` — access flag for the org in the envelope * `environment` — `"production"` or `"sandbox"` for the envelope org * `invitedByUserId`, `acceptedVia` (on `created`) * `syncPartialFailure`, `syncErrorMessage` (on `created` when secondary setup did not fully complete) Existing fields are unchanged. See [Security webhook events](/en/webhooks/events/security-events). **2026-06-26** Batch import: poll job status by jobId ## Batch import job polling **Additive.** New canonical endpoint for integrators to poll a single batch import job without scanning paginated history. ### HTTP endpoints * `GET /batch-import/jobs/{jobId}` — direct lookup by job id across entity, transaction, and user-event imports. Returns `status`, counters (`totalItems`, `succeeded`, `failed`, `skipped`), timestamps, and optional `jobFailure` when the whole job aborted. Optional query `include=failures` returns the same JSON as the kind-specific failures endpoints (row-level `failures[]`). * `GET /batch-import/unified-history` — new optional query param **`jobId`** (exact match; 0 or 1 row). Unified history remains for listing recent jobs; use `GET /batch-import/jobs/{jobId}` for polling after upload. ### Recommended integrator flow Upload (`202` + `jobId`) → poll `GET /batch-import/jobs/{jobId}` every 2–5s until terminal status → fetch failures if needed. See [Get batch job status](/en/api-reference/bulk-imports/get-batch-job-status) and [Unified history](/en/api-reference/bulk-imports/list-unified-history). **2026-06-25** Holder CBU/CVU intelligence: exists + accounts-count + metrics ## Holder CBU/CVU intelligence (`ar_gueno_holder_intelligence_service`) **Additive.** Account totals endpoint is `accounts-count` (replaces pre-release `cbu-count`). Returns `snapshotDate`, `isNew`, `cbuCount`, `cvuCount`, and `totalAccounts`. ### HTTP endpoints * `GET /api/integration-services/ar_gueno_holder_intelligence_service/health` — service availability and corpus freshness (`status`, `corpusFreshnessDate`). **No billing.** * `GET /api/integration-services/ar_gueno_holder_intelligence_service/cuits/:cuit/exists` — corpus membership check. Returns `found` and `snapshotDate` (`null` when not found). Always HTTP `200` on success (including `found: false`). **No billing.** * `GET /api/integration-services/ar_gueno_holder_intelligence_service/cuits/:cuit/accounts-count` — CBU/CVU totals plus `isNew` and `snapshotDate`. **Billable per request** when priced. * `GET /api/integration-services/ar_gueno_holder_intelligence_service/cuits/:cuit/metrics` — densified incremental lookback (`lookback` 1–180 **or** `window` preset `w_1d`…`w_180d`). Optional query `date` (`YYYY-MM-DD`, inclusive window end). Returns stock aliases, deltas, `%`, variance, and acceleration. **Billable per request** when priced. Errors: `400` `LOOKBACK_REQUIRED` / `INVALID_LOOKBACK` / `INVALID_WINDOW` / `INVALID_DATE`, `404` `CUIT_NOT_FOUND`, `422` `INCOMPLETE_WINDOW` / `NO_INCREMENTAL_STATE`. ### Rules engine New condition fields under `services.holder_intelligence.*`: `found`, `snapshot_date`, `cbu_quantity`, `cvu_quantity`, `total_accounts`, and nested `metrics.*` with per-condition `holderIntelligenceLookbackDays` (1–180). On transaction rules the window ends on `transactedAt` by default. Metrics trigger a separate billable upstream fetch when referenced. See [Provider codes](/en/api-reference/integrations/provider-codes) and [Marketplace Services](/en/api-reference/services/overview) (per-endpoint reference). **2026-06-26** Marketplace Services documentation section ## Marketplace Services docs (en / es / pt) New sidebar section **Services** with overview, per-service guides, and one page per HTTP endpoint for `ar_gueno_holder_intelligence_service`. [Services overview](/en/api-reference/services/overview). **2026-06-24** KYC & biometric: entityTaxId / entityExternalId ## Entity identifiers beyond `entityId` **Additive — backward compatible.** Existing clients sending only `entityId` behave unchanged. ### Create (POST) * `POST /api/kyc/validations` — body accepts **`entityId`**, **`entityExternalId`**, or **`entityTaxId`** (exactly one required). * `POST /api/kyc/biometric/sessions` — same identifier options. Gu1 resolves `entityExternalId` / `entityTaxId` to the internal entity UUID. Returns **`404 NOT_FOUND`** if no persisted entity matches. ### Read (GET) * `GET /api/kyc/validations?entityTaxId=...` or `?entityExternalId=...` (mutually exclusive with `entityId`). * `GET /api/kyc/biometric/sessions?entityTaxId=...` or `?entityExternalId=...` * KYC: `GET /api/kyc/entities/by-tax-id/:taxId/current|validations|status` and `.../by-external-id/:externalId/...` * Biometric: `GET /api/kyc/biometric/entities/by-tax-id/:taxId/current` and `.../by-external-id/:externalId/current` ### Sandbox entity preview (GET only) * `GET /api/entities/by-tax-id/{taxId}` and `GET /api/entities?taxId=...` may return **`sandboxMock: true`** synthetic data for catalog test document numbers when no real row exists (`id: null`). Does **not** enable POST without creating a real entity. See [Create KYC validation](/en/use-cases/kyc/create-validation), [Embedded biometric session](/en/use-cases/kyc/embedded-biometric), and [Sandbox mock data](/en/use-cases/kyc/sandbox-mock-data). **2026-06-23** KYC & biometric create: blocking IDs on 409 ## Additive 409 responses for open sessions / validations **No breaking change** for clients that only read `error` and `message`. New optional fields on existing `409` codes: ### Embedded biometric — `POST /api/kyc/biometric/sessions` * While the latest session is `pending` or `in_progress`, create **always** returns **`409 ACTIVE_SESSION_EXISTS`** (never `201` with the same pending session). * Body includes **`activeSessionId`** for cancel: `POST .../sessions/{activeSessionId}/cancel`. ### KYC validation — `POST /api/kyc/validations` * While the entity has an open validation (`pending`, `in_progress`, `in_review`), create returns **`409 VALIDATION_IN_PROGRESS`**. * Body now also includes **`activeValidationId`** for cancel: `DELETE .../validations/{activeValidationId}/cancel`. See [Create KYC validation](/en/use-cases/kyc/create-validation) and [Embedded biometric session](/en/use-cases/kyc/embedded-biometric). **2026-06-20** GET transaction: optional rulesExecutionSummary on persisted ## `includeRulesSummary` on single-transaction GET `GET /transactions/{id}` and `GET /transactions/external/{externalId}` accept an optional query parameter: * **`includeRulesSummary=full`** — Adds **`persisted.rulesExecutionSummary`** from the **latest** `risk_analysis_audits` row for that transaction. Rules are **not** re-executed on read. **Default (param omitted):** unchanged response — no `rulesExecutionSummary` on read. Use `full` only for detail views or debugging, not high-volume list polling. See [Get transaction](/en/api-reference/transactions/get) and [Rules execution summary](/en/api-reference/rules-execution-summary). **2026-06-19** Rules execution summary: transaction party entity status ## Optional fields in `rulesExecutionSummary` When transaction rules use `updateEntityStatus` with origin or destination party entity status, the API may now include these **optional** fields (additive; existing clients unchanged): * **`rulesHit[].actions.originEntityStatus`** / **`destinationEntityStatus`** — configured on the matched rule. * **`actionsExecuted.originEntityStatus`** / **`destinationEntityStatus`** — final entity statuses applied in that run (alongside existing **`actionsExecuted.status`** for transaction status). Audit rule snapshots now retain the full configured action list (including deferred status actions) for UI and integrators. See [Rules Execution Summary](/en/api-reference/rules-execution-summary). **2026-06-19** Security webhooks: unified member + environments ## `security.member.*` events (unified naming) All IAM events about people use the **`security.member.*`** prefix (no more `security.user.*`, `security.team.*`, or `security.channel.*`): * **Profile / password:** `security.member.profile_updated`, `.password_reset`, `.password_generated` * **Teams:** `security.member.team_added`, `.team_removed`, `.team_role_changed` * **Channels (child org):** `security.member.channel_granted`, `.channel_revoked` * **Environment access (production / sandbox):** `security.member.environment_granted`, `.environment_revoked` — use `context.environment` (`"production"` | `"sandbox"`) Team membership changes no longer emit misleading `security.role.assigned` / `security.role.updated` events. **Breaking:** if you subscribed to `security.user.password_*` or other legacy keys, migrate to the matching `security.member.*` keys. See [Security webhook events](/en/webhooks/events/security-events). **2026-06-19** Biometric current session endpoint ## `GET /api/kyc/biometric/entities/:entityId/current` Aligned with KYC `GET /api/kyc/entities/:entityId/current`: * Returns the **latest biometric session** for the entity (by `createdAt`), **any status** (`pending`, `in_progress`, `approved`, `rejected`, …). * **`200` with `null`** when the entity has no biometric sessions (no longer `404`). * List endpoint `currentSessionId` still refers to the latest **`approved`** session only. **`409 ACTIVE_SESSION_EXISTS`** on create now includes **`activeSessionId`** so integrators can cancel the blocking session without an extra lookup. See [Current biometric session](/en/use-cases/kyc/current-biometric-session). **2026-06-18** Security & IAM webhook events ## Security webhook events (`security.*`) New outbound webhook category for **Security / IAM** monitoring (SIEM integrations). Subscribe in **Webhooks → Configuration** to events such as: * **Auth:** `security.auth.login_succeeded`, `security.auth.logout`, `security.auth.login_failed` * **Members:** `security.member.invited`, `.created`, `.removed`, `.activated`, `.deactivated` * **Roles:** `security.role.created`, `.updated`, `.deleted`, `.assigned`, `.revoked` * **RBAC:** `security.rbac.granular_toggled` * **Password (admin):** `security.member.password_reset`, `security.member.password_generated` (formerly `security.user.password_*`) * **Settings:** `security.settings.updated` (sandbox, audited org security settings) Payload includes normalized `actionAt`, `actor`, `affectedUser`, `description`, `changes` (previous/current), and `context` (IP, user agent, scope). **Not covered:** Clerk self-service password change, MFA/SSO in Clerk, API-key auth. See [Security webhook events](/en/webhooks/events/security-events). **2026-06-18** Risk matrix watchFields + entity\_updated runtime ## Granular matrix triggers (`watchFields`) Risk matrix event triggers **`entity_updated`** (entities and KYT transaction updated) support optional **`watchFields`**: an array of rule-engine field paths (e.g. `email`, `phone`, `attributes.clientTypes`, `metadata.email`). When omitted or empty, **any** change on that event runs the matrix (backward compatible). When set, the matrix runs only if at least one listed path changed. Configure in the Risk Matrix editor (Triggers tab) or via API in `risk_matrices.triggers[]`. ## Entity update — `entity_updated` wired `PATCH /entities/{id}` (and by external ID / tax ID) now runs assigned matrices whose triggers include **`entity_updated`**, unless `skipRulesExecution: true`. The `entity.updated` webhook includes `rulesExecutionSummary` when rules ran or were skipped with a reason. See [Update entity](/en/api-reference/entities/update). Transaction `PATCH` with `executeRules=true` passes changed field paths to the same filter for transaction matrices. **2026-06-17** Bulk entity import — child enrichment policy ## Bulk automatic entity import — child enrichments & monitoring scope **`POST /batch-import/import/entities`** and JSON bulk automatic import accept two optional fields (automatic mode, `depth` > 0): * **`childEnrichmentPolicy`**: `all_active` (default), `by_root_type`, or `basic_only`. * **`by_root_type`**: company rows run all active enrichments on shareholders **except** `global_gueno_sanctions_enrichment`; person rows create related entities with **basic data only** from the root provider snapshot. * **`monitoringApplyToRelationships`**: when `false`, `monitoring` applies to main entities only (no watchlist on children). Default `true` when `depth` > 0 if omitted. The dashboard bulk entity import UI exposes the same controls. See [Import entities (bulk)](/en/api-reference/bulk-imports/import-entities#child-enrichments--monitoring). **2026-06-16** SDK pre-login events and remote config ## Events — SDK session fields and pre-login `POST /events/user` now accepts two optional fields: **`sessionId`** (SDK session id, `sess_...`) and **`sdkSignals`** (structured SDK signals — integrity and behavioral flags, kept separate from `metadata`). Both persist on the event. **Omitting them keeps the previous behavior byte-for-byte.** For organizations with the SDK enabled, an event carrying **only a `sessionId`** (no `entityId`/`entityExternalId`/`taxId`) is now accepted and stored as an **anonymous pre-login event** instead of returning an error; it is linked to the entity later, on the first event that carries both `sessionId` and an entity identifier. Without the SDK enabled, an entity identifier is still required (same response as before). ## Events — new event types Three SDK event types were added: **`SESSION_STARTED`**, **`SESSION_IDENTIFIED`**, **`SCREEN_VIEW`**. Existing clients are unaffected. ## New endpoint — `GET /sdk/config` Returns the SDK remote config (signal toggles + transport defaults) plus the organization's `sdkEnabled` flag. See [Create User Event](/en/api-reference/events/create). **2026-06-15** Enrichment errors and tax ID validation ## Marketplace enrichment — structured errors `POST /integration-execution/marketplace/enrichment` now returns richer per-integration `error` objects: optional `category`, `retryable`, and `statusCode` alongside `code` and `message`. Codes distinguish configuration issues (integration not enabled), timeouts, provider HTTP failures, and validation errors. ## Automatic / bulk entity creation — tax ID strictness `taxId` on automatic and bulk creation must be **only** the fiscal identifier. Values merged with spreadsheet columns (e.g. CNPJ plus business segment text) are rejected with `INVALID_TAX_ID`. ## Transactions — optional `exchangeRate` fallback `POST /transactions` and batch create accept optional **`exchangeRate`** on each transaction. **Omitting it keeps the previous behavior** (automatic conversion via the currency service). Used **only** when automatic conversion is unavailable. Semantics: base-currency units per 1 unit of `currency`; normalized base amount = `amount × exchangeRate`. Sets `rateSource: client-provided`. **Non-convertible today (no automatic rate):** `WLD` (Worldcoin), `ETH` (Ethereum). Send `exchangeRate` for a normalized base-currency amount and FX-dependent rules. See [Create Transaction — Currency conversion](/en/api-reference/transactions/create#currency-conversion). **2026-06-11** Entities — refresh scope and preserve flags ## `POST /entities/{entityId}/refresh` — unified scope and safe field sync New optional body fields (all backward compatible when omitted): * **`refreshScope`**: `basic_data` | `all_active` | `selected` (+ `providerCodes` when `selected`). * **`preserveName`**: `true` keeps the current display name; omitted = legacy sync from normalized `fullName`. * **`preserveEntityData`**: only with `refreshScope: "basic_data"` — `true` gap-fills `entityData`, `false` replaces; omitted = do not touch profile. `basic_data` always runs root-only (no shareholders), regardless of `depth`. See [Refresh Entity](/en/api-reference/entities/refresh). Existing Risk Matrix / integration payloads without these fields behave unchanged. **2026-06-11** KYC — cross-entity duplicate warning ## `GUENO_CROSS_ENTITY_DUPLICATED` warning When Gu1 resolves provider duplicate session/face references to **another entity** in the same organization (`metadata.kycCrossEntityDuplicates.matches`): * Appends warning **`GUENO_CROSS_ENTITY_DUPLICATED`** to session validation `warnings`. * If the provider mapped **`approved`**, Gu1 sets status to **`in_review`** (`metadata.guenoCrossEntityDuplicateEscalation`). * **Non-omittable:** cannot be sent in `omitWarnings` (400) and blocks omit auto-approve. Documented in [KYC warning risk codes](/en/use-cases/kyc/warning-risk-codes) and [`omitWarnings`](/en/use-cases/kyc/create-validation). **2026-06-11** KYC — Gu1 Biometric ## Gu1 Biometric (`POST /api/kyc/biometric` and `/api/kyc/biometric/sessions`) Re-authentication after approved KYC: image upload check or **hosted UI** session (`sessionUrl`, `iframeAllow`, `hostedSessionId`, optional `webhookUrl`, org webhooks `biometric.session_*`, Gu1 **`status`** / `rejectionCode`). Marketplace product `global_gueno_biometric_kyc`. See [Biometric verification](/en/use-cases/kyc/biometric), [Biometric session](/en/use-cases/kyc/embedded-biometric), and [Biometric webhook events](/en/webhooks/events/biometric-events). **2026-06-10** KYC — decision dual array/object shape ## `decision` always includes array + object feature pairs On persist (sync, webhook ingest, manual ingest), Gu1 **normalizes** `decision` so integrators can read either legacy singular keys or array keys interchangeably: * `id_verification` ↔ `id_verifications[0]` * `liveness` ↔ `liveness_checks[0]` * `face_match` ↔ `face_matches[0]` * `aml_screening` ↔ `aml_screenings[0]` * `ip_analysis` ↔ `ip_analyses[0]` When both shapes were present, **`array[0]` wins** and the singular object is synchronized. Applies to GET validation responses and KYC webhooks (`payload.decision`). Mintlify examples updated with **complete** `decision` payloads (no vendor branding; media as `kyc/...` keys). See [KYC webhook events](/en/webhooks/events/kyc-events#decision-object-payloaddecision). **2026-06-10** Risk matrix — rulesEngineConfig on analyze ## Per-run rules engine config on `POST /entities/{entityId}/analyze` New optional body object **`rulesEngineConfig`** (all fields default **`false`**): * **`partialCoverage`:** with multiple assigned matrices, data coverage is validated **per matrix**; matrices without data are skipped (`matricesSkippedForCoverage` / `warnings` on partial success). * **`omitCoverage`:** skip data coverage gates entirely (main entity + shareholders). Precedence over `partialCoverage` when both are true. Default unchanged: union coverage blocks the whole run on any missing field (`422 INCOMPLETE_DATA_COVERAGE`). See [Analyze Entity](/en/api-reference/entities/analyze) and [Execute Risk Matrix](/en/api-reference/risk-matrix/execute-risk-matrix). **2026-06-09** KYC — extractedData.ejemplar (Argentine DNI) ## `ejemplar` in extractedData Argentine DNI verifications can include **`extractedData.ejemplar`** (`A`–`D`) on KYC validations and ID Verification audit records (GET, sync, webhooks). With **`doubleCheckRenaper: true`**, **`comparisonResults.ejemplar`** compares OCR vs RENAPER; mismatch adds **`RENAPER_EJEMPLAR_NOT_MATCH`** to **`warnings`**. See [extractedData fields](/en/use-cases/kyc/id-verification#extracteddata-fields) and [RENAPER double-check](/en/use-cases/kyc/create-validation#renaper-double-check-argentina). **2026-06-05** KYC — RENAPER flow and manual review ## RENAPER double-check on KYC validations With `doubleCheckRenaper: true`, `metadata.responseDoubleChecks.renaper` includes **`comparisonResults`**, **`renaperBiometric`** (when applicable), and RENAPER codes in **`warnings`** (e.g. `RENAPER_TRAMITE_ID_NOT_MATCH`, `RENAPER_EXPIRY_NOT_MATCH`) **without replacing** OCR KYC verification warnings. **Enforcement (auto-reject):** only when OCR KYC verification returns status **`approved`**. On **`in_review`** and **`rejected`** the check is informational and stores registry data. **`POST /api/kyc/validations/{id}/approve`** from `in_review` does **not** re-run RENAPER. See [Create KYC validation](/en/use-cases/kyc/create-validation#when-renaper-enforcement-applies-automatic-rejection) and [Approve validation](/en/use-cases/kyc/approve-validation). **2026-06-04** Marketplace — checks removed, enrichments only ## Marketplace `*_check` product removed * **Removed:** all `*_check` provider codes, `POST /integration-execution/marketplace/check`, rules triggers/actions `check_completed` / `execute_check`, and RBAC permissions `checks:read` / `checks:execute`. * **Use instead:** matching `*_enrichment` codes with [Execute enrichment](/en/api-reference/enrichment/execute-by-id). * **Backward compat:** legacy create/import payloads with `checks`, `executeAllActiveChecks`, or `*_check` inside `autoExecuteIntegrations.enrichments` are **silently ignored** at parse time. See [Provider codes](/en/api-reference/integrations/provider-codes), [Create entity](/en/api-reference/entities/create), and [Create automatically](/en/api-reference/entities/create-automatic). **2026-06-04** Bulk imports — failure codes + JSON failures ## Stable batch failure codes and JSON endpoints * **Row failures** now include stable **`code`** + **`message`** (catalog: [Failure codes](/en/api-reference/bulk-imports/batch-import-failure-codes)). CSV adds a `code` column (`external_id,code,error` / `row_key,code,error` / entity `…,code,error_message`). * **New JSON endpoints:** `GET /batch-import/transaction-jobs/{jobId}/failures`, `GET /batch-import/user-event-jobs/{jobId}/failures`, `GET /batch-import/entity-jobs/{jobId}/failures` — include `failures[]`, optional `jobFailure` for whole-job errors, entity `skips[]`, `truncated` / `failuresTotal` (max 500 stored). * **CSV download:** same routes with `.csv` suffix (`failures.csv`). * Legacy rows with only free-text `error` are normalized on read when possible. **2026-06-04** Entities — PATCH riskMatrixIds ## Assign risk matrices on entity update * **`PATCH /entities/{id}`** (and **`PATCH /entities/by-external-id/{externalId}`**, **`PATCH /entities/by-tax-id/{taxId}`**): document **`riskMatrixIds`** (`string[]`) and **`riskMatrixId`** (`string | string[] | null`) — same normalization as create. Assigns matrices on the entity; does **not** run the rules engine (use [Analyze entity](/en/api-reference/entities/analyze) or lifecycle triggers). * Mintlify updated in `/en/`, `/es/`, `/pt/` on [Update entity](/en/api-reference/entities/update) and [Update by external ID](/en/api-reference/entities/update-by-external-id). **2026-06-03** Transactions — configRulesExecution.notifications ## `configRulesExecution` on create transaction * **`POST /transactions`**: optional body object **`configRulesExecution`** with **`notifications`** (`boolean`). When `false`, gu1 skips **in-app** notifications from rules evaluation (risk matrix / status). **`createAlert`** actions and investigations are unchanged. * **Default:** omitting the object keeps prior behavior for most orgs (`notifications` effectively `true`). **Paytime prod** (`3bc1f621-27d4-423e-9d64-86680bec2388`) defaults to **`notifications: false`** when omitted. * **Legacy KYT** `POST /legacy/kyt/verifyTransaction`: same field on the Gu2 body; Paytime prod default **`notifications: false`** when omitted (normalized before create). * Applies to **sync and async** rules (`asyncRules`). See [Create transaction](/en/api-reference/transactions/create). Parity in `/es/` and `/pt/`. **2026-06-02** Transactions — canonical entity denormalization on link ## `POST /transactions` and batch create — linked counterparty fields When origin or destination is **linked** to a person/company (`originEntityId` / auto-link by external or tax id), gu1 **always overwrites** denormalized columns from the entity row before insert: * `originTaxId` / `destinationTaxId` ← `entities.tax_id` * `originExternalId` / `destinationExternalId` ← `entities.external_id` Client-sent values for those fields are **not kept** if they differ from the linked entity. This aligns transaction monitoring rules with user events stored under the same entity identifiers. Documented in [Create transaction](/en/api-reference/transactions/create#origin-entity-fields) and [Create batch](/en/api-reference/transactions/create-batch). Parity in `/es/` and `/pt/`. **2026-06-02** User events — isNewDevice client priority ## `POST /events/user` — `isNewDevice` honors integrator value * If you send **`isNewDevice: true` or `false`**, gu1 **persists exactly that value** (no server override). * If you **omit** the field, gu1 infers it when **`deviceId` + `deviceDetails`** are present (device registry; `true` when the device is new or `firstSeenAt` is within the last **5 minutes**); otherwise **`false`**. Documented in [Create user event](/en/api-reference/events/create#how-isnewdevice-works) and [Events overview](/en/api-reference/events/overview). Parity in `/es/` and `/pt/`. **2026-06-01** Entity import — attributes / entityData dot notation ## Platform CSV: `attributes.*` and `entityData.*` * Dotted headers (same approach as native transaction CSV): `attributes.segment_tag`, `entityData.income`, `entityData.tradeName`. * **`entityData.`** without `person`/`company` uses the row **`type`** bucket. * Unprefixed columns (`segment_tag`) still map to `attributes` (backward compatible). * See [Import entities (CSV)](/en/api-reference/bulk-imports/import-entities). **2026-06-01** Bulk imports — limits and manual vs automatic ## Import limits documented (en / es / pt) * [Bulk imports overview](/en/api-reference/bulk-imports/overview): matrix of **max files per request**, **max rows by plan**, and **manual vs automatic** entity import. * Per-endpoint pages now include limits: [Import entities (CSV)](/en/api-reference/bulk-imports/import-entities), [Import transactions](/en/api-reference/bulk-imports/import-transactions), [Import user events](/en/api-reference/bulk-imports/import-user-events). * CSV entity import uses **plan limits** (4k–100k). Runtime caps: `GET /individual-organization/batch-upload-enabled`. Parity in `/es/` and `/pt/` docs. **2026-06-01** Entity import — countries by mode ## Bulk entity import countries (manual vs automatic) * **Manual** (`manual`): any **valid platform ISO2** (batch or per-row `country` / `country_code`). * **Automatic** (`automatic`): **AR**, **BR**, and **CL** (basic data by tax ID, including Chile ruts.info / BaseAPI enrichments). * Applies to **`POST /batch-import/import/entities`** (platform CSV and custom CSV with `mappingId`). See [Import entities (CSV)](/en/api-reference/bulk-imports/import-entities). **2026-06-01** Entity import — manual multipart alignments ## `POST /batch-import/import/entities` — manual mode enrichments * **Manual** multipart now matches the dashboard **Manual** hub mode: optional **`autoExecuteIntegrations`**, **`monitoring`**, and risk matrices — **without** the country basic-data pipeline (Nosis/CPF). * CSV-only upload (no `autoExecuteIntegrations`) still creates **minimal** entities with **no** enrichments. * Per-row CSV enrichment columns apply in manual mode; **`depth`** / shareholders remain **automatic-only**. See [Import entities (CSV)](/en/api-reference/bulk-imports/import-entities). **2026-06-01** Entity import — API default manual ## `POST /batch-import/import/entities` — manual default * Omitting **`entityImportMode`** → **`manual`** (minimal entity; enrichments only when explicitly requested). * **Automatic** with **`entityImportMode=automatic`** (+ optional `autoExecuteIntegrations`, `depth`, etc.). * Manual mode requires **`suggested_name`** on every row (`400` if missing). * Template **`bulk-entities-template.csv`**: documented columns; demo row without active enrichments. * **`202`** response includes effective **`importMode`**. See [Import entities (CSV)](/en/api-reference/bulk-imports/import-entities). **2026-06-01** Entity import — platform CSV without mappingId ## `POST /batch-import/import/entities` — platform format * **`mappingId` optional** for platform CSV headers. Import default: **`manual`** (see next changelog entry on this date). See [Import entities (CSV)](/en/api-reference/bulk-imports/import-entities). **2026-06-01** Async transaction rules evaluation ## `asyncRules` on create transaction * **`POST /transactions`**: optional query or body flag **`asyncRules`** (default **`false`**). When `true` and `executeRules` is not `false`, the transaction is created in the same request but rules run **in the background** via a job queue. The HTTP response returns immediately with empty `rulesHit` / `rulesNoHit`, plus **`asyncRules: true`** and **`rulesEvaluationStatus: "queued"`**. * **Default unchanged:** omitting `asyncRules` keeps **synchronous** rules execution and a full `rulesExecutionSummary` — existing clients behave exactly as before. * **Legacy KYT** `POST /legacy/kyt/verifyTransaction`: same flag via query or Gu2 body field. **Paytime prod** (`3bc1f621-27d4-423e-9d64-86680bec2388`) defaults to async when the flag is omitted; use `asyncRules=false` to force synchronous rules for a single request. * **Not on batch endpoints.** If Redis/queue is unavailable, API may return **503** `ASYNC_RULES_QUEUE_UNAVAILABLE` (transaction may already exist — check response body before retry). See [Create transaction](/en/api-reference/transactions/create). **2026-05-29** Face Match & ID Verification — RENAPER double-check ## RENAPER double-check on standalone KYC endpoints * **`POST /api/kyc/face-match`**: optional `doubleCheckRenaper` (body or `?doubleCheckRenaper=true`). After Gu1 face match approves, runs RENAPER **biometric** (`validate-dni` with selfie) and **data** (DNI + trámite). Requires `documentNumber`, `gender`, and `personalNumber` (or entity fallback for DNI/gender). Response adds `responseDoubleChecks.renaper` (including nested `renaperBiometric` when biometric check runs). * **`POST /api/kyc/id-verification`**: same flag; after OCR approval runs RENAPER **data** check only (fields from `extractedData`). Failed checks set `status` to `declined` and add RENAPER codes to `warnings`. * Org **RENAPER credentials** required (same as session KYC). Use HTTP timeout ≥ 60s for face-match with double-check. See [Face Match](/en/use-cases/kyc/face-match) and [ID Verification](/en/use-cases/kyc/id-verification). **2026-05-29** Transaction status-change rule trigger ## KYT — separate status-change vs field-update triggers * **`PATCH …/changeStatus`** now runs rules/matrices with trigger **`status_changed`** (`trigger_transaction_status_changed`), not `updated`. * **`PATCH /transactions/{id}`** (metadata, **deviceDetails**, channel, reason) with `executeRules=true` still uses **`updated`** (`trigger_transaction_updated`). * **Migration:** reconfigure rules that must run on status transitions to the new trigger (Rule Builder: *On transaction status change*; matrices: `transaction_status_changed`). Rules with only `updated` / *Transaction updated* no longer run on changeStatus. See [Change status](/en/use-cases/transaction-monitoring/change-status-api) and [Update transaction](/en/api-reference/transactions/update). **2026-05-29** PATCH transaction — metadata, deviceDetails, channel, reason ## Partial transaction update * **`PATCH /transactions/{id}`** and **`PATCH /transactions/external/{externalId}`**: update **`metadata`** (shallow merge — omitted keys are preserved), **`deviceDetails`** (shallow merge into `device_details`), **`channel`** (nullable), and/or **`reason`** (enum). Requires `transactions:edit`. * Query **`executeRules=true`** optionally re-runs KYT rules with trigger **`updated`** (`trigger_transaction_updated`) — not status-change rules. * Emits audit `transaction_updated` and webhook `transaction.updated` with a `changes` map (includes `deviceDetails` when patched). See [Update transaction](/en/api-reference/transactions/update). **2026-05-29** Has events by entity — query identifiers ## User events — has-events by external ID or tax ID * **`GET /events/user/entity/has-events`** (new): boolean check without the internal entity UUID. Query params: `entity_id`, `entity_external_id`, or `tax_id` (at least one required). Lookup priority: `entity_id` → `entity_external_id` → `tax_id`; tax IDs are matched with normalization (non-alphanumeric stripped). * Response still includes resolved **`entityId`** so you can call [List by Entity](/en/api-reference/events/list-by-entity) when `hasEvents` is true. * **`GET /events/user/entity/{entityId}/has-events`** remains supported (unchanged contract). See [Has events by entity](/en/api-reference/events/has-events-by-entity). **2026-05-28** KYC IP analysis warning codes ## Session KYC — Device & IP analysis warnings * **`GET /api/kyc/validations/:id`** (and sync/webhook paths): the top-level **`warnings`** array now merges **`risk`** codes from **`decision.ip_analyses[].warnings[]`** (and legacy `decision.ip_analysis.warnings`), alongside ID verification, liveness, face match, and AML. * Eight provider codes are supported (e.g. `PRIVATE_NETWORK_DETECTED`, `DUPLICATED_DEVICE_FINGERPRINT`, `IP_ADDRESS_IN_BLOCKLIST`). See [KYC Warning Risk Codes — Device & IP Analysis](/en/use-cases/kyc/warning-risk-codes#device--ip-analysis-session-based-kyc). * The same codes are valid in **`omitWarnings`** on [`POST /api/kyc/validations`](/en/use-cases/kyc/create-validation) when auto-approving `in_review` sessions. **Integrator note:** Existing validations keep their stored `warnings` until the next sync; re-fetch or sync to backfill IP analysis codes on older rows. **2026-05-26** ID Verification extractedData expansion ## ID Verification — richer `extractedData` * **`POST /api/kyc/id-verification`** and audit list/get now persist and return a broader `extractedData` object: identity fields (`personalNumber`, `taxNumber`, `placeOfBirth`, …), `providerStatus`, `warningMeta` (e.g. duplicate session IDs), quality scores, `extraFields`, `mrz`, `parsedAddress`, `barcodes` when returned by the Gu1 ID Verification service. * **`warnings`** remains a string array of risk codes for i18n; use `warningMeta` inside `extractedData` for structured duplicate-session metadata. * External document image URLs and base64 are **not** returned; images you uploaded are available via [ID Verification images](/en/use-cases/kyc/id-verification-images). * **`debugProviderResponse`** may appear only in non-production Gu1 API environments (sanitized verification payload, no images). See [ID Verification](/en/use-cases/kyc/id-verification#extracteddata-fields). **2026-05-26** Entity operationalHours + KYT operational hours rules ## operational hours per entity (global) * **Entities:** Optional root field `operationalHours` (`timezone` enum + `weekly` slots). Stored in `entities.operational_hours`. Documented on [Create entity](/en/api-reference/entities/create) and related entity endpoints. * **Transactions:** `transaction_time_zone` enum extended (Brazil zones). Optional `timeZone` is independent of entity `operationalHours`. **`transactedAt`:** stored as UTC; ISO with `Z` unchanged for existing clients; optional local datetime + `timeZone` converts to UTC when both are sent. * **Rules:** New operators `outside_entity_operational_hours` and `inside_entity_operational_hours` on `transactedAt` with value `origin` or `destination`. Requires `operationalHours` on the linked entity. See [Create transaction](/en/api-reference/transactions/create) and transactional rules knowledge base. **2026-05-22** Optional timeZone on transactions ## `timeZone` on transactions * **Database:** New nullable column `time_zone` on `transactions` with enum type `transaction_time_zone` (IANA values such as `America/Argentina/Buenos_Aires`, `UTC`, etc.). Existing rows remain `null`. * **API:** Optional `timeZone` on `POST /transactions` and batch create; returned on `GET /transactions/{id}` and `GET /transactions/external/{externalId}` as `string | null`. See [Transaction Time Zone Enum](/en/api-reference/transactions/time-zone-enum) and [Create transaction](/en/api-reference/transactions/create). **2026-05-21** validateExistingEntity on transactions ## `validateExistingEntity` (transaction create) * **`POST /transactions`**: optional `validateExistingEntity` (default **`false`**). When `true`, every origin/destination identifier you send must resolve to an existing person/company; otherwise **400** `INVALID_ENTITY_REFERENCES` and no row is created. * **Batch** endpoints: default remains **`true`**. Use `validateExistingEntity: false` for permissive bulk import. * **Legacy KYT** `POST /legacy/kyt/verifyTransaction`: same field in the Gu2 body. See [Create transaction](/en/api-reference/transactions/create) and [Batch create](/en/api-reference/transactions/create-batch). **2026-05-21** Entity creation auto-execute ## `excludeEnrichments` on entity creation `autoExecuteIntegrations` and `autoExecuteIntegrationsShareholders` (manual `POST /entities`, `POST /entities/automatic`, bulk import, materialize) now accept **`excludeEnrichments`**: an array of provider codes removed from the final enrichment set after merge (including when `executeAllActiveEnrichments` is `true`). **`executeAllActiveChecks` and `checks` are no longer part of the public contract** for these objects. Legacy payloads that still send them are ignored at parse time. See [Create entity (automatic)](/en/api-reference/entities/create-automatic) and [Create entity](/en/api-reference/entities/create). **2025-01-27** v1.3.0 - Hosted Onboarding Page Documentation ## New: Hosted Onboarding Page Documentation Complete documentation for the Hosted Onboarding Page - the quickest way to implement KYC verification without code. ### What's New **Hosted Page Documentation:** * ✅ Complete customization parameters guide (branding, colors, layout) * ✅ Validation rules configuration (age verification, capture methods, duplicate detection) * ✅ Document validation rules (QR/barcode, MRZ, expiration dates, liveness) * ✅ Step-by-step integration guide with code examples * ✅ Visual flow diagram showing the complete process * ✅ Security best practices for session management * ✅ Mobile-responsive design confirmation **Key Features:** * 📱 Mobile-responsive design for all devices * 🎨 Full customization of colors, branding, and layout * 🔒 Comprehensive security guidelines * 📊 Visual sequence diagrams for clarity * 🌐 Support channel information for configuration changes ### Languages All documentation available in: * 🇺🇸 English * 🇪🇸 Español * 🇧🇷 Português ### Impact * Faster implementation for no-code solutions * Clear guidance on customization options * Enhanced security awareness * Better understanding of the hosted page workflow [View Hosted Page Documentation](/en/use-cases/kyc/hosted-page) **2025-01-09** v1.2.0 - KYC Documentation Enhancement ## KYC Pages Refinement Based on Client Feedback Major enhancement to KYC documentation based on 14 questions from client feedback. ### What's New **Complete Flow Documentation:** * ✅ Added comprehensive comparison table: Automatic vs Manual creation * ✅ Complete Risk Matrix configuration guide with dashboard instructions * ✅ Clarified shareholders feature (KYB only, not KYC) * ✅ Provider codes reference with usage examples * ✅ Detailed credit management section with costs and workflows **Overview Page:** * ✅ Webhooks vs manual polling explanation * ✅ Full KYC vs Individual Verifications comparison table * ✅ Comprehensive face matching security warning for banks/fintech * ✅ Enhanced API endpoints table with use cases **Create Validation Page:** * ✅ Complete sequence diagram showing full flow * ✅ Sandbox vs Production clarification * ✅ Duplicate entity handling with code examples * ✅ Expanded integrationCode documentation **Entities API:** * ✅ Marked optional fields with examples (attributes, entityData) * ✅ Minimal vs full entity creation examples ### Languages All improvements available in: * 🇺🇸 English * 🇪🇸 Español * 🇧🇷 Português ### Impact * 14 client questions answered inline * 12 documentation files updated * 0 broken links * Improved developer onboarding experience [View KYC Documentation](/en/use-cases/kyc/overview) **2025-01-08** v1.1.0 - Multi-language Support ## Enhanced Multi-language Documentation Improved documentation structure with complete Spanish and Portuguese translations. ### Changes * Complete translation coverage for KYC, KYB, and Transaction Monitoring * Consistent terminology across all languages * Language-specific examples (CPF for Brazil, DNI for Spain, etc.) ### Available Languages * English (EN) - Primary * Spanish (ES) - Complete * Portuguese (PT) - Complete **2024-12-20** v1.0.0 - Initial Release ## gu1 Documentation Launch Initial release of comprehensive API documentation. ### Core Features * Complete API reference for all endpoints * Use case guides (KYC, KYB, Transaction Monitoring) * Webhook integration guides * Interactive tutorials * Multi-language support ### Components * Person entities API * Company entities API * KYC validation workflows * Transaction monitoring * Rules engine * Risk matrices * Alerts and investigations [Get Started](/en/quickstart) # Dashboard sessions (one device at a time) Source: https://docs.gu1.ai/en/dashboard-session-policy How gu1 dashboard login behaves when you use multiple browsers or devices — covering single-device login, idle timeout, and security limits. ## Overview When you sign in to the **gu1 dashboard** (e.g. [app.gu1.ai](https://app.gu1.ai)) with your user account, only **one active session** is kept for that account at a time. ## What This Means for You If you are already signed in on **device or browser A** and you sign in with the **same user** on **device or browser B**, the session on **A** is ended automatically. You will need to sign in again on A if you want to use the dashboard there. This applies to the **interactive dashboard** (web UI), not to **API keys**: server-to-server integrations that use API keys are not affected by dashboard session limits. ## Practical Tips * Use a **single browser profile** for day-to-day work to avoid unexpected sign-outs. * If your session ends unexpectedly, check whether a colleague or another device signed in with the same account. # Welcome to gu1 Source: https://docs.gu1.ai/en/introduction Discover gu1, an AI risk analysis and compliance platform for banks and fintechs covering KYB, KYC, AML, transaction monitoring, and case management. ![gu1 Logo](https://mintcdn.com/geno-f35946c5/u95feZdjOS0TUwM0/logo/light.svg?fit=max\&auto=format\&n=u95feZdjOS0TUwM0\&q=85\&s=2538da257ffd4de46bd5e7c5a7a70349) ## What is gu1? gu1 is a comprehensive risk analysis and compliance platform that helps financial institutions automate their due diligence processes, detect fraud, and ensure regulatory compliance. Our platform combines **intelligent data mapping**, **AI-powered analysis**, and **customizable rules engines** to provide real-time risk assessments across multiple use cases. ## 5 Core Use Cases > [card] [Know Your Business (KYB)](/en/use-cases/kyb/overview) > > Automated corporate risk analysis for business onboarding and monitoring > [card] [Know Your Customer (KYC)](/en/use-cases/kyc/overview) > > Identity verification and individual customer screening > [card] [Compliance Screening](/en/use-cases/kyc/warning-risk-codes) > > Sanctions, PEPs, adverse media, and risk codes aligned with your KYC configuration > [card] [Fraud Prevention](/en/use-cases/transaction-monitoring/fraud-detection) > > Transaction fraud patterns, velocity checks, and investigations > [card] [Transaction Monitoring](/en/use-cases/transaction-monitoring/overview) > > Rules engine, AML-style monitoring, alerts, and transaction workflows ## Key Features > [accordion] Smart Data Mapping > > Define custom schemas and automatically map your data sources to gu1's unified model. Support for CSV, APIs, databases, and custom formats. > [accordion] AI-Powered Analysis > > AI-powered entity analysis provides risk insights, behavioral patterns, and recommendations in multiple languages. > [accordion] Customizable Rules Engine > > Create sophisticated risk rules with visual builder or code. Support for templates, categories, and external rule execution via API. > [accordion] Real-time Alerts & Investigations > > Automatic alert consolidation and investigation management with timeline tracking and AI-driven prioritization. > [accordion] Webhooks & Integrations > > Integrate gu1 into your existing workflows with webhooks, API keys, and real-time event notifications. > [accordion] Multi-language Support > > Full platform support for English, Spanish, and Portuguese with automatic language detection. ## How It Works **1. Map Your Data** Define your data schema and map fields to gu1's unified model using our smart detection system. **2. Create Entities** Import companies, individuals, or transactions via API or bulk upload. **3. Apply Rules** Configure risk rules and compliance checks through the dashboard. **4. Monitor & Act** Receive alerts, manage investigations, and take action on risk findings. ## Getting Started > [card] [Quick Start](/en/quickstart) > > Get up and running in 5 minutes with our KYB tutorial > [card] [API Reference](/en/api-reference/authentication) > > Explore our comprehensive API documentation > [card] [KYC Complete Flow](/en/use-cases/kyc/complete-flow) > > End-to-end KYC integration from session creation to decisions > [card] [Use Case Examples](/en/use-cases/kyb/example) > > Real-world examples and best practices ## Support Need help? We're here for you: * **Documentation**: Browse our comprehensive guides and API reference * **Email**: [support@gueno.com](mailto:support@gueno.com) * **Dashboard**: Access your account at [app.gu1.ai](https://app.gu1.ai) *** Ready to get started? [Create your first KYB analysis →](/en/quickstart) # Get entity monitoring status Source: https://docs.gu1.ai/en/monitoring/api-reference/get-entity-monitoring GET /entities/{id}/monitoring Retrieve watchlist-style monitoring state for an entity per integration (e.g. gu1 sanctions screening), including last check and current match status. ``` GET http://api.gu1.ai/entities/{id}/monitoring ``` ## Authentication ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` Requires **read** permission on the entity (`entities:read`). ## Path Parameters **id** `string` *required* Internal gu1 entity UUID. ## Response (summary) **guenoDailyScreeningHitToday** `boolean` Whether there was at least one **detection** from the daily screening **today** (per configured timezone logic). **integrations** `array` Per-integration rows. Today this typically includes Gu1 global sanctions with fields such as: * **code** — e.g. `global_gueno_sanctions_enrichment` * **displayName** * **orgMonitoringEnabled** — Marketplace org toggle for that integration * **watchlistSearchName**, **watchlistUniqueId** — upstream handles when present * **isActive**, **monitoringOptOut**, **hasRow** * **riskMatrixId**, **riskMatrixName** — optional per-subscription matrix for monitoring-triggered rule runs; `null` means use the entity’s global matrix for that flow ## Example ```bash theme={null} curl -sS "http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/monitoring" \ -H "Authorization: Bearer YOUR_API_KEY" ``` # Get entity monitoring history Source: https://docs.gu1.ai/en/monitoring/api-reference/get-entity-monitoring-history GET /entities/{id}/monitoring/history GET /entities/{id}/monitoring/history — subscriptions and screening change timeline — in the gu1 entity monitoring service for ongoing screening. ``` GET http://api.gu1.ai/entities/{id}/monitoring/history ``` ## Authentication ```bash theme={null} Authorization: Bearer YOUR_API_KEY ``` Requires **read** permission on the entity. ## Path Parameters **id** `string` *required* Entity UUID. ## Query **tab** `string` *required* * `subscriptions` — watchlist lifecycle (activated/deactivated). * `changes` — snapshots and periodic screening detections. **limit** `integer` Page size (default 20, max 100). **offset** `integer` Pagination offset. **integrationCode** `string` Optional. Defaults to the Gu1 sanctions enrichment integration code. **currentlyOnWatchlist** `string` Only with `tab=subscriptions`. Use `1`, `true`, or `yes` to include open active ranges. ## Examples ```bash theme={null} curl -sS "http://api.gu1.ai/entities/{id}/monitoring/history?tab=subscriptions&limit=20&offset=0" \ -H "Authorization: Bearer YOUR_API_KEY" curl -sS "http://api.gu1.ai/entities/{id}/monitoring/history?tab=changes&limit=20&offset=0" \ -H "Authorization: Bearer YOUR_API_KEY" ``` # Enable or disable monitoring by entity and integration Source: https://docs.gu1.ai/en/monitoring/api-reference/patch-toggle-status-monitoring PATCH /entities/toggle-status-monitoring PATCH /entities/toggle-status-monitoring — provider-code–extensible — in the gu1 entity monitoring service for ongoing screening, with examples for patch. ``` PATCH http://api.gu1.ai/entities/toggle-status-monitoring ``` **Generic** endpoint to set whether an entity **participates** in continuous monitoring for a given `integrationCode` (server behavior depends on the code; today: **Gu1 global sanctions**). ## Authentication ```bash theme={null} Authorization: Bearer YOUR_API_KEY Content-Type: application/json ``` Requires **edit** permission on the entity referenced by `entityId`. ## JSON body **entityId** `string` *required* Entity UUID (must belong to your organization). **integrationCode** `string` *required* Integration / enrichment code. **Supported today:** `global_gueno_sanctions_enrichment`.\ Other values return **400** `UNSUPPORTED_MONITORING_INTEGRATION`. **active** `boolean` * `true` — **include** in continuous monitoring when org and upstream allow (re-enable). * `false` — **exclude** (same as legacy `monitoringOptOut: true`). At least one of **`active`** or **`riskMatrixId`** must be sent. **riskMatrixId** `string | null` Optional. **Gu1 global sanctions** only. UUID of a risk matrix in your org, or `null` to clear the per-subscription override (daily screening then uses the **entity** risk matrix again, same as before). When a UUID is set, **only that matrix** is used for rules triggered by monitoring (e.g. `trigger_monitoring_completed` after daily screening); the entity’s assigned matrix is **not** merged in for that run. Does not update `entities.riskMatrixId`. ## Error Responses | HTTP | Code (example) | When | | - | - | - | | 404 | `ENTITY_NOT_FOUND` | Entity not in org. | | 400 | `UNSUPPORTED_MONITORING_INTEGRATION` | No handler for `integrationCode`, or `riskMatrixId` on an unsupported code. | | 400 | `INVALID_RISK_MATRIX` | Matrix missing, archived, or not in org. | ## Example — turn off Gu1 monitoring ```bash theme={null} curl -sS -X PATCH "http://api.gu1.ai/entities/toggle-status-monitoring" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "entityId": "550e8400-e29b-41d4-a716-446655440000", "integrationCode": "global_gueno_sanctions_enrichment", "active": false }' ``` ## Deprecated route `PATCH /entities/{id}/gueno-sanctions-monitoring-opt-out` with `{ "monitoringOptOut" }` is **deprecated**; use this endpoint with `active: !monitoringOptOut`. # Entity monitoring Source: https://docs.gu1.ai/en/monitoring/overview Continuous watchlist screening per integration in gu1 (sanctions, PEPs, adverse media), distinct from transaction monitoring and rules. ## Scope This section covers **entity-level monitoring** (watchlist / periodic screening tied to enrichments) under `GET/PATCH /entities/...`. Do not confuse it with **Transaction monitoring** (KYT / payment alerts), documented under **Use cases → Transaction monitoring**. ## Typical Flow (Gu1 Sanctions) 1. **Marketplace**: enable the integration and org **monitoring** for `global_gueno_sanctions_enrichment`. 2. **Onboarding**: when creating the entity, send `monitoring` + `autoExecuteIntegrations` per [Create entity](/en/api-reference/entities/create) or [Create automatic](/en/api-reference/entities/create-automatic). 3. **Operations**: use the **API Reference** pages in this group for status and history. 4. **Enable / disable**: `PATCH /entities/toggle-status-monitoring` with `entityId`, `integrationCode`, and `active`. ## API Reference > [card] [Monitoring status](/en/monitoring/api-reference/get-entity-monitoring) > > `GET /entities/{id}/monitoring` > [card] [History](/en/monitoring/api-reference/get-entity-monitoring-history) > > `GET /entities/{id}/monitoring/history` > [card] [Monitoring status by integration](/en/monitoring/api-reference/patch-toggle-status-monitoring) > > `PATCH /entities/toggle-status-monitoring` ## Extended Client Guide (Repository) The end-to-end client guide with JSON examples lives in the repo: `docs/es/guias/monitoreo-sanciones-gueno-cliente.md` (Spanish; mirror to EN/PT in-repo if needed). # Quickstart: KYB Risk Analysis in 5 Minutes Source: https://docs.gu1.ai/en/quickstart Get started with gu1 in five minutes: authenticate, send company data to the KYB endpoint, and retrieve an automated risk score and decision. ## Overview This quickstart guide will walk you through creating your first **Know Your Business (KYB)** risk analysis using gu1's API. You'll learn how to: 1. Authenticate with the API 2. Define a custom schema for your company data 3. Create a company entity 4. Apply risk rules (via dashboard) 5. Monitor alerts and investigations > [!NOTE] > > **Prerequisites**: You'll need a gu1 account and an API key. Sign up at [app.gu1.ai](https://app.gu1.ai) if you haven't already. ## Step 1: Get Your API Key First, obtain your API key from the gu1 dashboard: **1. Log in to Dashboard** Go to [app.gu1.ai](https://app.gu1.ai) and log in to your account **2. Navigate to API Keys** Click **Settings** → **API Keys** in the sidebar **3. Create New Key** Click **Create API Key**, give it a name (e.g., "KYB Integration"), and copy the key > [!WARNING] > > Keep your API key secure! Never commit it to version control or share it publicly. ## Step 2: Define Your Company Schema Tell gu1 what data fields you'll be sending for companies: ```bash theme={null} curl -X POST http://api.gu1.ai/custom-schemas \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Corporate KYB Data", "version": "1.0.0", "description": "Company information for KYB analysis", "type": "database", "category": "financial", "schemaData": { "fields": [ { "name": "company_name", "type": "string", "required": true, "description": "Legal company name" }, { "name": "tax_id", "type": "string", "required": true, "description": "Tax identification number" }, { "name": "country", "type": "string", "required": true, "description": "Country of incorporation" }, { "name": "industry", "type": "string", "required": false, "description": "Industry sector" }, { "name": "annual_revenue", "type": "number", "required": false, "description": "Annual revenue in USD" } ] } }' ``` > [accordion] Response > > ```json theme={null} > { > "success": true, > "schema": { > "id": "550e8400-e29b-41d4-a716-446655440000", > "name": "Corporate KYB Data", > "version": "1.0.0", > "organizationId": "your-org-id", > "createdAt": "2025-10-03T12:00:00Z" > } > } > ``` ## Step 3: Map Fields to gu1's Model Create a mapping configuration to tell gu1 how your fields map to its unified entity model: ```bash theme={null} curl -X POST http://api.gu1.ai/custom-schemas/mappings \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "KYB Field Mapping", "sourceSchemaId": "550e8400-e29b-41d4-a716-446655440000", "targetSchemaType": "gueno_entity", "mappingData": { "mappings": [ { "id": "1", "sourceField": "company_name", "targetField": "name", "transformation": { "type": "direct" }, "required": true, "dataType": "string" }, { "id": "2", "sourceField": "tax_id", "targetField": "external_id", "transformation": { "type": "direct" }, "required": true, "dataType": "string" }, { "id": "3", "sourceField": "country", "targetField": "country", "transformation": { "type": "direct" }, "required": true, "dataType": "string" } ] } }' ``` ## Step 4: Create a Company Entity Now you can create a company entity using the mapped schema: ```bash theme={null} curl -X POST http://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "company", "name": "Acme Corporation", "externalId": "TAX123456789", "country": "US", "entityData": { "industry": "Technology", "annual_revenue": 5000000, "incorporation_date": "2010-01-15", "employees": 50 } }' ``` > [accordion] Response > > ```json theme={null} > { > "success": true, > "entity": { > "id": "a7c4c07f-a1f5-49d6-8c17-1577d0787a2e", > "type": "company", > "name": "Acme Corporation", > "externalId": "TAX123456789", > "country": "US", > "riskScore": 0, > "status": "active", > "createdAt": "2025-10-03T12:05:00Z" > } > } > ``` ## Step 5: View AI Analysis gu1 automatically generates an AI-powered risk analysis for the entity. Fetch it: ```bash theme={null} curl -X POST http://api.gu1.ai/ai-analysis/entity/a7c4c07f-a1f5-49d6-8c17-1577d0787a2e \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "language": "en" }' ``` > [accordion] Response > > ```json theme={null} > { > "success": true, > "analysis": { > "executive_summary": "Acme Corporation is a US-based technology company with moderate risk profile. The company shows stable operations with consistent revenue...", > "behavioral_analysis": "Entity demonstrates normal business patterns with no red flags in transaction history...", > "risk_factors": [ > "Limited public information available", > "Operating in high-risk technology sector" > ], > "recommendations": [ > "Request additional documentation for beneficial owners", > "Monitor for any changes in company structure" > ], > "confidence_score": 0.85, > "generated_at": "2025-10-03T12:05:30Z" > }, > "cached": false > } > ``` ## Step 6: Apply Rules (Dashboard) > [!NOTE] > > You configure rules through the gu1 dashboard for security and ease of use. 1. Go to your [gu1 Dashboard](https://app.gu1.ai) 2. Navigate to **Risk Analysis** → **Entities** 3. Find "Acme Corporation" and click to view details 4. Go to the **Rules** tab and click **Apply Rules** 5. Select pre-built KYB rules or create custom ones Rules will automatically generate alerts and investigations based on risk thresholds. ## Step 7: Monitor with Webhooks Set up webhooks to receive real-time notifications when alerts or investigations are created: ```bash theme={null} curl -X POST http://api.gu1.ai/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/webhooks/gueno", "events": [ "investigation.created", "investigation.updated", "alert.created", "entity.risk_score_changed" ], "active": true }' ``` ## Next Steps > [card] [Complete KYB Guide](/en/use-cases/kyb/workflow) > > Learn the full KYB workflow with advanced features > [card] [Custom Schemas](/en/api-reference/data-ingestion/custom-schemas) > > Map incoming fields to gu1’s unified model for entities and rules > [card] [API Reference](/en/api-reference/entities/create) > > Explore all available API endpoints > [card] [Webhooks](/en/webhooks/overview) > > Event types, security model, and configuration in the dashboard ## Need Help? * **Documentation**: Browse our [API Reference](/en/api-reference/authentication) * **Support**: Email us at [support@gueno.com](mailto:support@gueno.com) * **Dashboard**: [app.gu1.ai](https://app.gu1.ai) # Quickstart — React Native SDK Source: https://docs.gu1.ai/en/sdk/quickstart Integrate the Gu1 React Native SDK into your mobile app in minutes: device intelligence, session signals, and real-time fraud prevention. ## What the SDK Does (and Doesn't Do) The Gu1 SDK runs inside your app and captures what your backend cannot see: device signals, environment integrity, and the screen journey — including everything **before login**. The events you already send from your backend **stay exactly as they are**: they just carry an extra `sessionId` so the Gu1 engine can join both worlds. The SDK is **fail-open by design**: it never blocks your app, never propagates errors (the only exception is invalid configuration at init), requires no permissions, and does not access user data. | | | | - | - | | Size | \~150 KB | | Required permissions | None | | Requirements | React Native 0.71+, iOS 13+, Android 6+ (API 23) | | Distribution | Private npm (scope `@gu1` — request read access from Gu1) | ## 1. Install > [!NOTE] > > The SDK ships via **private npm** (scope `@gu1`, `restricted` package). The command below returns `404` if your environment lacks read access to the `@gu1` scope: **contact your Gu1 team for private package access** before installing. ```bash theme={null} npm install @gu1/sdk-react-native@latest react-native-keychain react-native-get-random-values cd ios && pod install ``` No changes to `AndroidManifest.xml` or `Info.plist` are required. The SDK is **backward-compatible**: it works on both the New Architecture and the classic React Native architecture (RN 0.71+), with no extra configuration. ## 2. Initialize (at Your App's Entry Point) ```typescript theme={null} import 'react-native-get-random-values' import { createGu1SDK } from '@gu1/sdk-react-native' const gu1 = await createGu1SDK({ apiKey: 'gk_xxx', // provided by Gu1 (sandbox and production) apiUrl: 'https://api..gu1.ai' // your instance URL, provided by Gu1 }) ``` From this moment the SDK generates an anonymous `sessionId`, collects device signals, and ships them in the background. Nothing else is required in the app for signal capture. ## 3. Screen Tracking (Recommended — 5 Lines) With React Navigation, the SDK captures navigation and screen timings automatically: ```typescript theme={null} import { createScreenTracker } from '@gu1/sdk-react-native' const screenTracker = createScreenTracker(gu1) ``` No per-screen manual instrumentation: this is all of it. ## 4. The sessionId Towards Your Backend (1 Header) To link your backend events to the device session, attach the `sessionId` as a header on the app's calls to your own backend: ```typescript theme={null} // In your HTTP client (axios/fetch interceptor): headers['X-Gu1-Session-Id'] = gu1.getSessionId() ``` Then on your backend: * **First authenticated request:** send Gu1 an event with the `sessionId` + the user's `entityExternalId`. Gu1 retroactively binds the whole session, including everything before login. * **Existing events:** add the optional camelCase `sessionId` field to the events you already send to `POST /events/user` — events without it keep working unchanged. ```json theme={null} POST /events/user { "eventType": "LOGIN_SUCCESS", "entityExternalId": "user_123", "sessionId": "sess_abc123", "metadata": { } } ``` ## 5. Transactions (1 Line) On the transactions you send to Gu1, the `sessionId` travels in metadata: ```json theme={null} POST /transactions { "amount": 50000, "metadata": { "sessionId": "sess_abc123" } } ``` With this in place, the rules engine evaluates every transaction with full session context: device, integrity, journey, and events. ## 6. Verify 1. Launch the app in sandbox → the session appears in your Gu1 dashboard with device signals. 2. Navigate between screens → automatic `NAVIGATION` events. 3. Log in → the session gets bound to the user (retroactive binding). 4. Run a test transfer → the transaction shows session context in its evaluation. ## Integration Summary | Step | Where | Effort | | - | - | - | | Install + init | App | \~15 min | | Screen tracking | App | 5 lines | | `X-Gu1-Session-Id` header | App (HTTP client) | 1 line | | `sessionId` on events + binding | Backend (middleware) | \~1 hour | | `sessionId` on transactions | Backend | 1 line | Any new signals Gu1 enables in the future are switched on through remote configuration — no app releases, no coordination required. # Quickstart — Web SDK Source: https://docs.gu1.ai/en/sdk/quickstart-web Integrate the Gu1 browser SDK into your web app in minutes for device intelligence, session signals, and real-time fraud prevention on any site. ## What the SDK Does (and Doesn't Do) `@gu1/sdk-web` is the browser channel of the Gu1 SDK: it runs inside your web app and captures what your backend cannot see — device signals (canvas, WebGL, `navigator` properties), environment integrity, and the user journey, including everything **before login**. It shares the event model with the React Native SDK: the events you already send from your backend **stay exactly as they are**, they just carry an extra `sessionId` so the Gu1 engine can join both worlds. The SDK is **fail-open by design**: it never blocks the page, never propagates errors (the only exception is invalid configuration at init), and does not access user data. | | | | - | - | | Environments | Modern browsers | | Builds | ESM, CommonJS, and IIFE (`window.Gu1Sdk` for ` ``` > [!NOTE] > > **Content Security Policy:** if the page enforces a CSP, allow `connect-src https://api..gu1.ai` (the SDK sends events and reads `/sdk/config`) and — only for the ` ``` From this moment the SDK generates an anonymous `sessionId`, collects device signals (canvas, WebGL, `navigator`) and environment integrity, and ships them in the background. Nothing else is required on the page for signal capture. ## 3. The sessionId Towards Your Backend (1 Header) To link your backend events to the device session, attach the `sessionId` as a header on the web app's calls to your own backend: ```typescript theme={null} // In your HTTP client (axios/fetch interceptor): headers['X-Gu1-Session-Id'] = gu1.getSessionId() ``` Then on your backend: * **First authenticated request:** send Gu1 an event with the `sessionId` + the user's `entityExternalId`. Gu1 retroactively binds the whole session, including everything before login. * **Existing events:** add the optional camelCase `sessionId` field to the events you already send to `POST /events/user` — events without it keep working unchanged. ```json theme={null} POST /events/user { "eventType": "LOGIN_SUCCESS", "entityExternalId": "user_123", "sessionId": "sess_abc123", "metadata": { } } ``` ## 4. Transactions (1 Line) On the transactions you send to Gu1, the `sessionId` travels in metadata: ```json theme={null} POST /transactions { "amount": 50000, "metadata": { "sessionId": "sess_abc123" } } ``` With this in place, the rules engine evaluates every transaction with full session context: device, integrity, journey, and events. ## 5. Verify 1. Load the page in sandbox → the session appears in your Gu1 dashboard with device signals. 2. Log in → the session gets bound to the user (retroactive binding). 3. Run a test transaction → the transaction shows session context in its evaluation. ## Integration Summary | Step | Where | Effort | | - | - | - | | Install + init | Web app | \~15 min | | `X-Gu1-Session-Id` header | Web app (HTTP client) | 1 line | | `sessionId` on events + binding | Backend (middleware) | \~1 hour | | `sessionId` on transactions | Backend | 1 line | Any new signals Gu1 enables in the future are switched on through remote configuration — no web app redeploys, no coordination required. # Complete Company (KYB) Flow Source: https://docs.gu1.ai/en/use-cases/kyb/complete-flow End-to-end guide for creating, enriching, and analyzing company entities with shareholder discovery — in the gu1 KYB workflow for business verification. ## Overview This guide covers the complete flow for company entity management (Know Your Business), from creation through enrichment, shareholder discovery, and risk analysis. The flow supports automatic shareholder creation and recursive enrichment of the entire ownership structure. ## Flow Diagram ```mermaid theme={null} graph TD A[Create Company] --> B{Automatic Creation?} B -->|Yes| C[POST /entities/automatic] B -->|No| D[POST /entities] C --> E[Basic Enrichment] E --> F[Company Created with Data] F --> G[Additional Enrichments] D --> H[Company Created - Basic Info Only] G --> I{Create Shareholders?} H --> J{Need Enrichment?} I -->|Yes| K[Shareholder Discovery] I -->|No| L[Risk Matrix Assignment] J -->|Yes| M[POST /entities/:id/analyze with enrichment] J -->|No| N{Risk Matrix Assigned?} K --> O[For Each Shareholder] O --> P{Shareholder Type} P -->|Person| Q[Create Person Entity] P -->|Company| R[Create Company Entity - Recursive] Q --> S[Enrich Person] R --> T[Enrich Company] T --> U{Max Depth Reached?} U -->|No| K U -->|Yes| L S --> L M --> N N -->|Yes| V[Auto Risk Analysis] N -->|No| W[Manual Risk Analysis] V --> X[Risk Score Calculated] W --> Y[POST /entities/:id/analyze] Y --> X X --> Z[Complete] ``` ## Step 1: Create Company Entity ### Option A: Automatic Creation (Recommended) Automatic creation handles enrichment, shareholder discovery, and risk analysis in a single operation, including recursive shareholder creation. **Endpoint**: `POST /entities/automatic` **Request**: ```json theme={null} { "entityType": "company", "data": { "taxId": "87654321", "name": "Acme Corporation", "countryCode": "US" }, "enrichmentOptions": { "basic": ["company_registry", "sanctions", "adverse_media"], "additional": ["financial_records", "legal_filings", "esg_ratings"], "createShareholders": true, "maxShareholderDepth": 3 }, "skipRulesExecution": false, "riskMatrixId": "uuid-of-risk-matrix" } ``` **What happens automatically**: 1. **Basic Data Enrichment**: Executes providers from `basic` list (company registry, sanctions, etc.) 2. **Company Creation**: Maps normalized data to company entity structure 3. **Additional Enrichment**: Executes providers from `additional` list 4. **Shareholder Discovery**: Extracts shareholders from enrichment data 5. **Recursive Shareholder Creation**: * Creates person entity for individual shareholders * Creates company entity for corporate shareholders * Enriches each shareholder * Continues recursively up to `maxShareholderDepth` 6. **Risk Matrix Assignment**: Assigns the provided risk matrix (or default) 7. **Risk Analysis**: Executes risk matrix rules automatically (unless `skipRulesExecution: true`) **Response**: ```json theme={null} { "entity": { "id": "company-uuid", "organizationId": "uuid", "type": "company", "name": "Acme Corporation", "taxId": "87654321", "countryCode": "US", "riskScore": "62.00", "riskFactors": { "reasons": [ "Adverse media found", "Shareholder in high-risk jurisdiction" ], "normalizedScore": 55, "originalScore": 62, "customLabel": { "name": "High Risk", "color": "#ef4444" } }, "metadata": { "enrichment": { "hasData": true, "executedProviders": [ "company_registry_us", "sanctions_api", "adverse_media", "financial_records" ], "lastExecutedAt": "2025-12-24T10:30:00Z" } } }, "enrichmentResult": { "success": true, "providers": [ "company_registry_us", "sanctions_api", "adverse_media", "financial_records" ], "dataQuality": 88, "confidence": 92 }, "rulesResult": { "success": true, "executed": true, "rulesTriggered": 5, "riskScore": 62 }, "shareholders": [ { "id": "person-shareholder-uuid", "type": "person", "name": "Jane Smith", "ownershipPercentage": 35, "riskScore": "25.00", "enriched": true }, { "id": "company-shareholder-uuid", "type": "company", "name": "Investment Holdings LLC", "ownershipPercentage": 40, "riskScore": "48.00", "enriched": true, "shareholders": [ { "id": "nested-person-uuid", "type": "person", "name": "John Doe", "ownershipPercentage": 100, "riskScore": "15.00" } ] }, { "id": "person-shareholder-2-uuid", "type": "person", "name": "Bob Johnson", "ownershipPercentage": 25, "riskScore": "18.00" } ] } ``` ### Option B: Manual Creation Create a company entity with basic information only, then enrich and analyze separately. **Endpoint**: `POST /entities` **Request**: ```json theme={null} { "type": "company", "name": "Acme Corporation", "taxId": "87654321", "countryCode": "US", "entityData": { "company": { "legalName": "Acme Corporation Inc.", "registrationNumber": "REG123456", "incorporationDate": "2010-05-15", "industry": "Technology", "website": "https://acme-corp.example" } } } ``` **Response**: ```json theme={null} { "entity": { "id": "company-uuid", "organizationId": "uuid", "type": "company", "name": "Acme Corporation", "taxId": "87654321", "countryCode": "US", "status": "active", "riskScore": null, "metadata": { "enrichment": { "hasData": false } } } } ``` ## Step 2: Enrich and Analyze (Manual Flow) If you created the entity manually, you need to enrich it and execute risk analysis. **Endpoint**: `POST /entities/:entityId/analyze` **Request**: ```json theme={null} { "enrichIfNeeded": true, "providerCodes": [ "company_registry_us", "sanctions_api", "adverse_media", "financial_records", "beneficial_ownership" ], "entityType": "company" } ``` **What happens**: 1. **Enrichment**: Runs specified providers to gather company data 2. **Shareholder Discovery**: Identifies shareholders from provider data (but doesn't auto-create) 3. **Risk Analysis**: Executes risk matrix rules on the company 4. **Score Update**: Updates company risk score and status **Response**: ```json theme={null} { "success": true, "executed": true, "result": { "entityId": "company-uuid", "entityType": "company", "riskScore": 62, "overallConfidence": 0.92, "totalRules": 15, "successfulRules": 5, "flags": [ { "type": "ADVERSE_MEDIA", "severity": "warning", "reason": "Company mentioned in 3 adverse media articles", "confidence": 0.88 }, { "type": "HIGH_RISK_JURISDICTION", "severity": "critical", "reason": "Shareholder based in high-risk jurisdiction", "confidence": 0.95 } ], "strategyEvaluation": { "normalizedScore": 55, "originalScore": 62, "customLabel": { "name": "High Risk", "minScore": 50, "maxScore": 75, "color": "#ef4444" } } }, "rulesTriggered": 5, "executionTimeMs": 2100 } ``` ## Step 3: Shareholder Discovery and Creation ### Automatic Shareholder Creation (via /entities/automatic) When using automatic creation with `createShareholders: true`, the system: 1. **Extracts Shareholders**: From enrichment provider data (e.g., company registry, beneficial ownership databases) 2. **Creates Entities**: For each shareholder (person or company) 3. **Enriches Shareholders**: Runs enrichment on each shareholder entity 4. **Recursive Processing**: For company shareholders, repeats the process up to `maxShareholderDepth` 5. **Links Relationships**: Creates ownership relationships in the entity graph **Example Shareholder Data Structure**: ```json theme={null} { "shareholders": [ { "name": "Jane Smith", "type": "person", "ownershipPercentage": 35, "position": "CEO", "taxId": "11111111" }, { "name": "Investment Holdings LLC", "type": "company", "ownershipPercentage": 40, "taxId": "22222222", "countryCode": "US" } ] } ``` ### Manual Shareholder Creation If you need to create shareholders manually: **Step 1**: Create the shareholder entity using `POST /entities` or `POST /entities/automatic` **Step 2**: Link the shareholder to the parent company: ```json theme={null} POST /entity-relationships { "fromEntityId": "shareholder-uuid", "toEntityId": "company-uuid", "relationshipType": "SHAREHOLDER_OF", "metadata": { "ownershipPercentage": 35, "position": "Board Member", "since": "2020-01-01" } } ``` ## Step 4: Enrichment Process (Company-Specific) ### Company Enrichment Providers Common providers for company enrichment: * **company\_registry\_us**: Company registration data, officers, shareholders * **company\_registry\_uk**: UK Companies House data * **company\_registry\_eu**: European company registries * **sanctions\_api**: Sanctions screening for companies * **adverse\_media**: News and media mentions * **financial\_records**: Financial statements, credit ratings * **beneficial\_ownership**: Ultimate beneficial ownership (UBO) data * **legal\_filings**: Court cases, legal proceedings * **esg\_ratings**: Environmental, social, governance ratings ### Enrichment Result (Company) ```json theme={null} { "success": true, "entityId": "company-uuid", "normalized": { "entityType": "company", "normalized": { "legalName": "Acme Corporation Inc.", "tradingNames": ["Acme", "Acme Corp"], "registrationNumber": "REG123456", "incorporationDate": "2010-05-15", "status": "active", "industry": "Technology", "employees": 150, "revenue": 25000000, "directors": [ { "name": "Jane Smith", "position": "CEO", "appointedDate": "2015-03-10" } ], "shareholders": [ { "name": "Jane Smith", "ownershipPercentage": 35, "type": "person" }, { "name": "Investment Holdings LLC", "ownershipPercentage": 40, "type": "company", "countryCode": "US" } ], "sanctionsMatch": false, "adverseMedia": [ { "title": "Company Settles Dispute", "date": "2023-08-20", "source": "Business Journal", "sentiment": "negative" } ], "creditRating": "BBB", "esgScore": 72 }, "providers": [ "company_registry_us", "sanctions_api", "adverse_media", "financial_records", "esg_ratings" ], "dataQuality": 88, "confidence": 92, "completeness": 85 }, "providers": [ "company_registry_us", "sanctions_api", "adverse_media", "financial_records", "esg_ratings" ], "totalCostCents": 250, "executionTimeMs": 5200, "cacheHit": false } ``` ## Step 5: Risk Analysis (Company-Specific) ### Company Risk Rules Examples Common risk rules for companies: 1. **Sanctions Screening**: Check if company or shareholders on sanctions lists 2. **High-Risk Jurisdiction**: Check if incorporated or operating in high-risk countries 3. **Adverse Media**: Count negative news articles 4. **Financial Health**: Evaluate credit rating and financial ratios 5. **ESG Risk**: Check ESG scores and controversies 6. **Ownership Structure**: Analyze shareholder risk (complex structures, offshore entities) 7. **Legal Proceedings**: Count active lawsuits and regulatory actions 8. **PEP Connections**: Check if directors/shareholders are PEPs ### Risk Analysis with Shareholder Risk The risk analysis considers: * **Company Direct Risk**: Based on company's own data * **Shareholder Risk**: Aggregated risk from all shareholders * **Ownership Complexity**: Risk from complex or opaque ownership structures **Example Result**: ```json theme={null} { "success": true, "executed": true, "result": { "entityId": "company-uuid", "entityType": "company", "riskScore": 62, "overallConfidence": 0.92, "rulesExecuted": [ { "ruleId": "rule-uuid-1", "ruleName": "Adverse Media Detection", "conditionsMet": true, "actionsExecuted": [ { "type": "add_risk_score", "value": 20 } ] }, { "ruleId": "rule-uuid-2", "ruleName": "Shareholder High-Risk Jurisdiction", "conditionsMet": true, "actionsExecuted": [ { "type": "add_risk_score", "value": 30 }, { "type": "create_alert", "result": { "alertId": "alert-uuid" } } ] }, { "ruleId": "rule-uuid-3", "ruleName": "Financial Health Check", "conditionsMet": true, "actionsExecuted": [ { "type": "add_risk_score", "value": 12 } ] } ], "flags": [ { "type": "ADVERSE_MEDIA", "severity": "warning", "reason": "3 adverse media articles found", "confidence": 0.88 }, { "type": "HIGH_RISK_JURISDICTION", "severity": "critical", "reason": "Shareholder 'Investment Holdings LLC' in high-risk jurisdiction", "confidence": 0.95 } ] }, "rulesTriggered": 5, "executionTimeMs": 2100 } ``` ## Step 6: Shareholder Risk Aggregation ### How Shareholder Risk Affects Company Risk Companies can configure rules that evaluate shareholder risk: **Example Rule**: "High-Risk Shareholder Alert" ```json theme={null} { "name": "High-Risk Shareholder Alert", "conditions": { "operator": "AND", "conditions": [ { "field": "shareholders.riskScore", "operator": "greater_than", "value": 70 }, { "field": "shareholders.ownershipPercentage", "operator": "greater_than", "value": 10 } ] }, "actions": [ { "type": "add_risk_score", "value": 40 }, { "type": "create_alert", "severity": "critical", "description": "Company has high-risk shareholder with significant ownership" } ] } ``` ### Querying Company with Shareholders Read owners already stored on the company. This does not run enrichment again. **Endpoint**: `GET /entities/{companyId}/shareholders` Same body by tax id: `GET /entities/by-tax-id/{taxId}/shareholders`. See [Get materialized shareholders](/en/api-reference/entities/shareholders). **Response**: ```json theme={null} { "success": true, "data": { "entityId": "company-uuid", "shareholders": [ { "id": "shareholder-1-uuid", "name": "Jane Smith", "taxId": "12345678900", "type": "person", "shareholderInfo": { "percentage": 35, "roles": ["CEO"], "isActive": true } } ], "relationships": [] } } ``` ## Step 7: Update by External ID For companies created via external systems, you can update using external ID: **Endpoint**: `PATCH /entities/by-external-id/:externalId` **Request**: ```json theme={null} { "entityData": { "company": { "revenue": 30000000, "employees": 200, "status": "active" } }, "metadata": { "lastUpdated": "2025-12-24T10:00:00Z", "source": "CRM" } } ``` **Use Cases**: * Sync company data from CRM * Update financial data from accounting system * Update status from business registry ## Best Practices 1. **Use Automatic Creation with Shareholders**: Enable `createShareholders: true` to build complete ownership structure automatically. 2. **Set Appropriate Depth**: Use `maxShareholderDepth: 3` to prevent excessive recursion while capturing important ownership layers. 3. **Provider Selection**: For companies, prioritize: * Company registry (must-have) * Beneficial ownership databases (for UBO discovery) * Sanctions screening * Adverse media * Financial data providers 4. **Risk Matrix Configuration**: Configure company-specific rules that evaluate: * Direct company risk factors * Shareholder risk (individual and aggregate) * Ownership complexity * Jurisdictional risk 5. **Shareholder Monitoring**: Set up rules to monitor shareholder changes and trigger re-analysis. 6. **Cost Management**: Shareholder creation with enrichment can be expensive. Monitor provider costs and set `maxCostCents` limits. 7. **Periodic Re-enrichment**: Company data changes over time. Schedule periodic re-enrichment for active companies. 8. **External ID Mapping**: Always set `externalId` when creating companies from external systems for easy updates. ## Error Handling ### Shareholder Creation Failures If shareholder creation fails during automatic creation: * Main company entity is still created * Partial shareholder data may be stored * Error details in response **Example**: ```json theme={null} { "entity": {...}, "shareholders": [ { "name": "Jane Smith", "status": "created", "id": "uuid" }, { "name": "Investment Holdings LLC", "status": "failed", "error": "Insufficient data to create entity" } ], "warnings": [ "Failed to create 1 of 2 shareholders" ] } ``` ### Incomplete Ownership Data If enrichment providers don't return shareholder data: ```json theme={null} { "enrichmentResult": { "success": true, "shareholders": [], "warnings": [ "No shareholder data found from providers" ] } } ``` **Solution**: * Manually add shareholders using `POST /entities` + `POST /entity-relationships` * Try additional beneficial ownership providers ### Recursive Depth Limit If ownership structure exceeds `maxShareholderDepth`: ```json theme={null} { "shareholders": [...], "warnings": [ "Maximum shareholder depth reached (3 levels). Deeper shareholders not created." ] } ``` ## Next Steps * [Configure Risk Matrix for Companies](/en/api-reference/risk-matrix/list) * [Shareholder Monitoring Rules](/en/use-cases/kyb/overview) * [Beneficial Ownership Analysis](/en/use-cases/kyb/workflow) * [Company Registry Integrations](/en/api-reference/integrations/provider-codes) # KYB Data Requirements Source: https://docs.gu1.ai/en/use-cases/kyb/data-requirements Required and optional fields for KYB business verification in gu1, including company registration data, tax IDs, beneficial owners, and addresses. ## Overview This guide details all data fields required for comprehensive KYB (Know Your Business) verification using gu1's platform. Data requirements vary by jurisdiction, business type, and risk level. ## Core Business Information ### Required Fields These fields are mandatory for all business entities: | Field | Type | Description | Example | | - | - | - | - | | `legalName` | string | Official registered business name | "Tech Solutions Sociedade Anônima" | | `tradeName` | string | Business trading name | "Tech Solutions" | | `taxId` | string | Tax identification number | "12.345.678/0001-90" (CNPJ - Brazil) | | `countryCode` | string | ISO 3166-1 alpha-2 code | "BR", "US", "MX", "AR" | | `incorporationDate` | date | Date of business formation | "2020-06-15" | | `industry` | string | Primary business activity | "Software Development" | | `registeredAddress` | object | Official business address | See address structure below | ### Address Structure ```json theme={null} { "street": "Av. Paulista, 1000", "city": "São Paulo", "state": "SP", "postalCode": "01310-100", "country": "BR" } ``` ## Business Details ### Strongly Recommended Fields These fields significantly improve risk assessment accuracy: | Field | Type | Description | Example | | - | - | - | - | | `registrationNumber` | string | Government business registration ID | "NIRE 35.300.123456" | | `businessType` | string | Legal structure | "LLC", "Corporation", "Partnership" | | `website` | string | Official company website | "[https://techsolutions.com.br](https://techsolutions.com.br)" | | `employeeCount` | number | Number of employees | 50 | | `annualRevenue` | number | Annual revenue in USD | 5000000 | | `foundingYear` | number | Year company was founded | 2020 | | `businessDescription` | string | What the company does | "B2B SaaS for enterprises" | ### Optional Fields Helpful for enhanced due diligence: | Field | Type | Description | | - | - | - | | `phoneNumber` | string | Primary business phone | | `email` | string | Official contact email | | `parentCompany` | string | Name of parent company (if applicable) | | `subsidiaries` | array | List of subsidiary companies | | `stockSymbol` | string | Ticker symbol (if publicly traded) | | `regulatoryLicenses` | array | Required licenses and permits | ## Beneficial Ownership Data Required for companies with complex ownership structures: ### Ultimate Beneficial Owners (UBOs) For each individual owning >25% of the company: ```json theme={null} { "beneficialOwners": [ { "firstName": "Carlos", "lastName": "Silva", "dateOfBirth": "1975-08-22", "nationality": "BR", "ownershipPercentage": 60, "isPEP": false, "idNumber": "123.456.789-00", "address": { "street": "Rua das Flores, 500", "city": "São Paulo", "state": "SP", "postalCode": "01234-567", "country": "BR" } } ] } ``` ### Corporate Structure For complex ownership: ```json theme={null} { "ownershipStructure": { "type": "multi_tier", "layers": [ { "level": 1, "owners": [ { "type": "person", "name": "Carlos Silva", "ownership": 60 }, { "type": "company", "name": "Investment Holdings Inc", "ownership": 40 } ] } ] } } ``` ## Required Documents ### Tier 1: Essential Documents Required for all businesses: 1. **Articles of Incorporation / Certificate of Formation** * File type: PDF * Max size: 10MB * Must be: Government-issued, recent (within 6 months) 2. **Business License / Operating Permit** * File type: PDF, JPG, PNG * Max size: 10MB * Must show: License number, expiry date, issuing authority 3. **Tax Registration Certificate** * File type: PDF * Max size: 10MB * Must show: Tax ID, registration date, current status 4. **Proof of Business Address** * File type: PDF, JPG * Max size: 5MB * Acceptable: Utility bill, bank statement (last 3 months) ### Tier 2: Enhanced Due Diligence Required for medium/high-risk businesses: 5. **Financial Statements** * File type: PDF * Period: Last 2 years * Must be: Audited or certified by accountant 6. **Beneficial Ownership Declaration** * File type: PDF * Max size: 10MB * Must include: Names, ownership %, IDs of all UBOs 7. **Board Resolution / Authorization** * File type: PDF * Max size: 5MB * Purpose: Authorizing business relationship 8. **Source of Funds Documentation** * File type: PDF * Max size: 10MB * Examples: Investment agreements, bank statements ### Tier 3: High-Risk Additional Requirements Required for high-risk industries or jurisdictions: 9. **Regulatory Approvals** * Specific to industry (financial services, healthcare, etc.) * Must be current and valid 10. **AML Policy Documentation** * Internal AML/CFT procedures * Compliance officer information 11. **Sanctions Compliance Certificate** * Declaration of no sanctions violations * Last 5 years compliance history ## Country-Specific Requirements ### United States ```json theme={null} { "countryCode": "US", "requiredFields": { "ein": "12-3456789", "stateOfIncorporation": "Delaware", "businessStructure": "LLC", "duns": "012345678" }, "documents": [ "articles_of_incorporation", "ein_letter", "state_business_license", "w9_form" ] } ``` ### Brazil ```json theme={null} { "countryCode": "BR", "requiredFields": { "cnpj": "12.345.678/0001-90", "nire": "35.300.123456", "capitalSocial": 1000000, "municipalRegistration": "123456-7" }, "documents": [ "contrato_social", "cartao_cnpj", "certidao_federal", "certidao_estadual", "alvara_funcionamento" ] } ``` ### Mexico ```json theme={null} { "countryCode": "MX", "requiredFields": { "rfc": "ABC123456ABC", "curp": "SABC750822HDFNLR09", "folioMercantil": "123456" }, "documents": [ "acta_constitutiva", "cedula_rfc", "comprobante_domicilio" ] } ``` ### Argentina ```json theme={null} { "countryCode": "AR", "requiredFields": { "cuit": "20-12345678-9", "inscripcionIgj": "123456", "iibb": "901-234567-8" }, "documents": [ "estatuto_social", "constancia_cuit", "certificado_vigencia" ] } ``` ## Transaction & Activity Data ### Expected Transaction Patterns ```json theme={null} { "transactionProfile": { "expectedMonthlyVolume": 250000, "expectedMonthlyTransactions": 150, "averageTransactionSize": 1667, "primaryCurrencies": ["USD", "BRL"], "geographicFocus": ["BR", "AR", "MX"], "businessModel": "subscription_saas" } } ``` ### Business Relationships ```json theme={null} { "businessRelationships": { "majorCustomers": [ { "name": "Enterprise Corp", "country": "BR", "monthlyVolume": 50000 } ], "majorSuppliers": [ { "name": "Cloud Provider Inc", "country": "US", "monthlyVolume": 30000 } ], "bankingPartners": [ { "bankName": "Banco do Brasil", "accountType": "business_checking", "since": "2020-07-01" } ] } } ``` ## Risk-Based Requirements ### Low Risk (Score \< 30) * Basic business information * Tier 1 documents only * Single-layer ownership verification ### Medium Risk (Score 30-70) * Complete business information * Tier 1 + Tier 2 documents * Full beneficial ownership verification * Transaction monitoring setup ### High Risk (Score > 70) * Exhaustive business information * All Tier 1, 2, and 3 documents * Enhanced beneficial ownership verification * Source of wealth documentation * Ongoing enhanced monitoring ## Industry-Specific Requirements ### Financial Services ```json theme={null} { "industry": "financial_services", "additionalRequirements": { "regulatoryLicenses": ["banking_license", "payment_processor_license"], "capitalRequirement": 1000000, "amlPolicyRequired": true, "complianceOfficer": { "name": "João Santos", "email": "compliance@company.com", "certifications": ["CAMS", "CFE"] } } } ``` ### Cryptocurrency / Blockchain ```json theme={null} { "industry": "cryptocurrency", "additionalRequirements": { "virtualAssetLicense": true, "blockchainWallets": ["0x1234..."], "amlProgram": "documented", "travelRuleCompliance": true, "coldStoragePolicy": "documented" } } ``` ### Gaming / Gambling ```json theme={null} { "industry": "gaming", "additionalRequirements": { "gamingLicense": true, "licensingAuthority": "Malta Gaming Authority", "fairnessVerification": "third_party_certified", "responsibleGamingPolicy": true } } ``` ## Data Quality Standards ### Validation Rules All data must meet these quality standards: 1. **Completeness**: No missing required fields 2. **Accuracy**: Data matches official documents 3. **Consistency**: Cross-field validation passes 4. **Currency**: Documents less than 6 months old 5. **Legibility**: Documents clearly readable (min 300 DPI) ### Common Validation Errors | Error | Cause | Solution | | - | - | - | | Invalid Tax ID format | Wrong format for country | Use country-specific validator | | Document too old | Issue date > 6 months ago | Request updated document | | Name mismatch | Legal name ≠ document name | Verify correct legal name | | Missing UBO | No owners listed | Provide ownership structure | | Address unverifiable | Can't confirm address exists | Provide utility bill or statement | ## Data Submission Format ### JSON Structure Complete KYB data submission example: ```json theme={null} { "entity": { "type": "company", "externalId": "business_12345", "name": "Tech Solutions Sociedade Anônima", "taxId": "12.345.678/0001-90", "countryCode": "BR", "entityData": { "company": { "legalName": "Tech Solutions Sociedade Anônima", "tradeName": "Tech Solutions", "incorporationDate": "2020-06-15", "industry": "Software Development", "businessType": "LLC", "employeeCount": 50, "revenue": 5000000, "website": "https://techsolutions.com.br" } }, "attributes": { "registrationNumber": "NIRE 35.300.123456", "registeredAddress": { "street": "Av. Paulista, 1000", "city": "São Paulo", "state": "SP", "postalCode": "01310-100", "country": "BR" }, "expectedMonthlyVolume": 250000, "businessDescription": "B2B SaaS platform for enterprise resource planning" } }, "beneficialOwners": [ { "firstName": "Carlos", "lastName": "Silva", "dateOfBirth": "1975-08-22", "nationality": "BR", "ownershipPercentage": 60, "isPEP": false } ], "documents": [ { "type": "articles_of_incorporation", "fileName": "contrato_social.pdf", "uploadUrl": "https://..." }, { "type": "tax_certificate", "fileName": "cnpj_certificate.pdf", "uploadUrl": "https://..." } ] } ``` ## API Endpoints for Data Submission * **Create Entity**: `POST /entities` * **Upload Documents**: `POST /documents` * **Add UBOs**: `POST /entities/{id}/beneficial-owners` * **Update Business Info**: `PATCH /entities/{id}` ## Next Steps > [card] [Complete Example](/use-cases/kyb/example) > > Full working implementation with all required data > [card] [API Reference](/api-reference/entities/create) > > Detailed API documentation > [card] [KYB Workflow](/use-cases/kyb/workflow) > > Step-by-step verification process > [card] [Document Upload](/en/api-reference/documents/upload) > > How to upload verification documents # KYB Complete Example Source: https://docs.gu1.ai/en/use-cases/kyb/example End-to-end KYB implementation example with gu1: send company data, trigger enrichment and screening, and read the resulting risk score and decision. ## Overview This guide provides a complete, production-ready implementation of KYB (Know Your Business) verification using gu1's API. You can copy and adapt this code for your application. ## Prerequisites * gu1 API key ([get one here](https://app.gu1.ai/org-api-keys)) * Node.js 18+ or Python 3.8+ * Basic understanding of RESTful APIs ## Complete Implementation ### Node.js / TypeScript Full KYB implementation with TypeScript: ```typescript theme={null} import axios from 'axios'; import FormData from 'form-data'; import fs from 'fs'; const GUENO_API_KEY = process.env.GUENO_API_KEY; const GUENO_API_URL = 'http://api.gu1.ai'; // API Client Setup const apiClient = axios.create({ baseURL: GUENO_API_URL, headers: { 'Authorization': `Bearer ${GUENO_API_KEY}`, 'Content-Type': 'application/json' } }); // Types interface BusinessApplication { businessId: string; legalName: string; tradeName: string; taxId: string; countryCode: string; incorporationDate: string; industry: string; website?: string; employeeCount?: number; revenue?: number; address: { street: string; city: string; state: string; postalCode: string; country: string; }; contactEmail: string; contactPhone: string; expectedMonthlyVolume: number; beneficialOwners: BeneficialOwner[]; documents: DocumentUpload[]; } interface BeneficialOwner { firstName: string; lastName: string; dateOfBirth: string; nationality: string; ownershipPercentage: number; isPEP: boolean; idNumber?: string; } interface DocumentUpload { type: string; filePath: string; } interface KYBResult { success: boolean; entityId: string; status: 'approved' | 'pending' | 'rejected' | 'manual_review'; riskScore: number; findings: any; nextSteps: string[]; } // Main KYB Workflow Class class KYBProcessor { /** * Step 1: Create Business Entity */ async createBusinessEntity(application: BusinessApplication): Promise { console.log('📋 Creating business entity...'); const response = await apiClient.post('/entities', { type: 'company', externalId: application.businessId, name: application.legalName, taxId: application.taxId, countryCode: application.countryCode, entityData: { company: { legalName: application.legalName, tradeName: application.tradeName, incorporationDate: application.incorporationDate, industry: application.industry, employeeCount: application.employeeCount, revenue: application.revenue } }, attributes: { website: application.website, registeredAddress: application.address, contactEmail: application.contactEmail, contactPhone: application.contactPhone, expectedMonthlyVolume: application.expectedMonthlyVolume, applicationDate: new Date().toISOString() } }); console.log(`✅ Entity created: ${response.data.entity.id}`); return response.data.entity; } /** * Step 2: Upload Verification Documents */ async uploadDocuments(entityId: string, documents: DocumentUpload[]): Promise { console.log(`📄 Uploading ${documents.length} documents...`); const uploadResults = []; for (const doc of documents) { const formData = new FormData(); formData.append('file', fs.createReadStream(doc.filePath)); formData.append('documentType', doc.type); formData.append('entityId', entityId); const response = await axios.post( `${GUENO_API_URL}/documents`, formData, { headers: { 'Authorization': `Bearer ${GUENO_API_KEY}`, ...formData.getHeaders() } } ); console.log(` ✅ Uploaded: ${doc.type}`); uploadResults.push(response.data); } return uploadResults; } /** * Step 3: Request AI Analysis */ async requestAIAnalysis(entityId: string): Promise { console.log('🤖 Requesting AI analysis...'); const response = await apiClient.post(`/entities/${entityId}/ai-analysis`, { analysisType: 'kyb_verification', includeDocuments: true, checkSanctions: true, checkAdverseMedia: true, checkUBOs: true }); console.log(`✅ Analysis complete. Risk Score: ${response.data.riskScore}`); return response.data; } /** * Step 4: Verify Beneficial Owners */ async verifyBeneficialOwners(entityId: string, owners: BeneficialOwner[]): Promise { console.log(`👥 Verifying ${owners.length} beneficial owners...`); const verifiedOwners = []; for (const owner of owners) { // Create person entity for UBO const uboResponse = await apiClient.post('/entities', { type: 'person', externalId: `ubo_${entityId}_${owner.idNumber}`, name: `${owner.firstName} ${owner.lastName}`, countryCode: owner.nationality, entityData: { person: { firstName: owner.firstName, lastName: owner.lastName, dateOfBirth: owner.dateOfBirth, nationality: owner.nationality } }, attributes: { ownershipPercentage: owner.ownershipPercentage, isPEP: owner.isPEP, relationshipToCompany: 'beneficial_owner' } }); const ubo = uboResponse.data.entity; // Run KYC check on UBO const kycResponse = await apiClient.post(`/entities/${ubo.id}/ai-analysis`, { analysisType: 'kyc_verification', checkPEP: true, checkSanctions: true }); // Create relationship await apiClient.post('/relationships', { fromEntityId: entityId, toEntityId: ubo.id, relationshipType: 'beneficial_owner', metadata: { ownershipPercentage: owner.ownershipPercentage } }); console.log(` ✅ Verified: ${owner.firstName} ${owner.lastName}`); verifiedOwners.push({ ...ubo, kycStatus: kycResponse.data.status, riskScore: kycResponse.data.riskScore }); } return verifiedOwners; } /** * Step 5: Make Decision Based on Risk */ async makeDecision(entityId: string, analysis: any): Promise { console.log('⚖️ Making KYB decision...'); const { riskScore, riskLevel } = analysis; if (riskScore < 30) { // Low Risk - Auto Approve await this.approveEntity(entityId, analysis); return 'approved'; } else if (riskScore < 70) { // Medium Risk - Enhanced Due Diligence await this.requestEnhancedDueDiligence(entityId, analysis); return 'pending'; } else { // High Risk - Manual Review await this.flagForManualReview(entityId, analysis); return 'manual_review'; } } /** * Approve Low-Risk Entity */ private async approveEntity(entityId: string, analysis: any): Promise { console.log('✅ Auto-approving low-risk entity...'); // Update entity status await apiClient.patch(`/entities/${entityId}`, { attributes: { kybStatus: 'approved', approvedAt: new Date().toISOString(), approvedBy: 'automated_system', riskLevel: 'low', reviewNotes: 'Low risk - auto-approved based on AI analysis' } }); // Setup monitoring await this.setupMonitoring(entityId); // Send notification await this.sendStatusNotification(entityId, 'approved'); } /** * Request Enhanced Due Diligence */ private async requestEnhancedDueDiligence(entityId: string, analysis: any): Promise { console.log('🔍 Requesting enhanced due diligence...'); await apiClient.patch(`/entities/${entityId}`, { attributes: { kybStatus: 'enhanced_due_diligence', requestedAt: new Date().toISOString(), riskLevel: 'medium', additionalDocsRequired: [ 'financial_statements', 'ownership_structure', 'source_of_funds' ] } }); await this.sendStatusNotification(entityId, 'additional_info_required'); } /** * Flag for Manual Review */ private async flagForManualReview(entityId: string, analysis: any): Promise { console.log('⚠️ Flagging for manual review...'); // Create review task await apiClient.post('/tasks', { type: 'manual_review', entityId: entityId, priority: 'high', assignTo: 'compliance_team', dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), context: { riskScore: analysis.riskScore, riskFactors: analysis.riskFactors, findings: analysis.findings } }); await apiClient.patch(`/entities/${entityId}`, { attributes: { kybStatus: 'manual_review', flaggedAt: new Date().toISOString(), riskLevel: 'high' } }); await this.sendStatusNotification(entityId, 'under_review'); } /** * Setup Ongoing Monitoring */ private async setupMonitoring(entityId: string): Promise { console.log('📊 Setting up ongoing monitoring...'); await apiClient.post('/rules', { name: `KYB Monitoring - ${entityId}`, entityId: entityId, active: true, rules: [ { type: 'sanctions_screening', frequency: 'daily', action: 'alert_compliance_team' }, { type: 'adverse_media', frequency: 'weekly', action: 'create_review_task' }, { type: 'ownership_changes', frequency: 'realtime', action: 'trigger_reverification' } ] }); } /** * Send Status Notification */ private async sendStatusNotification(entityId: string, status: string): Promise { console.log(`📧 Sending ${status} notification...`); // Your notification logic here (email, webhook, etc.) await apiClient.post('/webhooks/send', { event: 'kyb_status_changed', entityId: entityId, status: status, timestamp: new Date().toISOString() }); } /** * Complete KYB Workflow */ async processKYB(application: BusinessApplication): Promise { try { console.log('🚀 Starting KYB verification process...\n'); // Step 1: Create entity const entity = await this.createBusinessEntity(application); // Step 2: Upload documents await this.uploadDocuments(entity.id, application.documents); // Step 3: AI Analysis const analysis = await this.requestAIAnalysis(entity.id); // Step 4: Verify UBOs const verifiedOwners = await this.verifyBeneficialOwners( entity.id, application.beneficialOwners ); // Step 5: Make decision const status = await this.makeDecision(entity.id, analysis); console.log('\n✨ KYB process completed successfully!'); return { success: true, entityId: entity.id, status: status as any, riskScore: analysis.riskScore, findings: analysis.findings, nextSteps: analysis.nextSteps }; } catch (error: any) { console.error('❌ KYB process failed:', error.message); return { success: false, entityId: '', status: 'rejected', riskScore: 100, findings: { error: error.message }, nextSteps: ['Contact support'] }; } } } // Example Usage async function main() { const kybProcessor = new KYBProcessor(); // Sample business application const application: BusinessApplication = { businessId: 'business_12345', legalName: 'Tech Solutions Sociedade Anônima', tradeName: 'Tech Solutions', taxId: '12.345.678/0001-90', countryCode: 'BR', incorporationDate: '2020-06-15', industry: 'Software Development', website: 'https://techsolutions.com.br', employeeCount: 50, revenue: 5000000, address: { street: 'Av. Paulista, 1000', city: 'São Paulo', state: 'SP', postalCode: '01310-100', country: 'BR' }, contactEmail: 'contact@techsolutions.com.br', contactPhone: '+55 11 1234-5678', expectedMonthlyVolume: 250000, beneficialOwners: [ { firstName: 'Carlos', lastName: 'Silva', dateOfBirth: '1975-08-22', nationality: 'BR', ownershipPercentage: 60, isPEP: false, idNumber: '123.456.789-00' }, { firstName: 'Ana', lastName: 'Costa', dateOfBirth: '1980-03-15', nationality: 'BR', ownershipPercentage: 40, isPEP: false, idNumber: '987.654.321-00' } ], documents: [ { type: 'articles_of_incorporation', filePath: './docs/contrato_social.pdf' }, { type: 'tax_certificate', filePath: './docs/cnpj_certificate.pdf' }, { type: 'business_license', filePath: './docs/alvara.pdf' }, { type: 'proof_of_address', filePath: './docs/comprovante.pdf' } ] }; // Execute KYB workflow const result = await kybProcessor.processKYB(application); console.log('\n📊 Final Result:'); console.log(JSON.stringify(result, null, 2)); } // Run the example main().catch(console.error); ``` ### Python Implementation Complete KYB workflow in Python: ```python theme={null} import requests import os from typing import List, Dict, Optional from datetime import datetime, timedelta GUENO_API_KEY = os.getenv('GUENO_API_KEY') GUENO_API_URL = 'http://api.gu1.ai' class KYBProcessor: def __init__(self, api_key: str): self.api_key = api_key self.headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } def create_business_entity(self, application: Dict) -> Dict: """Step 1: Create business entity""" print('📋 Creating business entity...') response = requests.post( f'{GUENO_API_URL}/entities', headers=self.headers, json={ 'type': 'company', 'externalId': application['business_id'], 'name': application['legal_name'], 'taxId': application['tax_id'], 'countryCode': application['country_code'], 'entityData': { 'company': { 'legalName': application['legal_name'], 'tradeName': application['trade_name'], 'incorporationDate': application['incorporation_date'], 'industry': application['industry'], 'employeeCount': application.get('employee_count'), 'revenue': application.get('revenue') } }, 'attributes': { 'website': application.get('website'), 'registeredAddress': application['address'], 'contactEmail': application['contact_email'], 'contactPhone': application['contact_phone'], 'expectedMonthlyVolume': application['expected_monthly_volume'], 'applicationDate': datetime.now().isoformat() } } ) response.raise_for_status() entity = response.json()['entity'] print(f'✅ Entity created: {entity["id"]}') return entity def upload_documents(self, entity_id: str, documents: List[Dict]) -> List[Dict]: """Step 2: Upload verification documents""" print(f'📄 Uploading {len(documents)} documents...') upload_results = [] for doc in documents: with open(doc['file_path'], 'rb') as file: files = {'file': file} data = { 'documentType': doc['type'], 'entityId': entity_id } response = requests.post( f'{GUENO_API_URL}/documents', headers={'Authorization': f'Bearer {self.api_key}'}, data=data, files=files ) response.raise_for_status() print(f' ✅ Uploaded: {doc["type"]}') upload_results.append(response.json()) return upload_results def request_ai_analysis(self, entity_id: str) -> Dict: """Step 3: Request AI analysis""" print('🤖 Requesting AI analysis...') response = requests.post( f'{GUENO_API_URL}/entities/{entity_id}/ai-analysis', headers=self.headers, json={ 'analysisType': 'kyb_verification', 'includeDocuments': True, 'checkSanctions': True, 'checkAdverseMedia': True, 'checkUBOs': True } ) response.raise_for_status() analysis = response.json() print(f'✅ Analysis complete. Risk Score: {analysis["riskScore"]}') return analysis def verify_beneficial_owners(self, entity_id: str, owners: List[Dict]) -> List[Dict]: """Step 4: Verify beneficial owners""" print(f'👥 Verifying {len(owners)} beneficial owners...') verified_owners = [] for owner in owners: # Create person entity for UBO ubo_response = requests.post( f'{GUENO_API_URL}/entities', headers=self.headers, json={ 'type': 'person', 'externalId': f'ubo_{entity_id}_{owner["id_number"]}', 'name': f'{owner["first_name"]} {owner["last_name"]}', 'countryCode': owner['nationality'], 'entityData': { 'person': { 'firstName': owner['first_name'], 'lastName': owner['last_name'], 'dateOfBirth': owner['date_of_birth'], 'nationality': owner['nationality'] } }, 'attributes': { 'ownershipPercentage': owner['ownership_percentage'], 'isPEP': owner['is_pep'], 'relationshipToCompany': 'beneficial_owner' } } ) ubo = ubo_response.json()['entity'] # Run KYC check kyc_response = requests.post( f'{GUENO_API_URL}/entities/{ubo["id"]}/ai-analysis', headers=self.headers, json={ 'analysisType': 'kyc_verification', 'checkPEP': True, 'checkSanctions': True } ) # Create relationship requests.post( f'{GUENO_API_URL}/relationships', headers=self.headers, json={ 'fromEntityId': entity_id, 'toEntityId': ubo['id'], 'relationshipType': 'beneficial_owner', 'metadata': { 'ownershipPercentage': owner['ownership_percentage'] } } ) print(f' ✅ Verified: {owner["first_name"]} {owner["last_name"]}') verified_owners.append({ **ubo, 'kycStatus': kyc_response.json()['status'], 'riskScore': kyc_response.json()['riskScore'] }) return verified_owners def make_decision(self, entity_id: str, analysis: Dict) -> str: """Step 5: Make decision based on risk""" print('⚖️ Making KYB decision...') risk_score = analysis['riskScore'] if risk_score < 30: self.approve_entity(entity_id, analysis) return 'approved' elif risk_score < 70: self.request_enhanced_due_diligence(entity_id, analysis) return 'pending' else: self.flag_for_manual_review(entity_id, analysis) return 'manual_review' def approve_entity(self, entity_id: str, analysis: Dict): """Approve low-risk entity""" print('✅ Auto-approving low-risk entity...') requests.patch( f'{GUENO_API_URL}/entities/{entity_id}', headers=self.headers, json={ 'attributes': { 'kybStatus': 'approved', 'approvedAt': datetime.now().isoformat(), 'approvedBy': 'automated_system', 'riskLevel': 'low' } } ) self.setup_monitoring(entity_id) self.send_status_notification(entity_id, 'approved') def request_enhanced_due_diligence(self, entity_id: str, analysis: Dict): """Request enhanced due diligence""" print('🔍 Requesting enhanced due diligence...') requests.patch( f'{GUENO_API_URL}/entities/{entity_id}', headers=self.headers, json={ 'attributes': { 'kybStatus': 'enhanced_due_diligence', 'requestedAt': datetime.now().isoformat(), 'riskLevel': 'medium', 'additionalDocsRequired': [ 'financial_statements', 'ownership_structure', 'source_of_funds' ] } } ) self.send_status_notification(entity_id, 'additional_info_required') def flag_for_manual_review(self, entity_id: str, analysis: Dict): """Flag for manual review""" print('⚠️ Flagging for manual review...') requests.post( f'{GUENO_API_URL}/tasks', headers=self.headers, json={ 'type': 'manual_review', 'entityId': entity_id, 'priority': 'high', 'assignTo': 'compliance_team', 'dueDate': (datetime.now() + timedelta(days=1)).isoformat(), 'context': { 'riskScore': analysis['riskScore'], 'riskFactors': analysis['riskFactors'], 'findings': analysis['findings'] } } ) def setup_monitoring(self, entity_id: str): """Setup ongoing monitoring""" print('📊 Setting up ongoing monitoring...') requests.post( f'{GUENO_API_URL}/rules', headers=self.headers, json={ 'name': f'KYB Monitoring - {entity_id}', 'entityId': entity_id, 'active': True, 'rules': [ { 'type': 'sanctions_screening', 'frequency': 'daily', 'action': 'alert_compliance_team' }, { 'type': 'adverse_media', 'frequency': 'weekly', 'action': 'create_review_task' } ] } ) def send_status_notification(self, entity_id: str, status: str): """Send status notification""" print(f'📧 Sending {status} notification...') requests.post( f'{GUENO_API_URL}/webhooks/send', headers=self.headers, json={ 'event': 'kyb_status_changed', 'entityId': entity_id, 'status': status, 'timestamp': datetime.now().isoformat() } ) def process_kyb(self, application: Dict) -> Dict: """Complete KYB workflow""" try: print('🚀 Starting KYB verification process...\n') # Step 1: Create entity entity = self.create_business_entity(application) # Step 2: Upload documents self.upload_documents(entity['id'], application['documents']) # Step 3: AI Analysis analysis = self.request_ai_analysis(entity['id']) # Step 4: Verify UBOs verified_owners = self.verify_beneficial_owners( entity['id'], application['beneficial_owners'] ) # Step 5: Make decision status = self.make_decision(entity['id'], analysis) print('\n✨ KYB process completed successfully!') return { 'success': True, 'entityId': entity['id'], 'status': status, 'riskScore': analysis['riskScore'], 'findings': analysis['findings'], 'nextSteps': analysis['nextSteps'] } except Exception as e: print(f'❌ KYB process failed: {str(e)}') return { 'success': False, 'entityId': '', 'status': 'rejected', 'riskScore': 100, 'findings': {'error': str(e)}, 'nextSteps': ['Contact support'] } # Example usage if __name__ == '__main__': processor = KYBProcessor(GUENO_API_KEY) application = { 'business_id': 'business_12345', 'legal_name': 'Tech Solutions Sociedade Anônima', 'trade_name': 'Tech Solutions', 'tax_id': '12.345.678/0001-90', 'country_code': 'BR', 'incorporation_date': '2020-06-15', 'industry': 'Software Development', 'website': 'https://techsolutions.com.br', 'employee_count': 50, 'revenue': 5000000, 'address': { 'street': 'Av. Paulista, 1000', 'city': 'São Paulo', 'state': 'SP', 'postalCode': '01310-100', 'country': 'BR' }, 'contact_email': 'contact@techsolutions.com.br', 'contact_phone': '+55 11 1234-5678', 'expected_monthly_volume': 250000, 'beneficial_owners': [ { 'first_name': 'Carlos', 'last_name': 'Silva', 'date_of_birth': '1975-08-22', 'nationality': 'BR', 'ownership_percentage': 60, 'is_pep': False, 'id_number': '123.456.789-00' }, { 'first_name': 'Ana', 'last_name': 'Costa', 'date_of_birth': '1980-03-15', 'nationality': 'BR', 'ownership_percentage': 40, 'is_pep': False, 'id_number': '987.654.321-00' } ], 'documents': [ {'type': 'articles_of_incorporation', 'file_path': './docs/contrato_social.pdf'}, {'type': 'tax_certificate', 'file_path': './docs/cnpj_certificate.pdf'}, {'type': 'business_license', 'file_path': './docs/alvara.pdf'}, {'type': 'proof_of_address', 'file_path': './docs/comprovante.pdf'} ] } result = processor.process_kyb(application) print('\n📊 Final Result:') print(result) ``` ## Expected Output When you run the complete workflow, you'll see: ``` 🚀 Starting KYB verification process... 📋 Creating business entity... ✅ Entity created: 660e9511-f39c-52e5-b827-557766551111 📄 Uploading 4 documents... ✅ Uploaded: articles_of_incorporation ✅ Uploaded: tax_certificate ✅ Uploaded: business_license ✅ Uploaded: proof_of_address 🤖 Requesting AI analysis... ✅ Analysis complete. Risk Score: 35 👥 Verifying 2 beneficial owners... ✅ Verified: Carlos Silva ✅ Verified: Ana Costa ⚖️ Making KYB decision... 🔍 Requesting enhanced due diligence... 📧 Sending additional_info_required notification... ✨ KYB process completed successfully! 📊 Final Result: { "success": true, "entityId": "660e9511-f39c-52e5-b827-557766551111", "status": "pending", "riskScore": 35, "findings": { "documentVerification": "verified", "sanctionsScreening": "clear", "adverseMedia": "minor_flags" }, "nextSteps": [ "Provide financial statements", "Submit ownership structure diagram", "Document source of funds" ] } ``` ## Testing Test the KYB workflow with sample data: ```bash theme={null} # Install dependencies npm install axios form-data # or pip install requests # Set your API key export GUENO_API_KEY="your_api_key_here" # Run the example node kyb-example.ts # or python kyb_example.py ``` ## Production Considerations ### Error Handling ```typescript theme={null} try { const result = await kybProcessor.processKYB(application); } catch (error) { if (error.response?.status === 401) { console.error('Invalid API key'); } else if (error.response?.status === 429) { console.error('Rate limit exceeded - retry in 60s'); } else { console.error('KYB process failed:', error.message); } } ``` ### Webhook Integration Setup webhooks to receive real-time updates: ```typescript theme={null} app.post('/webhooks/kyb', (req, res) => { const { event, entityId, status } = req.body; switch (status) { case 'approved': // Enable business features enableBusinessAccount(entityId); break; case 'additional_info_required': // Request more documents requestAdditionalDocs(entityId); break; case 'manual_review': // Notify compliance team alertComplianceTeam(entityId); break; } res.sendStatus(200); }); ``` ## Next Steps > [card] [KYB Overview](/use-cases/kyb/overview) > > Understand KYB concepts and benefits > [card] [KYB Workflow](/use-cases/kyb/workflow) > > Detailed step-by-step process > [card] [Data Requirements](/use-cases/kyb/data-requirements) > > Required fields and documents > [card] [API Reference](/api-reference/entities/create) > > Complete API documentation # KYB Overview Source: https://docs.gu1.ai/en/use-cases/kyb/overview Automate KYB business verification with gu1: validate company registries, screen against sanctions, identify beneficial owners, and score risk in real time. ## What is KYB (Know Your Business)? Know Your Business (KYB) is the process of verifying the identity and legitimacy of business entities before establishing commercial relationships. gu1's KYB solution automates business verification, beneficial ownership identification, and ongoing risk monitoring to ensure compliance with AML/CFT regulations. ## Why KYB Matters ### Regulatory Compliance * **AML/CFT Requirements**: Meet anti-money laundering and counter-terrorism financing obligations * **Global Standards**: Comply with FATF recommendations and local regulations * **Audit Trail**: Maintain complete documentation for regulatory audits * **Ongoing Monitoring**: Continuous compliance with changing regulations ### Business Risk Management * **Due Diligence**: Comprehensive assessment of business partners and clients * **Fraud Prevention**: Detect shell companies and fraudulent business entities * **Reputation Protection**: Avoid relationships with high-risk or sanctioned businesses * **Financial Crime Prevention**: Identify money laundering and terrorist financing risks ### Operational Efficiency * **Automated Verification**: Reduce manual review time by up to 80% * **Faster Onboarding**: Complete KYB checks in minutes instead of days * **Cost Reduction**: Lower operational costs with AI-powered automation * **Scalability**: Handle high volumes without proportional resource increases ## Key KYB Verification Components ### 1. Business Identity Verification * **Legal Name & Trade Name**: Verify official business names * **Registration Number**: Validate government registration numbers * **Tax Identification**: Verify tax IDs (EIN, CNPJ, RFC, etc.) * **Incorporation Details**: Confirm incorporation date and jurisdiction * **Business Address**: Validate registered office location ### 2. Beneficial Ownership * **Ultimate Beneficial Owners (UBOs)**: Identify individuals with >25% ownership * **Control Structure**: Map ownership hierarchy and control chains * **PEP Screening**: Screen owners against politically exposed persons lists * **Sanctions Screening**: Check owners against global sanctions lists * **Adverse Media**: Monitor negative news about owners and directors ### 3. Document Verification * **Articles of Incorporation**: Verify founding documents * **Business Licenses**: Validate operating licenses and permits * **Tax Certificates**: Confirm tax registration status * **Financial Statements**: Assess financial health and stability * **Proof of Address**: Verify business location ### 4. Risk Assessment * **Industry Risk**: Evaluate risk level based on business sector * **Geographic Risk**: Assess jurisdiction and operational location risks * **Transaction Patterns**: Analyze expected vs. actual transaction behavior * **Relationship Risk**: Evaluate partners, suppliers, and customers * **Compliance History**: Review past violations or regulatory actions ## gu1's KYB Advantages ### AI-Powered Intelligence * **Document Analysis**: Automatically extract data from business documents * **OCR Technology**: Read and validate documents in 100+ languages * **Anomaly Detection**: Identify inconsistencies and red flags * **Risk Scoring**: Dynamic risk scores based on 50+ factors * **Predictive Analytics**: Forecast potential compliance issues ### Global Coverage * **200+ Jurisdictions**: Support for businesses worldwide * **Local Regulations**: Country-specific compliance requirements * **Multi-Language**: Documentation and support in multiple languages * **Regional Experts**: Built-in knowledge of local business practices ### Continuous Monitoring * **Real-Time Updates**: Automatic alerts on business changes * **Ownership Changes**: Monitor UBO updates and transfers * **Sanctions Lists**: Daily screening against updated lists * **Adverse Media**: Ongoing monitoring of negative news * **License Expiry**: Track business license renewals ### Integration & Automation * **API-First Design**: Easy integration with existing systems * **Webhook Notifications**: Real-time alerts for status changes * **Bulk Processing**: Handle high volumes efficiently * **Workflow Automation**: Customizable approval workflows * **No-Code Rules**: Build verification rules without programming ## Common KYB Use Cases ### Financial Institutions * **Business Banking**: Verify commercial account applicants * **Merchant Onboarding**: Screen payment processing clients * **Business Lending**: Assess creditworthiness and legitimacy * **Trade Finance**: Verify import/export business partners ### Fintech & Payment Processors * **Marketplace Sellers**: Verify vendor identities on platforms * **Payment Gateways**: Screen merchants before activation * **Crypto Exchanges**: Comply with crypto business regulations * **P2P Platforms**: Verify business users on peer networks ### B2B Marketplaces * **Supplier Verification**: Validate vendor legitimacy * **Buyer Screening**: Assess purchasing entity risk * **Partner Onboarding**: Due diligence on business partners * **Distribution Networks**: Verify channel partners ### Real Estate & Professional Services * **Property Transactions**: Verify buyer/seller entities * **Legal Services**: Client identification for firms * **Accounting Firms**: Verify business clients * **Consulting**: Screen enterprise clients ## KYB vs KYC | Aspect | KYB (Business) | KYC (Individual) | | - | - | - | | **Subject** | Legal entities | Individual persons | | **Complexity** | Higher (ownership structures) | Lower (single identity) | | **Documents** | Corporate records, licenses | ID documents, proof of address | | **Timeline** | 2-5 days (traditional) | 1-2 days (traditional) | | **Ongoing Monitoring** | Complex (multiple stakeholders) | Simpler (single person) | | **Risk Factors** | Industry, jurisdiction, UBOs | Income, nationality, PEP status | | **gu1 Processing** | Minutes with AI automation | Seconds with AI automation | ## Regulatory Framework ### International Standards * **FATF Recommendations**: Follow Financial Action Task Force guidelines * **Basel AML Index**: Risk assessment based on global standards * **EU AMLD6**: Sixth Anti-Money Laundering Directive compliance * **US Bank Secrecy Act**: Customer Due Diligence (CDD) requirements ### Regional Regulations * **United States**: FinCEN CDD Rule, USA PATRIOT Act * **European Union**: 4th, 5th, 6th AML Directives (AMLD) * **United Kingdom**: Money Laundering Regulations 2017 * **Brazil**: COAF regulations, BACEN requirements * **Singapore**: MAS AML/CFT guidelines * **UAE**: FATF compliance, UAE AML laws ## Risk Categories ### Low Risk * Established businesses (10+ years) * Publicly traded companies * Government entities * Regulated industries with good compliance * Low-risk jurisdictions ### Medium Risk * New businesses (1-5 years) * Private companies with clear ownership * Medium-risk industries * Emerging market jurisdictions * Complex ownership structures ### High Risk * Newly incorporated companies (less than 1 year) * Shell companies or nominee structures * High-risk industries (crypto, cash-intensive) * High-risk jurisdictions (non-FATF compliant) * Politically exposed ownership * Adverse media findings ## Get Started with KYB Ready to implement automated KYB verification? > [card] [KYB Workflow](/use-cases/kyb/workflow) > > Step-by-step KYB verification process > [card] [Data Requirements](/use-cases/kyb/data-requirements) > > Required data for business verification > [card] [Complete Example](/use-cases/kyb/example) > > Full KYB implementation with code > [card] [API Reference](/api-reference/entities/create) > > API documentation for entity creation ## Next Steps 1. [Review the KYB Workflow](/use-cases/kyb/workflow) - Understand the complete verification process 2. [Check Data Requirements](/use-cases/kyb/data-requirements) - See what data you need to collect 3. [Run the Complete Example](/use-cases/kyb/example) - Implement KYB with code samples 4. [Get Your API Key](https://app.gu1.ai/org-api-keys) - Start building your integration # KYB Workflow Source: https://docs.gu1.ai/en/use-cases/kyb/workflow Step-by-step KYB workflow in gu1 covering data intake, registry enrichment, sanctions and adverse media screening, decisioning, and ongoing monitoring. ## Complete KYB Verification Workflow gu1's KYB workflow automates the entire business verification process from initial data collection to ongoing monitoring. This guide walks through each step with technical implementation details. ## Workflow Overview ```mermaid theme={null} graph TD A[Business Applies] --> B[Data Collection] B --> C[Create Entity] C --> D[Document Upload] D --> E[AI Analysis] E --> F[Risk Assessment] F --> G{Risk Score} G -->|Low Risk| H[Auto-Approve] G -->|Medium Risk| I[Enhanced Due Diligence] G -->|High Risk| J[Manual Review] H --> K[Ongoing Monitoring] I --> K J --> K K --> L[Status Updates] ``` ## Step 1: Initial Data Collection ### What to Collect Gather basic business information from your application form: * **Company Name**: Legal name and trade name * **Registration Number**: Government-issued business registration * **Tax ID**: EIN (US), CNPJ (Brazil), RFC (Mexico), etc. * **Incorporation Date**: When the business was formed * **Country**: Jurisdiction of incorporation * **Business Address**: Registered office location * **Industry**: Type of business activity * **Expected Transaction Volume**: Monthly/annual estimates ### Example Application Form ```javascript theme={null} const businessApplication = { legalName: "Tech Solutions Sociedade Anônima", tradeName: "Tech Solutions", registrationNumber: "12.345.678/0001-90", taxId: "12.345.678/0001-90", incorporationDate: "2020-06-15", country: "BR", address: { street: "Av. Paulista, 1000", city: "São Paulo", state: "SP", postalCode: "01310-100" }, industry: "Software Development", website: "https://techsolutions.com.br", expectedMonthlyVolume: 250000, businessDescription: "B2B SaaS platform for enterprise clients" }; ``` ## Step 2: Create Business Entity Use the Entities API to create a company entity in gu1: ```bash cURL theme={null} curl -X POST http://api.gu1.ai/entities \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "company", "externalId": "business_12345", "name": "Tech Solutions Sociedade Anônima", "taxId": "12.345.678/0001-90", "countryCode": "BR", "entityData": { "company": { "legalName": "Tech Solutions Sociedade Anônima", "tradeName": "Tech Solutions", "incorporationDate": "2020-06-15", "industry": "Software Development", "employeeCount": 50, "revenue": 5000000 } }, "attributes": { "registrationNumber": "12.345.678/0001-90", "website": "https://techsolutions.com.br", "registeredAddress": "Av. Paulista, 1000, São Paulo", "expectedMonthlyVolume": 250000, "applicationDate": "2024-10-03T10:00:00Z" } }' ``` ```javascript JavaScript theme={null} async function createBusinessEntity(applicationData) { const response = await fetch('http://api.gu1.ai/entities', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'company', externalId: applicationData.businessId, name: applicationData.legalName, taxId: applicationData.taxId, countryCode: applicationData.country, entityData: { company: { legalName: applicationData.legalName, tradeName: applicationData.tradeName, incorporationDate: applicationData.incorporationDate, industry: applicationData.industry, employeeCount: applicationData.employeeCount, revenue: applicationData.estimatedRevenue } }, attributes: { registrationNumber: applicationData.registrationNumber, website: applicationData.website, registeredAddress: applicationData.address, expectedMonthlyVolume: applicationData.expectedVolume, applicationDate: new Date().toISOString() } }) }); const result = await response.json(); return result.entity; } ``` ```python Python theme={null} import requests def create_business_entity(application_data): response = requests.post( 'http://api.gu1.ai/entities', headers={ 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' }, json={ 'type': 'company', 'externalId': application_data['business_id'], 'name': application_data['legal_name'], 'taxId': application_data['tax_id'], 'countryCode': application_data['country'], 'entityData': { 'company': { 'legalName': application_data['legal_name'], 'tradeName': application_data['trade_name'], 'incorporationDate': application_data['incorporation_date'], 'industry': application_data['industry'], 'employeeCount': application_data.get('employee_count'), 'revenue': application_data.get('estimated_revenue') } }, 'attributes': { 'registrationNumber': application_data['registration_number'], 'website': application_data.get('website'), 'registeredAddress': application_data['address'], 'expectedMonthlyVolume': application_data['expected_volume'], 'applicationDate': datetime.now().isoformat() } } ) return response.json()['entity'] ``` **Response:** ```json theme={null} { "success": true, "entity": { "id": "660e9511-f39c-52e5-b827-557766551111", "externalId": "business_12345", "type": "company", "name": "Tech Solutions Sociedade Anônima", "riskScore": 0, "status": "under_review", "createdAt": "2024-10-03T10:00:00Z" } } ``` ## Step 3: Document Upload & Verification Upload required business documents for verification: ### Required Documents 1. **Articles of Incorporation** - Founding document 2. **Business License** - Government-issued operating permit 3. **Tax Certificate** - Proof of tax registration 4. **Proof of Address** - Utility bill or bank statement 5. **Beneficial Ownership Declaration** - UBO information ### Upload Documents ```javascript theme={null} async function uploadBusinessDocuments(entityId, documents) { const documentUploads = []; for (const doc of documents) { const formData = new FormData(); formData.append('file', doc.file); formData.append('documentType', doc.type); formData.append('entityId', entityId); const response = await fetch('http://api.gu1.ai/documents', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}` }, body: formData }); documentUploads.push(await response.json()); } return documentUploads; } // Usage const documents = [ { file: articlesOfIncorporation, type: 'articles_of_incorporation' }, { file: businessLicense, type: 'business_license' }, { file: taxCertificate, type: 'tax_certificate' }, { file: proofOfAddress, type: 'proof_of_address' } ]; const uploadedDocs = await uploadBusinessDocuments(entityId, documents); ``` ## Step 4: AI Analysis & Risk Assessment Request AI-powered analysis of the business entity: ```javascript theme={null} async function requestAIAnalysis(entityId) { const response = await fetch( `http://api.gu1.ai/entities/${entityId}/ai-analysis`, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ analysisType: 'kyb_verification', includeDocuments: true, checkSanctions: true, checkAdverseMedia: true }) } ); return await response.json(); } ``` **AI Analysis Response:** ```json theme={null} { "analysisId": "analysis_abc123", "entityId": "660e9511-f39c-52e5-b827-557766551111", "riskScore": 35, "riskLevel": "medium", "findings": { "documentVerification": { "status": "verified", "confidence": 0.95, "articlesOfIncorporation": "valid", "businessLicense": "valid", "taxCertificate": "valid" }, "businessLegitimacy": { "status": "verified", "registrationVerified": true, "taxIdValid": true, "addressConfirmed": true }, "sanctionsScreening": { "status": "clear", "listsChecked": ["OFAC", "UN", "EU", "UK"], "matches": [] }, "adverseMedia": { "status": "minor_flags", "findings": [ { "source": "news_article", "date": "2023-05-15", "summary": "Small tax dispute resolved", "severity": "low" } ] }, "riskFactors": [ { "factor": "new_business", "impact": 20, "description": "Company incorporated less than 5 years ago" }, { "factor": "high_growth_industry", "impact": 15, "description": "Software industry has elevated fraud risk" }, { "factor": "clean_compliance_history", "impact": -10, "description": "No regulatory violations found" } ] }, "recommendation": "approve_with_monitoring", "nextSteps": [ "Verify beneficial ownership", "Set transaction monitoring thresholds", "Schedule 6-month review" ] } ``` ## Step 5: Risk-Based Decision Based on the risk score, route to appropriate workflow: ```javascript theme={null} async function processKYBDecision(analysisResult) { const { riskScore, riskLevel, recommendation } = analysisResult; if (riskScore < 30) { // Low Risk - Auto-approve return await autoApprove(analysisResult.entityId); } else if (riskScore < 70) { // Medium Risk - Enhanced Due Diligence return await enhancedDueDiligence(analysisResult.entityId); } else { // High Risk - Manual Review Required return await flagForManualReview(analysisResult.entityId, analysisResult.findings); } } async function autoApprove(entityId) { // Update entity status to approved await fetch(`http://api.gu1.ai/entities/${entityId}`, { method: 'PATCH', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { kybStatus: 'approved', approvedAt: new Date().toISOString(), approvedBy: 'automated_system', reviewNotes: 'Low risk - auto-approved' } }) }); // Send approval notification await sendApprovalEmail(entityId); // Enable monitoring await enableOngoingMonitoring(entityId); return { status: 'approved', action: 'auto_approved' }; } async function enhancedDueDiligence(entityId) { // Request additional information await requestAdditionalDocs(entityId, [ 'financial_statements', 'ownership_structure', 'source_of_funds' ]); // Update status await updateEntityStatus(entityId, 'enhanced_due_diligence'); return { status: 'pending', action: 'edd_required' }; } async function flagForManualReview(entityId, findings) { // Create review task await createReviewTask({ entityId, priority: 'high', assignTo: 'compliance_team', findings, dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours }); return { status: 'manual_review', action: 'flagged_for_review' }; } ``` ## Step 6: Beneficial Ownership Verification Identify and verify Ultimate Beneficial Owners (UBOs): ```javascript theme={null} async function verifyBeneficialOwners(entityId, owners) { const verifiedOwners = []; for (const owner of owners) { // Create person entity for each UBO const uboEntity = await fetch('http://api.gu1.ai/entities', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'person', externalId: `ubo_${owner.id}`, name: `${owner.firstName} ${owner.lastName}`, countryCode: owner.nationality, entityData: { person: { firstName: owner.firstName, lastName: owner.lastName, dateOfBirth: owner.dateOfBirth, nationality: owner.nationality } }, attributes: { ownershipPercentage: owner.ownership, isPEP: owner.isPEP, relationshipToCompany: 'beneficial_owner' } }) }); const ubo = await uboEntity.json(); // Run KYC checks on UBO const kycResult = await runKYCCheck(ubo.entity.id); // Create relationship between company and UBO await createRelationship({ fromEntityId: entityId, toEntityId: ubo.entity.id, relationshipType: 'beneficial_owner', ownershipPercentage: owner.ownership }); verifiedOwners.push({ ...ubo.entity, kycStatus: kycResult.status, riskScore: kycResult.riskScore }); } return verifiedOwners; } ``` ## Step 7: Setup Ongoing Monitoring Enable continuous monitoring for approved businesses: ```javascript theme={null} async function setupOngoingMonitoring(entityId) { // Configure monitoring rules await fetch('http://api.gu1.ai/rules', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: `KYB Monitoring - ${entityId}`, entityId: entityId, rules: [ { type: 'sanctions_screening', frequency: 'daily', action: 'alert_compliance_team' }, { type: 'adverse_media', frequency: 'weekly', action: 'create_review_task' }, { type: 'ownership_changes', frequency: 'realtime', action: 'trigger_reverification' }, { type: 'transaction_anomalies', threshold: 'high', action: 'flag_for_review' } ] }) }); // Setup webhook notifications await configureWebhook({ entityId, events: [ 'sanctions_match', 'adverse_media_found', 'ownership_change', 'transaction_anomaly' ], url: 'https://your-app.com/webhooks/kyb-alerts' }); } ``` ## Step 8: Status Updates & Notifications Keep the business informed throughout the process: ```javascript theme={null} async function sendStatusUpdate(entityId, status, details) { // Get entity details const entity = await getEntity(entityId); // Send email notification await sendEmail({ to: entity.attributes.contactEmail, subject: `KYB Verification Update - ${status}`, template: 'kyb_status_update', data: { companyName: entity.name, status: status, details: details, nextSteps: getNextSteps(status), dashboardUrl: `https://app.gu1.ai/onboarding/${entityId}` } }); // Send webhook to your system await sendWebhook({ event: 'kyb_status_changed', entityId: entityId, status: status, timestamp: new Date().toISOString(), details: details }); } // Status update examples await sendStatusUpdate(entityId, 'documents_received', { message: 'We have received your documents and are processing them.' }); await sendStatusUpdate(entityId, 'approved', { message: 'Your business has been verified and approved!', approvalDate: new Date().toISOString() }); await sendStatusUpdate(entityId, 'additional_info_required', { message: 'We need additional information to complete your verification.', requiredDocuments: ['financial_statements', 'ownership_structure'] }); ``` ## Complete Workflow Implementation Here's a complete function that orchestrates the entire KYB workflow: ```javascript theme={null} async function executeKYBWorkflow(applicationData) { try { // Step 1 & 2: Create entity console.log('Creating business entity...'); const entity = await createBusinessEntity(applicationData); // Step 3: Upload documents console.log('Uploading verification documents...'); await uploadBusinessDocuments(entity.id, applicationData.documents); // Step 4: Request AI analysis console.log('Running AI analysis...'); const analysis = await requestAIAnalysis(entity.id); // Step 5: Make risk-based decision console.log('Processing KYB decision...'); const decision = await processKYBDecision(analysis); if (decision.status === 'approved') { // Step 6: Verify UBOs (for approved entities) console.log('Verifying beneficial owners...'); await verifyBeneficialOwners(entity.id, applicationData.beneficialOwners); // Step 7: Setup monitoring console.log('Setting up ongoing monitoring...'); await setupOngoingMonitoring(entity.id); } // Step 8: Send status update console.log('Sending status notification...'); await sendStatusUpdate(entity.id, decision.status, analysis.findings); return { success: true, entityId: entity.id, status: decision.status, riskScore: analysis.riskScore, decision: decision }; } catch (error) { console.error('KYB workflow error:', error); return { success: false, error: error.message }; } } ``` ## Timeline Estimates | Risk Level | Automated Processing | With Manual Review | Traditional Process | | - | - | - | - | | **Low Risk** | 2-5 minutes | 30 minutes | 2-3 days | | **Medium Risk** | 15-30 minutes | 2-4 hours | 3-5 days | | **High Risk** | 30-60 minutes | 1-2 days | 5-10 days | ## Next Steps > [card] [Data Requirements](/use-cases/kyb/data-requirements) > > See detailed data fields needed for KYB > [card] [Complete Example](/use-cases/kyb/example) > > Full working code implementation > [card] [API Reference](/api-reference/entities/create) > > Entity creation API documentation > [card] [Webhooks](/en/webhooks/overview) > > Setup real-time notifications # Approve KYC Validation Source: https://docs.gu1.ai/en/use-cases/kyc/approve-validation POST /api/kyc/validations/{id}/approve Manually approve a KYC validation — in the gu1 KYC API for identity verification flows, with examples for approve validation use cases. ## Overview This endpoint allows you to manually approve a KYC validation. When you approve: * **Automatic sync with provider**: The system first syncs with the KYC provider to get the latest verification status * **Status validation**: You can only approve if provider status is `in_review` (user has completed verification and requires manual review from compliance team) * The validation status changes to `approved` * The validation is marked as verified with timestamp * The approval reason is saved in metadata and audit logs * With **`doubleCheckRenaper`**: RENAPER is **not** re-run and cross-check enforcement is **not** re-applied; the API reuses `metadata.responseDoubleChecks.renaper` and `warnings` already computed in `in_review`. The decision is human after reviewing that data in the UI. > [!WARNING] > > Manual approval should only be used when you've performed additional verification or have sufficient reason to override the automated process. The approval reason is required for audit compliance. ## When to Use This * **Additional verification completed**: You've performed manual review of documents or biometric data * **Business exception**: You have business reasons to approve despite minor issues * **Risk assessment override**: Your risk team has approved the validation * **Provider delay**: The verification provider is taking too long but your internal review is complete ## Request ### Endpoint ``` POST https://api.gu1.ai/api/kyc/validations/{id}/approve ``` ### Path Parameters **id** `string` *required* The validation ID to approve ### Headers ```json theme={null} { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } ``` ### Body Parameters **reason** `string` *required* Reason for manually approving the validation (minimum 5 characters) **Type**: `string` (min length: 5) **Example**: `"Manual review completed successfully - all documents verified"` ## Response ### Success Response (200 OK) Returns the updated validation object with `approved` status: ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "entityId": "123e4567-e89b-12d3-a456-426614174000", "organizationId": "org_abc123", "validationSessionId": "session_xyz789", "status": "approved", "provider": "kyc_provider", "providerSessionUrl": "https://verify.example.com/session_xyz789", "isCurrent": true, "verifiedAt": "2025-01-27T10:30:00Z", "metadata": { "manuallyApprovedBy": "user_123", "manuallyApprovedAt": "2025-01-27T10:30:00Z", "approvalReason": "Manual review completed successfully - all documents verified" }, "createdAt": "2025-01-15T10:30:00Z", "updatedAt": "2025-01-27T10:30:00Z" } ``` ## Example Request ```javascript Node.js theme={null} const validationId = '550e8400-e29b-41d4-a716-446655440000'; const response = await fetch( `https://api.gu1.ai/api/kyc/validations/${validationId}/approve`, { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ reason: 'Manual review completed successfully - all documents verified' }) } ); const approved = await response.json(); console.log('Validation approved:', approved.status); ``` ```python Python theme={null} import requests validation_id = '550e8400-e29b-41d4-a716-446655440000' response = requests.post( f'https://api.gu1.ai/api/kyc/validations/{validation_id}/approve', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, json={ 'reason': 'Manual review completed successfully - all documents verified' } ) approved = response.json() print('Validation approved:', approved['status']) ``` ```curl cURL theme={null} curl -X POST https://api.gu1.ai/api/kyc/validations/550e8400-e29b-41d4-a716-446655440000/approve \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Manual review completed successfully - all documents verified" }' ``` ## Error Responses ### Validation Not Found (404) ```json theme={null} { "error": "NOT_FOUND", "message": "Validation not found" } ``` ### Invalid Status (400) Validation can only be approved if provider status is `in_review` (user has completed verification and requires manual review from compliance team): ```json theme={null} { "error": "INVALID_STATUS", "message": "Cannot manually approve. Current status is \"approved\". Manual approval is only allowed when status is \"in_review\" (validation requires manual review from compliance team)." } ``` **What this means:** * If the provider already approved (`approved`) or rejected (`rejected`) the validation, you cannot override that decision * If the validation is `cancelled`, you cannot approve it * If it's `expired` or `abandoned`, it also cannot be manually approved * If it's `in_progress`, the user is still filling out the verification form * **You can only approve** when the provider reports the validation as `in_review` (user has completed all verification steps and requires manual review from compliance team) ### Invalid Reason (400) Reason must be at least 5 characters: ```json theme={null} { "error": "VALIDATION_ERROR", "message": "Reason must be at least 5 characters" } ``` ## Important Notes > [accordion] Automatic Sync Before Approval > > Before approving, the system automatically syncs with the KYC provider to get the latest verification data. This ensures you're making decisions based on the most recent information. > [accordion] Status Protection > > You cannot approve validations that are already `approved`, `rejected`, or `cancelled`. These statuses are protected to maintain data integrity. > [accordion] Audit Trail > > The approval reason is saved in both the validation metadata and audit logs. This is critical for compliance and regulatory requirements. > [accordion] Only for In-Review Validations > > Manual approval is only allowed when the provider reports the validation as `in_review`. This prevents approving validations that: > > * The provider has already declined or completed > * Don't have complete verification data (status `pending` or `in_progress`) > * The user is still filling out the form (status `in_progress`) > [accordion] Verification Timestamp > > When approved, the validation receives a `verifiedAt` timestamp and becomes the current validation for the entity. ## Best Practices * **Always provide detailed reasons**: Include specific details about why manual approval is necessary * **Document your process**: Maintain internal documentation for manual approval criteria * **Review fresh data**: The automatic sync ensures you see the latest documents and biometric results * **Use sparingly**: Manual approval should be the exception, not the rule * **Train your team**: Ensure staff understand when manual approval is appropriate ## Next Steps > [card] [Reject Validation](/en/use-cases/kyc/reject-validation) > > Manually reject a validation > [card] [Check Verification Status](/en/use-cases/kyc/check-status) > > Query validation results # Biometric Check Source: https://docs.gu1.ai/en/use-cases/kyc/biometric POST /api/kyc/biometric Validate a face image against previously approved KYC sessions — in the gu1 KYC API for identity verification flows, with examples for biometric use cases. ## Overview > [!NOTE] > > For **step-up authentication** with hosted liveness capture (iframe), use [Embedded Biometric Session](/en/use-cases/kyc/embedded-biometric) (`POST /api/kyc/biometric/sessions`) instead of this synchronous endpoint. This page documents the **server-side image upload** check. The **Biometric** service is a Gu1 verification that checks whether a face image corresponds to a person who has **already completed an approved KYC validation** in your organization. You send a single face image and the entity to check (by `entityId`, `entityExternalId`, or `entityTaxId`). The API compares that face against the biometric data stored in **previous approved session-based validations** for that entity. If the face matches one of those approved sessions, the response indicates a match and returns the related KYC validation IDs. > [!NOTE] > > **How it works** > > The service looks up approved KYC sessions (created via [session-based validation](/en/use-cases/kyc/create-validation)) for the given entity. It compares the face you send with the biometric information already stored from those approved sessions. No new hosted session is started—this is a one-off check against existing data. ## Prerequisites For this endpoint to work, your organization must have **session-based KYC validation** set up: 1. **KYC Validation integration enabled**: The integration used for session-based validation (e.g. “Gu1 KYC” / validation by session) must be **enabled** for your organization (e.g. in Marketplace / Integrations). 2. **Credentials configured**: The **API key** (and webhook secret) for that **session validation** integration must be set in your organization’s KYC settings. The Biometric endpoint uses the same credentials as session-based validation to perform the check. If these credentials are not set or the integration is not enabled, the API returns **403** (`NOT_ENABLED` or `NOT_CONFIGURED`). > [!NOTE] > > The Biometric service is a Gu1 service. All verification runs on our infrastructure; no third-party provider names are exposed in responses or errors. ## Request ### Endpoint ``` POST https://api.gu1.ai/api/kyc/biometric ``` ### Content-Type Accepts **`multipart/form-data`** or **`application/json`**. **Multipart** — send the face image in either way (same as Face Match / ID Verification): 1. **As a file part**: field `userImage` or `user_image` (recommended). 2. **As a base64 string**: same field names with a base64-encoded image (with or without `data:image/...;base64,` prefix). If the image is missing (no file and no base64 string), the API returns **400**. **JSON** — send `user_image` or `userImage` as a base64/data URL string, or an http(s) URL to fetch the image server-side. Entity identifiers: `entityId`, `entityExternalId`, and/or `entityTaxId`. You must provide **at least one** of `entityId`, `entityExternalId`, or `entityTaxId` so the API knows which entity to check against. ### Headers ``` Authorization: Bearer YOUR_API_KEY Content-Type: application/json ``` or, for multipart: ``` Authorization: Bearer YOUR_API_KEY Content-Type: multipart/form-data; boundary=----... ``` The organization is determined from your authentication context; you do not need to send `X-Organization-Id`. ### Body Parameters **user\_image** `file | string` *required* Face image. **Multipart:** field `userImage` or `user_image` as a **file part** or **base64 string** (with or without `data:image/...;base64,` prefix). **JSON:** `user_image` or `userImage` as base64, data URL, or http(s) URL. Formats: JPEG, PNG, WebP, TIFF. Max 5MB. **entityId** `string` UUID of the person entity in Gu1. At least one of `entityId`, `entityExternalId`, or `entityTaxId` is required. **entityExternalId** `string` Your own identifier for the entity (external ID). If you do not send `entityId`, the API resolves the entity by organization + `externalId`. At least one entity identifier is required. **externalEntityId** `string` **Deprecated alias** for `entityExternalId`. Still accepted on `POST /api/kyc/biometric` for backward compatibility. Prefer `entityExternalId` in new integrations. **entityTaxId** `string` Tax ID of the entity (CUIT, CPF, RFC, etc.). If you do not send `entityId` or `entityExternalId`, the API resolves the entity by organization + normalized `tax_id` (ignores formatting characters such as dashes and dots). At least one entity identifier is required. ## Response ### Success (200 OK) | Field | Type | Description | | - | - | - | | `match` | boolean | `true` if the face matches at least one **approved** KYC validation for this entity in Gu1. | | `matchedSessionIds` | string\[] | Session IDs of the matched approved validations. | | `matchedKycValidationIds` | string\[] | KYC validation IDs in Gu1 that matched. | | `faceSearch` | object | Summary: `totalMatches`, `requestId` (for support). | **Example:** ```json theme={null} { "match": true, "matchedSessionIds": ["session-abc-123"], "matchedKycValidationIds": ["550e8400-e29b-41d4-a716-446655440000"], "faceSearch": { "totalMatches": 1, "requestId": "req_xyz" } } ``` ## Example Request ```javascript JSON body (entityTaxId) theme={null} const response = await fetch('https://api.gu1.ai/api/kyc/biometric', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ user_image: 'data:image/jpeg;base64,/9j/4AAQ...', entityTaxId: '20-41873887-2', }), }); const result = await response.json(); console.log('Match:', result.match, 'KYC validations:', result.matchedKycValidationIds); ``` ```javascript JSON body theme={null} const response = await fetch('https://api.gu1.ai/api/kyc/biometric', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ user_image: 'data:image/jpeg;base64,/9j/4AAQ...', entityId: '550e8400-e29b-41d4-a716-446655440000', }), }); const result = await response.json(); console.log('Match:', result.match, 'KYC validations:', result.matchedKycValidationIds); ``` ```javascript Multipart (file) theme={null} const form = new FormData(); form.append('userImage', imageFile); form.append('entityId', '550e8400-e29b-41d4-a716-446655440000'); const response = await fetch('https://api.gu1.ai/api/kyc/biometric', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, body: form, }); const result = await response.json(); ``` ```curl cURL (multipart) theme={null} curl -X POST https://api.gu1.ai/api/kyc/biometric \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "userImage=@selfie.jpg" \ -F "entityId=550e8400-e29b-41d4-a716-446655440000" ``` ## Error Responses | Code | HTTP | Meaning | | - | - | - | | `NOT_CONFIGURED` | 403 | Session-based KYC validation credentials are not set in organization KYC settings. | | `NOT_ENABLED` | 403 | Session-based KYC validation integration is not enabled for this organization. | | `INVALID_REQUEST` | 400 | Missing or invalid body (e.g. missing `user_image`, or none of `entityId`, `entityExternalId`, `entityTaxId`). | | `NOT_FOUND` | 404 | No entity found for the given `entityId`, `entityExternalId`, or `entityTaxId` in this organization. | | `UNAUTHORIZED` | 401 | Invalid or missing authentication. | | `VERIFICATION_FAILED` | 500 | Verification could not be completed; retry or contact support. | ## Relation to Session-Based KYC * **Session-based validation** (`POST /api/kyc/validations`): Creates a KYC session, gives the user a hosted URL, and stores the result (including biometric data) when they complete the flow. Those sessions are what the Biometric endpoint checks against. * **Biometric** (`POST /api/kyc/biometric`): Sends one face image and checks if it matches any **already approved** session for that entity. Use it when you need to re-verify the same person (e.g. at login or for a new action) without starting a new session. Both use the same organization credentials for session-based KYC validation. If those credentials are not configured, the Biometric endpoint cannot run. ## Next Steps > [card] [Create KYC Validation](/en/use-cases/kyc/create-validation) > > Start a session-based verification > [card] [Face Match (Document + Selfie)](/en/use-cases/kyc/face-match) > > Compare two images in one call # Cancel KYC Validation Source: https://docs.gu1.ai/en/use-cases/kyc/cancel-validation DELETE /api/kyc/validations/{id}/cancel Cancel a pending, in-progress, or in-review KYC validation — in the Gu1 KYC API for identity verification flows, with examples for cancel validation use cases. ## Overview This endpoint allows you to cancel a KYC validation that is in `pending`, `in_progress`, or `in_review` status. When cancelled: * The validation status changes to `cancelled` * The Gu1 session is terminated (the user can no longer access the verification URL) * The validation is marked as not current (`isCurrent: false`) * You can create a new validation for the same entity afterward * Usage recorded when the session started is not refunded > [!WARNING] > > This action cannot be undone. Usage is consumed when the session starts and is not refunded when cancelled. The user will need to start a new process if identity verification is still required. ## When to Use This * **User requested cancellation**: Customer no longer wants to complete verification * **Incorrect data**: Entity information was entered incorrectly * **Duplicate validation**: Validation was created by mistake * **Process restart needed**: Need to start fresh with new verification session ## Request ### Endpoint ``` DELETE https://api.gu1.ai/api/kyc/validations/{id}/cancel ``` ### Path Parameters **id** `string` *required* The validation ID to cancel ### Headers ```json theme={null} { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } ``` ### Body Parameters **reason** `string` *required* Reason for cancelling the validation (minimum 5 characters) **Type**: `string` (min length: 5) **Example**: `"User requested to cancel the verification process"` ## Response ### Success Response (200 OK) Returns the updated validation object with `cancelled` status: ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "entityId": "123e4567-e89b-12d3-a456-426614174000", "organizationId": "org_abc123", "validationSessionId": "session_xyz789", "status": "cancelled", "provider": "kyc_provider", "providerSessionUrl": "https://verify.example.com/session_xyz789", "isCurrent": false, "metadata": { "cancelledBy": "user_123", "cancelledAt": "2025-01-27T10:30:00Z", "cancellationReason": "User requested to cancel the verification process" }, "createdAt": "2025-01-15T10:30:00Z", "updatedAt": "2025-01-27T10:30:00Z" } ``` ## Example Request ```javascript Node.js theme={null} const validationId = '550e8400-e29b-41d4-a716-446655440000'; const response = await fetch( `https://api.gu1.ai/api/kyc/validations/${validationId}/cancel`, { method: 'DELETE', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ reason: 'User requested to cancel the verification process' }) } ); const cancelled = await response.json(); console.log('Validation cancelled:', cancelled.status); ``` ```python Python theme={null} import requests validation_id = '550e8400-e29b-41d4-a716-446655440000' response = requests.delete( f'https://api.gu1.ai/api/kyc/validations/{validation_id}/cancel', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', }, json={ 'reason': 'User requested to cancel the verification process' } ) cancelled = response.json() print('Validation cancelled:', cancelled['status']) ``` ```curl cURL theme={null} curl -X DELETE https://api.gu1.ai/api/kyc/validations/550e8400-e29b-41d4-a716-446655440000/cancel \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "User requested to cancel the verification process" }' ``` ## Error Responses ### Validation Not Found (404) ```json theme={null} { "error": "NOT_FOUND", "message": "Validation not found" } ``` ### Invalid Status (400) Validation can only be cancelled if status is `pending`, `in_progress`, or `in_review`: ```json theme={null} { "error": "INVALID_STATUS", "message": "Cannot cancel validation with status 'approved'. Only 'pending', 'in_progress', or 'in_review' validations can be cancelled." } ``` ### Invalid Reason (400) Reason must be at least 5 characters: ```json theme={null} { "error": "VALIDATION_ERROR", "message": "Reason must be at least 5 characters" } ``` ## Important Notes > [accordion] The session is closed > > When you cancel a validation, Gu1 closes the session and the verification URL stops working. The execution is consumed when the session starts; cancelling, abandoning, or allowing the validation to expire does not refund that usage. > [accordion] Audit Trail > > The cancellation reason is saved in the validation metadata and audit logs. This helps maintain compliance and track why validations were cancelled. > [accordion] Cannot Cancel Completed Validations > > You cannot cancel validations that are already `approved`, `rejected`, `expired`, `abandoned`, or `cancelled`. Only `pending`, `in_progress`, or `in_review` validations can be cancelled. > [accordion] Create New Validation After Cancellation > > After cancelling, you can create a new KYC validation for the same entity. The previous validation will remain in the history with `cancelled` status. ## Next Steps > [card] [Create KYC Validation](/en/use-cases/kyc/create-validation) > > Start a new verification session > [card] [Check Verification Status](/en/use-cases/kyc/check-status) > > Query validation results # Check Verification Status Source: https://docs.gu1.ai/en/use-cases/kyc/check-status GET /api/kyc/validations/{id} Query KYC validation results and verification details — in the gu1 KYC API for identity verification flows, with examples for check status use cases. ## Overview After a customer completes their KYC verification, you can query the results to check the verification status, extracted data, and decision details. This is useful for: * Checking if verification is complete * Retrieving verified customer information * Getting verification results and risk assessment * Auditing verification history > [!NOTE] > > While you can poll this API, we strongly recommend using [webhooks](/en/use-cases/kyc/webhook-integration) to receive real-time notifications when verification completes. ## Get Validation by ID Retrieve a specific validation using its ID: ### Endpoint ``` GET https://api.gu1.ai/api/kyc/validations/{id} ``` ### Example ```javascript Node.js theme={null} const validationId = '550e8400-e29b-41d4-a716-446655440000'; const response = await fetch( `https://api.gu1.ai/api/kyc/validations/${validationId}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const validation = await response.json(); console.log('Status:', validation.status); console.log('Verified:', validation.status === 'approved'); if (validation.status === 'approved') { console.log('Verified data:', validation.extractedData); console.log('Verified fields:', validation.verifiedFields); } ``` ```python Python theme={null} import requests validation_id = '550e8400-e29b-41d4-a716-446655440000' response = requests.get( f'https://api.gu1.ai/api/kyc/validations/{validation_id}', headers={'Authorization': 'Bearer YOUR_API_KEY'} ) validation = response.json() print('Status:', validation['status']) print('Verified:', validation['status'] == 'approved') if validation['status'] == 'approved': print('Verified data:', validation['extractedData']) print('Verified fields:', validation['verifiedFields']) ``` ## Get Current Validation for Entity If you don't have the validation ID, retrieve the current active validation for a person entity: ### Endpoint ``` GET https://api.gu1.ai/api/kyc/entities/{entityId}/current ``` ### Example ```javascript Node.js theme={null} const entityId = '123e4567-e89b-12d3-a456-426614174000'; const response = await fetch( `https://api.gu1.ai/api/kyc/entities/${entityId}/current`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); if (response.status === 404) { console.log('No active validation for this entity'); } else { const validation = await response.json(); console.log('Current validation:', validation.status); } ``` ```python Python theme={null} import requests entity_id = '123e4567-e89b-12d3-a456-426614174000' response = requests.get( f'https://api.gu1.ai/api/kyc/entities/{entity_id}/current', headers={'Authorization': 'Bearer YOUR_API_KEY'} ) if response.status_code == 404: print('No active validation for this entity') else: validation = response.json() print('Current validation:', validation['status']) ``` ## Get Entity KYC Status Get a summary of an entity's KYC verification status: ### Endpoint ``` GET https://api.gu1.ai/api/kyc/entities/{entityId}/status ``` ### Response ```json theme={null} { "entityId": "123e4567-e89b-12d3-a456-426614174000", "hasKyc": true, "isVerified": true, "currentValidation": { "id": "550e8400-e29b-41d4-a716-446655440000", "status": "approved", "verifiedAt": "2025-01-15T11:00:00Z" }, "lastVerifiedAt": "2025-01-15T11:00:00Z", "expiresAt": "2026-01-15T11:00:00Z", "needsReverification": false } ``` ### Example ```javascript Node.js theme={null} const entityId = '123e4567-e89b-12d3-a456-426614174000'; const response = await fetch( `https://api.gu1.ai/api/kyc/entities/${entityId}/status`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const status = await response.json(); if (status.isVerified) { console.log('✅ Customer is verified'); console.log('Verified on:', status.lastVerifiedAt); if (status.needsReverification) { console.log('⚠️ Needs reverification'); } } else { console.log('❌ Customer not verified'); } ``` ```python Python theme={null} import requests entity_id = '123e4567-e89b-12d3-a456-426614174000' response = requests.get( f'https://api.gu1.ai/api/kyc/entities/{entity_id}/status', headers={'Authorization': 'Bearer YOUR_API_KEY'} ) status = response.json() if status['isVerified']: print('✅ Customer is verified') print('Verified on:', status['lastVerifiedAt']) if status['needsReverification']: print('⚠️ Needs reverification') else: print('❌ Customer not verified') ``` ## Understanding Validation Results ### Status Values **status** `string` Current validation status: * **`pending`** - Validation created, waiting for customer to start * **`in_progress`** - Customer is actively completing verification (filling out form) * **`in_review`** - Verification completed, requires manual review from compliance team * **`approved`** - Verification successful, identity confirmed * **`rejected`** - Verification failed, identity not confirmed * **`expired`** - Verification session expired (typically after 7 days) * **`abandoned`** - Customer started but didn't complete verification * **`cancelled`** - Validation manually cancelled ### Decision object (`decision`) When status is `approved` or `rejected`, the `decision` field contains detailed provider results. When a validation reaches a terminal or in-review state with provider results, `decision` contains the full verification outcome from the KYC flow. Gu1 **always stores and returns both shapes** for each feature: a singular object (legacy) **and** a one-element array (current). You can read either `id_verification` or `id_verifications[0]`; they are kept in sync. The same applies to `liveness` / `liveness_checks`, `face_match` / `face_matches`, `aml_screening` / `aml_screenings`, and `ip_analysis` / `ip_analyses`. Media fields (`front_image`, `reference_image`, `images.*`, etc.) are **Gu1 storage keys** (`kyc/...`). Fetch them via the [validation media API](/en/use-cases/kyc/validation-media). If the copy has not finished, the field is `null` until a later sync. **Approved example (complete):** ```json theme={null} { "status": "Approved", "workflow_type": "standard", "session_id": "7c0fa22d-0cfa-4a78-8090-7c842397e788", "session_number": 921, "features": ["ID_VERIFICATION", "LIVENESS", "FACE_MATCH", "IP_ANALYSIS"], "images": { "documentFront": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "documentBack": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-back.jpg", "selfie": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg" }, "id_verification": { "status": "Approved", "node_id": "feature_ocr", "document_type": "Passport", "document_number": "AB123456", "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "date_of_birth": "1990-05-20", "nationality": "US", "gender": "M", "age": 35, "issuing_state": "US", "expiration_date": "2030-05-20", "date_of_issue": "2020-05-20", "front_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "back_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-back.jpg", "portrait_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [], "matches": [] }, "id_verifications": [ { "status": "Approved", "node_id": "feature_ocr", "document_type": "Passport", "document_number": "AB123456", "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "date_of_birth": "1990-05-20", "nationality": "US", "gender": "M", "age": 35, "issuing_state": "US", "expiration_date": "2030-05-20", "date_of_issue": "2020-05-20", "front_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "back_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-back.jpg", "portrait_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [], "matches": [] } ], "liveness": { "status": "Approved", "node_id": "feature_liveness", "score": 98, "method": "PASSIVE", "reference_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-reference.jpg", "video_url": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-video.webm", "face_quality": 92.5, "warnings": [], "matches": [] }, "liveness_checks": [ { "status": "Approved", "node_id": "feature_liveness", "score": 98, "method": "PASSIVE", "reference_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-reference.jpg", "video_url": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-video.webm", "face_quality": 92.5, "warnings": [], "matches": [] } ], "face_match": { "status": "Approved", "node_id": "feature_face_match", "score": 95, "source_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "target_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [] }, "face_matches": [ { "status": "Approved", "node_id": "feature_face_match", "score": 95, "source_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "target_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [] } ], "aml_screening": { "status": "Approved", "node_id": "feature_aml", "warnings": [] }, "aml_screenings": [ { "status": "Approved", "node_id": "feature_aml", "warnings": [] } ], "ip_analysis": { "status": "Approved", "node_id": "feature_ip_analysis", "ip_address": "203.0.113.10", "country": "US", "region": "New York", "city": "New York", "is_vpn": false, "is_proxy": false, "warnings": [] }, "ip_analyses": [ { "status": "Approved", "node_id": "feature_ip_analysis", "ip_address": "203.0.113.10", "country": "US", "region": "New York", "city": "New York", "is_vpn": false, "is_proxy": false, "warnings": [] } ] } ``` **Rejected example (complete):** ```json theme={null} { "status": "Declined", "workflow_type": "standard", "session_id": "7c0fa22d-0cfa-4a78-8090-7c842397e788", "session_number": 921, "features": ["ID_VERIFICATION", "LIVENESS", "FACE_MATCH"], "images": { "documentFront": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "selfie": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg" }, "id_verification": { "status": "Declined", "node_id": "feature_ocr", "document_type": "Passport", "document_number": "AB123456", "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "front_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "portrait_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [ { "risk": "DOCUMENT_AUTHENTICITY_FAILED", "feature": "ID_VERIFICATION", "short_description": "Document authenticity could not be verified", "long_description": "The document failed authenticity checks.", "log_type": "error" } ], "matches": [] }, "id_verifications": [ { "status": "Declined", "node_id": "feature_ocr", "document_type": "Passport", "document_number": "AB123456", "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "front_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "portrait_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [ { "risk": "DOCUMENT_AUTHENTICITY_FAILED", "feature": "ID_VERIFICATION", "short_description": "Document authenticity could not be verified", "long_description": "The document failed authenticity checks.", "log_type": "error" } ], "matches": [] } ], "liveness": { "status": "Declined", "node_id": "feature_liveness", "score": 42, "method": "PASSIVE", "reference_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-reference.jpg", "warnings": [ { "risk": "LIVENESS_FAILED", "feature": "LIVENESS", "short_description": "Liveness detection failed", "long_description": "The liveness check did not pass the required threshold.", "log_type": "error" } ], "matches": [] }, "liveness_checks": [ { "status": "Declined", "node_id": "feature_liveness", "score": 42, "method": "PASSIVE", "reference_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-reference.jpg", "warnings": [ { "risk": "LIVENESS_FAILED", "feature": "LIVENESS", "short_description": "Liveness detection failed", "long_description": "The liveness check did not pass the required threshold.", "log_type": "error" } ], "matches": [] } ], "face_match": { "status": "Declined", "node_id": "feature_face_match", "score": 38, "source_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "target_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [ { "risk": "FACE_MATCH_LOW_CONFIDENCE", "feature": "FACE_MATCH", "short_description": "Face match confidence below threshold", "long_description": "The selfie did not match the document portrait with sufficient confidence.", "log_type": "error" } ] }, "face_matches": [ { "status": "Declined", "node_id": "feature_face_match", "score": 38, "source_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg", "target_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg", "warnings": [ { "risk": "FACE_MATCH_LOW_CONFIDENCE", "feature": "FACE_MATCH", "short_description": "Face match confidence below threshold", "long_description": "The selfie did not match the document portrait with sufficient confidence.", "log_type": "error" } ] } ] } ``` ### Verification results Each feature block in `decision` includes a **`status`** (`Approved`, `Declined`, `In Review`, etc.), optional **`score`**, **`warnings`**, and media references: | Feature key | Array alias | Typical fields | | - | - | - | | `id_verification` | `id_verifications[0]` | `document_type`, `document_number`, `front_image`, `back_image`, `portrait_image`, `warnings`, `matches` | | `liveness` | `liveness_checks[0]` | `score`, `method`, `reference_image`, `video_url`, `warnings`, `matches` | | `face_match` | `face_matches[0]` | `score`, `source_image`, `target_image`, `warnings` | | `aml_screening` | `aml_screenings[0]` | `status`, `warnings` | | `ip_analysis` | `ip_analyses[0]` | `ip_address`, `country`, `is_vpn`, `warnings` | Gu1 also exposes normalized fields in **`extractedData`**, **`verifiedFields`**, and top-level **`warnings`** (risk codes) for easier integration. ### Extracted Data Use `extractedData` to update customer records with verified information: ```javascript theme={null} const validation = await getValidation(validationId); if (validation.status === 'approved' && validation.extractedData) { // Update customer record with verified data await updateCustomer(customerId, { firstName: validation.extractedData.firstName, lastName: validation.extractedData.lastName, dateOfBirth: validation.extractedData.dateOfBirth, nationality: validation.extractedData.nationality, documentType: validation.extractedData.documentType, documentNumber: validation.extractedData.documentNumber, isVerified: true, verifiedAt: validation.verifiedAt }); } ``` ## List All Validations for Entity Get the complete verification history for an entity: ### Endpoint ``` GET https://api.gu1.ai/api/kyc/entities/{entityId}/validations ``` ### Response ```json theme={null} { "validations": [ { "id": "validation_1", "status": "approved", "isCurrent": true, "createdAt": "2025-01-15T10:30:00Z", "verifiedAt": "2025-01-15T11:00:00Z" }, { "id": "validation_2", "status": "abandoned", "isCurrent": false, "createdAt": "2025-01-10T09:00:00Z" } ], "total": 2, "page": 1, "limit": 100 } ``` ## Sync Validation Status If you suspect the validation status is out of sync with the identity provider, trigger a manual sync: ### Endpoint ``` POST https://api.gu1.ai/api/kyc/validations/{id}/sync ``` ### Example ```javascript Node.js theme={null} const validationId = '550e8400-e29b-41d4-a716-446655440000'; const response = await fetch( `https://api.gu1.ai/api/kyc/validations/${validationId}/sync`, { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ force: true }) } ); const updatedValidation = await response.json(); console.log('Updated status:', updatedValidation.status); ``` ```python Python theme={null} import requests validation_id = '550e8400-e29b-41d4-a716-446655440000' response = requests.post( f'https://api.gu1.ai/api/kyc/validations/{validation_id}/sync', headers={ 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, json={'force': True} ) updated_validation = response.json() print('Updated status:', updated_validation['status']) ``` ## Common Integration Patterns ### Pattern 1: Check Before Allowing Action ```javascript theme={null} async function requireVerification(entityId) { const status = await fetch( `https://api.gu1.ai/api/kyc/entities/${entityId}/status`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ).then(r => r.json()); if (!status.isVerified) { throw new Error('Customer must complete identity verification'); } if (status.needsReverification) { throw new Error('Customer identity verification expired. Please reverify.'); } return true; } ``` ### Pattern 2: Conditional Features Based on Verification ```javascript theme={null} async function getCustomerFeatures(entityId) { const status = await getKycStatus(entityId); return { basicFeatures: true, advancedFeatures: status.isVerified, highLimitTransactions: status.isVerified && !status.needsReverification, internationalTransfers: status.isVerified && hasAmlClearance(status) }; } ``` ### Pattern 3: Periodic Re-verification Check ```javascript theme={null} async function checkReverificationNeeded() { const stats = await fetch( 'https://api.gu1.ai/api/kyc/stats', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ).then(r => r.json()); // Find entities needing reverification const validations = await fetch( 'https://api.gu1.ai/api/kyc/validations?status=approved', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ).then(r => r.json()); for (const validation of validations.validations) { const status = await getEntityKycStatus(validation.entityId); if (status.needsReverification) { await notifyCustomerReverification(validation.entityId); } } } // Run daily setInterval(checkReverificationNeeded, 24 * 60 * 60 * 1000); ``` ## Best Practices > [accordion] Use Webhooks, Not Polling > > Instead of repeatedly checking validation status, use [webhooks](/en/use-cases/kyc/webhook-integration) to receive real-time notifications. This is more efficient and provides better user experience. > [accordion] Cache Verification Status > > Store the verification status in your database and update it via webhooks. Don't query the API on every request. > > ```javascript theme={null} > // Good: Cache in your database > const customer = await db.getCustomer(customerId); > if (customer.isVerified) { > // Allow action > } > > // Bad: Query API every time > const status = await api.getKycStatus(entityId); > if (status.isVerified) { > // Allow action > } > ``` > [accordion] Handle Expired Verifications > > Verifications may expire after a certain period (typically 1 year). Check `needsReverification` and prompt customers to reverify when necessary. > [accordion] Store Validation IDs > > Always store the validation ID in your database linked to the customer. This allows you to audit verification history and retrieve detailed results later. ## Next Steps > [card] [Create KYC Validation](/en/use-cases/kyc/create-validation) > > Start a new verification session > [card] [Webhook Integration](/en/use-cases/kyc/webhook-integration) > > Get real-time notifications # Client-Side Integration Guide Source: https://docs.gu1.ai/en/use-cases/kyc/client-integration Complete guide for integrating KYC verification in mobile apps and web applications — in the gu1 KYC API for identity verification flows. ## Overview This guide shows you how to integrate Gu1's KYC verification flow into your mobile apps (Android, iOS, React Native, Flutter) and web applications (React, Vue, vanilla JS). The verification runs in a WebView/iframe pointing to a secure URL generated by your backend. > [!NOTE] > > This guide assumes you've already set up your backend integration with Gu1's API. If not, start with the [KYC API Overview](/en/use-cases/kyc/overview). ## Architecture Overview ```mermaid theme={null} sequenceDiagram participant User participant YourApp as Your Frontend
(Mobile/Web) participant YourBackend as Your Backend participant Gu1API as Gu1 API participant Gu1UI as Gu1 Verification UI User->>YourApp: Start KYC verification YourApp->>YourBackend: Request verification URL YourBackend->>Gu1API: POST /kyc/validations
(with entity data) Gu1API-->>YourBackend: Returns validation_url YourBackend-->>YourApp: Returns secure URL YourApp->>Gu1UI: Open WebView/iframe with URL User->>Gu1UI: Complete verification
(document + selfie) Gu1UI-->>User: Show completion message Gu1API->>YourBackend: Send webhook (approved/rejected) YourBackend->>YourBackend: Update user status YourApp->>YourBackend: Poll for status updates YourBackend-->>YourApp: Return verification result YourApp->>User: Show final result ``` **Key Points:** * 🔒 Your **backend** generates the verification URL (never expose API keys in client) * 📱 Your **frontend** opens the URL in WebView/iframe * 🔔 Gu1 sends **webhooks** to your backend when verification completes * 🔄 Your **frontend** polls your backend to detect completion *** ## Security Best Practices > [!WARNING] > > **CRITICAL**: Never expose Gu1 API credentials or workflow IDs in your client-side code. Always generate verification URLs from your secure backend. ### ✅ DO > [accordion] Generate URLs on-demand from your backend > > ```javascript theme={null} > // ✅ CORRECT: Frontend requests URL from YOUR backend > const response = await fetch('https://yourapi.com/kyc/start', { > method: 'POST', > headers: { > 'Authorization': `Bearer ${userToken}`, // Your auth > 'Content-Type': 'application/json' > }, > body: JSON.stringify({ > userId: '123' > }) > }); > > const { verificationUrl } = await response.json(); > // Open verificationUrl in WebView/iframe > ``` > [accordion] Implement short TTL for URLs > > Generate verification URLs that expire quickly (15-30 minutes). If user doesn't start within that time, generate a new one. > > ```javascript theme={null} > // In your backend > const validation = await gu1.createValidation({ > // ... entity data > }); > > // Store with expiration > await redis.setex( > `kyc:${userId}`, > 1800, // 30 minutes TTL > validation.validation_url > ); > ``` > [accordion] Use Process-and-Purge pattern > > When receiving webhooks from Gu1: > > 1. Extract only necessary data > 2. Update user status in your DB > 3. Don't store sensitive verification data long-term > > ```javascript theme={null} > // In your webhook handler > app.post('/webhooks/kyc', async (req, res) => { > const { event, payload } = req.body; > > if (event === 'kyc.validation_approved') { > // Extract only what you need > await db.users.update({ > where: { externalId: payload.entity.externalId }, > data: { > kycStatus: 'approved', > kycVerifiedAt: new Date(), > // Don't store extractedData unless required > } > }); > } > > res.status(200).send('OK'); > }); > ``` > [accordion] Validate webhook signatures > > Always verify webhooks are from Gu1 using HMAC signatures. > > [Learn about webhook security →](/en/webhooks/security) ### ❌ DON'T > [accordion] Never hardcode API keys or workflow IDs > > ```javascript theme={null} > // ❌ WRONG: Exposing credentials in client code > const response = await fetch('https://api.gu1.ai/kyc/validations', { > headers: { > 'x-api-key': 'gsk_live_abc123...', // NEVER DO THIS > 'x-workflow-id': 'workflow-id' // NEVER DO THIS > } > }); > ``` > > **Why it's dangerous:** > > * API keys exposed in app bundles can be extracted > * Anyone can create validations on your behalf > * Impossible to rotate compromised keys without app updates > [accordion] Don't reuse verification URLs > > ```javascript theme={null} > // ❌ WRONG: Storing URL permanently > localStorage.setItem('kycUrl', verificationUrl); > > // Later... > window.open(localStorage.getItem('kycUrl')); // URL might be expired > ``` > > **Instead:** Always request a fresh URL from your backend when needed. > [accordion] Don't rely on client-side validation > > ```javascript theme={null} > // ❌ WRONG: Trusting client to report completion > function onVerificationComplete() { > // User could fake this > updateUserStatus('approved'); > } > ``` > > **Instead:** Only trust webhooks received by your backend. *** ## Mobile Integration ### Android (Kotlin) > [tab] Standard Android > > ```kotlin theme={null} > import android.webkit.WebView > import android.webkit.WebViewClient > import androidx.appcompat.app.AppCompatActivity > > class KYCActivity : AppCompatActivity() { > private lateinit var webView: WebView > > override fun onCreate(savedInstanceState: Bundle?) { > super.onCreate(savedInstanceState) > > webView = WebView(this).apply { > settings.apply { > javaScriptEnabled = true > domStorageEnabled = true > mediaPlaybackRequiresUserGesture = false // For camera access > } > > webViewClient = object : WebViewClient() { > override fun onPageFinished(view: WebView?, url: String?) { > // Page loaded > } > } > } > > setContentView(webView) > > // Request verification URL from YOUR backend > loadVerificationUrl() > } > > private fun loadVerificationUrl() { > lifecycleScope.launch { > try { > val url = apiClient.requestKYCUrl(userId) > webView.loadUrl(url) > > // Start polling for completion > startStatusPolling() > } catch (e: Exception) { > // Handle error > showError("Failed to load verification") > } > } > } > > private fun startStatusPolling() { > lifecycleScope.launch { > while (true) { > delay(3000) // Poll every 3 seconds > > val status = apiClient.getKYCStatus(userId) > when (status) { > "approved" -> { > showSuccess() > finish() > return@launch > } > "rejected" -> { > showRejected() > finish() > return@launch > } > "pending", "in_progress" -> { > // Continue polling > } > } > } > } > } > > override fun onDestroy() { > webView.destroy() > super.onDestroy() > } > } > ``` > [tab] Jetpack Compose > > ```kotlin theme={null} > import androidx.compose.runtime.* > import androidx.compose.ui.viewinterop.AndroidView > import android.webkit.WebView > > @Composable > fun KYCVerificationScreen( > userId: String, > onComplete: (status: String) -> Unit > ) { > var verificationUrl by remember { mutableStateOf(null) } > var isLoading by remember { mutableStateOf(true) } > > // Load verification URL > LaunchedEffect(userId) { > try { > val url = apiClient.requestKYCUrl(userId) > verificationUrl = url > isLoading = false > } catch (e: Exception) { > // Handle error > } > } > > // Poll for status > LaunchedEffect(userId) { > while (true) { > delay(3000) // Poll every 3 seconds > > val status = apiClient.getKYCStatus(userId) > when (status) { > "approved", "rejected" -> { > onComplete(status) > return@LaunchedEffect > } > } > } > } > > if (isLoading) { > CircularProgressIndicator() > } else { > verificationUrl?.let { url -> > AndroidView( > factory = { context -> > WebView(context).apply { > settings.apply { > javaScriptEnabled = true > domStorageEnabled = true > mediaPlaybackRequiresUserGesture = false > } > loadUrl(url) > } > } > ) > } > } > } > ``` **Permissions (AndroidManifest.xml):** ```xml theme={null} ``` *** ### iOS (Swift) > [tab] UIKit > > ```swift theme={null} > import UIKit > import WebKit > > class KYCViewController: UIViewController { > private var webView: WKWebView! > private let userId: String > private var pollingTimer: Timer? > > init(userId: String) { > self.userId = userId > super.init(nibName: nil, bundle: nil) > } > > required init?(coder: NSCoder) { > fatalError("init(coder:) has not been implemented") > } > > override func viewDidLoad() { > super.viewDidLoad() > > // Configure WebView > let configuration = WKWebViewConfiguration() > configuration.allowsInlineMediaPlayback = true > configuration.mediaTypesRequiringUserActionForPlayback = [] > > webView = WKWebView(frame: view.bounds, configuration: configuration) > webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] > view.addSubview(webView) > > // Load verification URL > loadVerificationURL() > } > > private func loadVerificationURL() { > Task { > do { > let urlString = try await apiClient.requestKYCURL(userId: userId) > guard let url = URL(string: urlString) else { return } > > let request = URLRequest(url: url) > webView.load(request) > > // Start polling > startStatusPolling() > } catch { > showError("Failed to load verification") > } > } > } > > private func startStatusPolling() { > pollingTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { [weak self] _ in > guard let self = self else { return } > > Task { > do { > let status = try await self.apiClient.getKYCStatus(userId: self.userId) > > switch status { > case "approved": > self.handleApproved() > case "rejected": > self.handleRejected() > default: > break // Continue polling > } > } catch { > // Handle error > } > } > } > } > > private func handleApproved() { > pollingTimer?.invalidate() > // Show success and dismiss > dismiss(animated: true) > } > > private func handleRejected() { > pollingTimer?.invalidate() > // Show rejection message > } > > deinit { > pollingTimer?.invalidate() > } > } > ``` > [tab] SwiftUI > > ```swift theme={null} > import SwiftUI > import WebKit > > struct KYCVerificationView: View { > let userId: String > @State private var verificationURL: URL? > @State private var isLoading = true > @State private var status: String = "pending" > @Environment(\.dismiss) var dismiss > > var body: some View { > ZStack { > if isLoading { > ProgressView("Loading verification...") > } else if let url = verificationURL { > WebView(url: url) > } > } > .onAppear { > loadVerificationURL() > startStatusPolling() > } > } > > private func loadVerificationURL() { > Task { > do { > let urlString = try await apiClient.requestKYCURL(userId: userId) > verificationURL = URL(string: urlString) > isLoading = false > } catch { > // Handle error > } > } > } > > private func startStatusPolling() { > Task { > while status == "pending" || status == "in_progress" { > try? await Task.sleep(nanoseconds: 3_000_000_000) // 3 seconds > > do { > status = try await apiClient.getKYCStatus(userId: userId) > > if status == "approved" || status == "rejected" { > dismiss() > return > } > } catch { > // Handle error > } > } > } > } > } > > struct WebView: UIViewRepresentable { > let url: URL > > func makeUIView(context: Context) -> WKWebView { > let configuration = WKWebViewConfiguration() > configuration.allowsInlineMediaPlayback = true > configuration.mediaTypesRequiringUserActionForPlayback = [] > > return WKWebView(frame: .zero, configuration: configuration) > } > > func updateUIView(_ webView: WKWebView, context: Context) { > let request = URLRequest(url: url) > webView.load(request) > } > } > ``` **Permissions (Info.plist):** ```xml theme={null} NSCameraUsageDescription We need camera access for identity verification NSPhotoLibraryUsageDescription We need photo library access for document upload ``` *** ### Kotlin Multiplatform (KMP) Perfect for sharing logic between Android and iOS: > [tab] Common Code > > ```kotlin theme={null} > // commonMain/KYCManager.kt > expect class KYCManager { > fun openVerification(url: String) > fun startStatusPolling(userId: String, onComplete: (String) -> Unit) > } > > // Shared business logic > class KYCCoordinator( > private val apiClient: ApiClient, > private val kycManager: KYCManager > ) { > suspend fun startVerification(userId: String) { > try { > val url = apiClient.requestKYCUrl(userId) > kycManager.openVerification(url) > > kycManager.startStatusPolling(userId) { status -> > when (status) { > "approved" -> handleApproved() > "rejected" -> handleRejected() > } > } > } catch (e: Exception) { > // Handle error > } > } > > private fun handleApproved() { > // Shared approval logic > } > > private fun handleRejected() { > // Shared rejection logic > } > } > ``` > [tab] Android Implementation > > ```kotlin theme={null} > // androidMain/KYCManager.kt > actual class KYCManager(private val activity: Activity) { > actual fun openVerification(url: String) { > val intent = Intent(activity, KYCWebViewActivity::class.java).apply { > putExtra("url", url) > } > activity.startActivity(intent) > } > > actual fun startStatusPolling(userId: String, onComplete: (String) -> Unit) { > // Use coroutines for polling > CoroutineScope(Dispatchers.Main).launch { > while (true) { > delay(3000) > val status = apiClient.getKYCStatus(userId) > if (status in listOf("approved", "rejected")) { > onComplete(status) > break > } > } > } > } > } > ``` > [tab] iOS Implementation > > ```swift theme={null} > // iosMain/KYCManager.kt > actual class KYCManager { > actual fun openVerification(url: String) { > let vc = KYCViewController(urlString: url) > // Present view controller > UIApplication.shared.windows.first?.rootViewController? > .present(vc, animated: true) > } > > actual fun startStatusPolling(userId: String, onComplete: (String) -> Unit) { > Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { timer in > Task { > let status = try await apiClient.getKYCStatus(userId: userId) > if status == "approved" || status == "rejected" { > onComplete(status) > timer.invalidate() > } > } > } > } > } > ``` *** ### React Native ```typescript theme={null} import React, { useEffect, useState } from 'react'; import { View, ActivityIndicator, StyleSheet } from 'react-native'; import { WebView } from 'react-native-webview'; interface KYCVerificationProps { userId: string; onComplete: (status: string) => void; } export const KYCVerification: React.FC = ({ userId, onComplete }) => { const [verificationUrl, setVerificationUrl] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { loadVerificationUrl(); const pollInterval = startStatusPolling(); return () => clearInterval(pollInterval); }, [userId]); const loadVerificationUrl = async () => { try { const response = await fetch(`https://yourapi.com/kyc/start`, { method: 'POST', headers: { 'Authorization': `Bearer ${userToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ userId }) }); const { verificationUrl } = await response.json(); setVerificationUrl(verificationUrl); setIsLoading(false); } catch (error) { console.error('Failed to load KYC URL:', error); setIsLoading(false); } }; const startStatusPolling = () => { return setInterval(async () => { try { const response = await fetch(`https://yourapi.com/kyc/status/${userId}`, { headers: { 'Authorization': `Bearer ${userToken}` } }); const { status } = await response.json(); if (status === 'approved' || status === 'rejected') { onComplete(status); } } catch (error) { console.error('Polling error:', error); } }, 3000); // Poll every 3 seconds }; if (isLoading) { return ( ); } if (!verificationUrl) { return ( Failed to load verification ); } return ( ); }; const styles = StyleSheet.create({ webview: { flex: 1 }, loading: { flex: 1, justifyContent: 'center', alignItems: 'center' }, error: { flex: 1, justifyContent: 'center', alignItems: 'center' } }); ``` **Permissions:** * Add camera permissions to `AndroidManifest.xml` and `Info.plist` * Install: `npm install react-native-webview` *** ### Flutter ```dart theme={null} import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'dart:async'; class KYCVerificationScreen extends StatefulWidget { final String userId; final Function(String) onComplete; const KYCVerificationScreen({ Key? key, required this.userId, required this.onComplete, }) : super(key: key); @override _KYCVerificationScreenState createState() => _KYCVerificationScreenState(); } class _KYCVerificationScreenState extends State { String? verificationUrl; bool isLoading = true; Timer? pollingTimer; late WebViewController controller; @override void initState() { super.initState(); _loadVerificationUrl(); _startStatusPolling(); } @override void dispose() { pollingTimer?.cancel(); super.dispose(); } Future _loadVerificationUrl() async { try { final response = await http.post( Uri.parse('https://yourapi.com/kyc/start'), headers: { 'Authorization': 'Bearer $userToken', 'Content-Type': 'application/json', }, body: jsonEncode({'userId': widget.userId}), ); if (response.statusCode == 200) { final data = jsonDecode(response.body); setState(() { verificationUrl = data['verificationUrl']; isLoading = false; }); // Initialize WebView controller controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(const Color(0x00000000)) ..loadRequest(Uri.parse(verificationUrl!)); } } catch (e) { print('Error loading KYC URL: $e'); setState(() => isLoading = false); } } void _startStatusPolling() { pollingTimer = Timer.periodic(Duration(seconds: 3), (timer) async { try { final response = await http.get( Uri.parse('https://yourapi.com/kyc/status/${widget.userId}'), headers: {'Authorization': 'Bearer $userToken'}, ); if (response.statusCode == 200) { final data = jsonDecode(response.body); final status = data['status']; if (status == 'approved' || status == 'rejected') { timer.cancel(); widget.onComplete(status); } } } catch (e) { print('Polling error: $e'); } }); } @override Widget build(BuildContext context) { if (isLoading) { return Scaffold( body: Center( child: CircularProgressIndicator(), ), ); } if (verificationUrl == null) { return Scaffold( body: Center( child: Text('Failed to load verification'), ), ); } return Scaffold( appBar: AppBar( title: Text('Identity Verification'), ), body: WebViewWidget(controller: controller), ); } } ``` **Dependencies (pubspec.yaml):** ```yaml theme={null} dependencies: webview_flutter: ^4.4.0 http: ^1.1.0 ``` **Permissions:** * Android: Add camera permission to `AndroidManifest.xml` * iOS: Add camera usage description to `Info.plist` *** ## Web Integration ### React ```typescript theme={null} import React, { useEffect, useState, useRef } from 'react'; interface KYCVerificationProps { userId: string; onComplete: (status: string) => void; } export const KYCVerification: React.FC = ({ userId, onComplete }) => { const [verificationUrl, setVerificationUrl] = useState(null); const [isLoading, setIsLoading] = useState(true); const iframeRef = useRef(null); const pollingInterval = useRef(null); useEffect(() => { loadVerificationUrl(); startStatusPolling(); return () => { if (pollingInterval.current) { clearInterval(pollingInterval.current); } }; }, [userId]); const loadVerificationUrl = async () => { try { const response = await fetch('/api/kyc/start', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getAuthToken()}` }, body: JSON.stringify({ userId }) }); const { verificationUrl } = await response.json(); setVerificationUrl(verificationUrl); setIsLoading(false); } catch (error) { console.error('Failed to load KYC URL:', error); setIsLoading(false); } }; const startStatusPolling = () => { pollingInterval.current = setInterval(async () => { try { const response = await fetch(`/api/kyc/status/${userId}`, { headers: { 'Authorization': `Bearer ${getAuthToken()}` } }); const { status } = await response.json(); if (status === 'approved' || status === 'rejected') { if (pollingInterval.current) { clearInterval(pollingInterval.current); } onComplete(status); } } catch (error) { console.error('Polling error:', error); } }, 3000); // Poll every 3 seconds }; if (isLoading) { return (
); } if (!verificationUrl) { return (

Failed to load verification

); } return (
``` *** ### Plain HTML/JavaScript (Vanilla) ```html theme={null} KYC Verification

Loading verification...

Failed to load verification. Please try again.

``` *** ## Detecting Flow Completion > [!WARNING] > > The WebView/iframe **cannot** directly notify your app when verification completes. The Gu1 verification UI runs in isolation for security reasons. ### Recommended Pattern: Backend Polling Your frontend polls your backend, which receives webhooks from Gu1: ```mermaid theme={null} sequenceDiagram participant User participant Frontend participant YourBackend participant Gu1 User->>Gu1: Complete verification Gu1->>YourBackend: Webhook (approved/rejected) YourBackend->>YourBackend: Update user status in DB loop Every 3 seconds Frontend->>YourBackend: Poll: GET /kyc/status/:userId YourBackend-->>Frontend: Return current status end Frontend->>Frontend: Detect status change Frontend->>User: Show result ``` **Backend endpoint example:** ```javascript theme={null} // Node.js/Express example app.get('/api/kyc/status/:userId', authenticate, async (req, res) => { const { userId } = req.params; const user = await db.users.findOne({ id: userId }); res.json({ status: user.kycStatus, // 'pending', 'in_progress', 'approved', 'rejected' verifiedAt: user.kycVerifiedAt, lastUpdated: user.kycLastUpdated }); }); ``` **Frontend polling (all platforms):** > [tab] JavaScript > > ```javascript theme={null} > async function pollStatus(userId) { > const interval = setInterval(async () => { > const response = await fetch(`/api/kyc/status/${userId}`); > const { status } = await response.json(); > > if (status === 'approved' || status === 'rejected') { > clearInterval(interval); > handleComplete(status); > } > }, 3000); // 3 seconds > } > ``` > [tab] Kotlin > > ```kotlin theme={null} > fun pollStatus(userId: String) { > lifecycleScope.launch { > while (true) { > delay(3000) > val status = apiClient.getKYCStatus(userId) > if (status in listOf("approved", "rejected")) { > handleComplete(status) > break > } > } > } > } > ``` > [tab] Swift > > ```swift theme={null} > func pollStatus(userId: String) { > Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { timer in > Task { > let status = try await apiClient.getKYCStatus(userId: userId) > if status == "approved" || status == "rejected" { > timer.invalidate() > handleComplete(status) > } > } > } > } > ``` ### Alternative: WebSockets (Advanced) For better UX, use WebSockets to push updates instead of polling: ```javascript theme={null} // Backend (Socket.IO example) io.on('connection', (socket) => { socket.on('subscribe-kyc', (userId) => { socket.join(`kyc:${userId}`); }); }); // When webhook arrives app.post('/webhooks/kyc', async (req, res) => { const { event, payload } = req.body; // Update database await updateUserStatus(payload); // Notify connected clients io.to(`kyc:${payload.entity.externalId}`).emit('kyc-update', { status: payload.status }); res.status(200).send('OK'); }); // Frontend const socket = io(); socket.emit('subscribe-kyc', userId); socket.on('kyc-update', ({ status }) => { handleComplete(status); }); ``` *** ## Webhook Handling Your backend receives webhooks from Gu1 when verification completes. > [card] [Webhook Integration Guide](/en/webhooks/events/kyc-events) > > See complete webhook integration guide with code examples, security, and payload structures ### Key Webhook Events | Event | When Fired | Action | | - | - | - | | `kyc.validation_approved` | User verified successfully | Update user status to `verified`, enable features | | `kyc.validation_rejected` | Verification failed | Update status to `rejected`, optionally allow retry | | `kyc.validation_abandoned` | User left without completing | Mark as `incomplete`, send reminder email | | `kyc.validation_expired` | Session expired | Allow user to request new URL | **Minimal webhook handler:** ```javascript theme={null} app.post('/webhooks/gu1/kyc', async (req, res) => { // Verify signature (see webhook guide) const { event, payload } = req.body; const userId = payload.entity.externalId; switch (event) { case 'kyc.validation_approved': await db.users.update({ where: { id: userId }, data: { kycStatus: 'approved', kycVerifiedAt: new Date(), isVerified: true } }); break; case 'kyc.validation_rejected': await db.users.update({ where: { id: userId }, data: { kycStatus: 'rejected', isVerified: false } }); break; } res.status(200).send('OK'); }); ``` *** ## Complete Flow Example Let's see a complete end-to-end example: ### 1. Backend: Generate URL ```javascript theme={null} // POST /api/kyc/start app.post('/api/kyc/start', authenticate, async (req, res) => { const { userId } = req.body; const user = await db.users.findOne({ id: userId }); // Ensure person entity exists in Gu1 (create or get existing by externalId/taxId) let entityId = user.gu1EntityId; if (!entityId) { const entityRes = await gu1.post('/entities', { type: 'person', externalId: user.id, name: user.name, taxId: user.taxId, countryCode: user.countryCode || 'US' }); entityId = entityRes.entity?.id ?? entityRes.id; await db.users.update({ where: { id: userId }, data: { gu1EntityId: entityId } }); } // Create KYC validation (entityId + integrationCode) const validation = await gu1.post('/kyc/validations', { entityId, integrationCode: 'global_gueno_validation_kyc' }); await db.users.update({ where: { id: userId }, data: { kycValidationId: validation.id, kycStatus: 'pending' } }); res.json({ verificationUrl: validation.providerSessionUrl }); }); ``` ### 2. Frontend: Open Verification ```javascript theme={null} // User clicks "Verify Identity" async function startVerification() { const { verificationUrl } = await fetch('/api/kyc/start', { method: 'POST', body: JSON.stringify({ userId: currentUser.id }) }).then(r => r.json()); // Open in WebView/iframe openVerificationUI(verificationUrl); // Start polling pollForCompletion(); } ``` ### 3. Backend: Receive Webhook ```javascript theme={null} // POST /webhooks/gu1/kyc app.post('/webhooks/gu1/kyc', async (req, res) => { const { event, payload } = req.body; if (event === 'kyc.validation_approved') { await db.users.update({ where: { externalId: payload.entity.externalId }, data: { kycStatus: 'approved', isVerified: true } }); } res.status(200).send('OK'); }); ``` ### 4. Frontend: Detect Completion ```javascript theme={null} async function pollForCompletion() { const interval = setInterval(async () => { const { status } = await fetch(`/api/kyc/status/${userId}`) .then(r => r.json()); if (status === 'approved') { clearInterval(interval); showSuccess('Identity verified!'); } else if (status === 'rejected') { clearInterval(interval); showError('Verification failed'); } }, 3000); } ``` *** ## Testing ### Sandbox Environment Use sandbox mode for testing: ```javascript theme={null} // Backend const gu1 = new Gu1Client({ apiKey: process.env.GU1_SANDBOX_API_KEY, environment: 'sandbox' // Use sandbox for testing }); ``` In sandbox mode: * No real documents required * You can simulate different outcomes * Webhooks still fire normally ### Testing Different Outcomes To test rejected/expired scenarios, use different test data in sandbox mode. *** ## Troubleshooting > [accordion] WebView shows blank page > > **Possible causes:** > > * URL expired (generate a new one) > * JavaScript disabled in WebView > * Network connectivity issues > > **Solutions:** > > * Enable JavaScript: `settings.javaScriptEnabled = true` > * Check URL is valid and not expired > * Test URL in regular browser first > [accordion] Camera not working in WebView > > **Possible causes:** > > * Missing camera permissions > * Media playback requires user gesture > > **Solutions:** > > **Android:** > > ```xml theme={null} > > ``` > > **iOS:** > > ```swift theme={null} > configuration.mediaTypesRequiringUserActionForPlayback = [] > ``` > > **Web:** > > ```html theme={null} > ``` Alternatives: full-page redirect to `sessionUrl`, or a compatible Web SDK initialized with the same URL. ## Poll or Sync Status * `GET /api/kyc/biometric/sessions/:id` — one session by ID * `GET /api/kyc/biometric/entities/:entityId/current` — **current session** = most recent by `createdAt` (any status). Returns `200` with `null` if none. * `GET /api/kyc/biometric/entities/by-tax-id/:taxId/current` — same, resolved by tax ID * `GET /api/kyc/biometric/entities/by-external-id/:externalId/current` — same, resolved by external ID * `GET /api/kyc/biometric/sessions?entityId=...` — list; also accepts `entityTaxId` or `entityExternalId` (one at a time). `currentSessionId` is the latest **`approved`** session. * `POST /api/kyc/biometric/sessions/:id/sync` — refresh session state from Gu1 if webhooks are delayed. * `POST /api/kyc/biometric/sessions/:id/cancel` — manually cancel `pending` or `in_progress` sessions (marks `cancelled` in Gu1). If `POST /sessions` returns `409 ACTIVE_SESSION_EXISTS`, the body includes `activeSessionId` so you can cancel without calling `/current`. > [!NOTE] > > The platform may report **In Review** while capture is reviewed; Gu1 maps that to `in_progress` until the final verdict (`approved` or `rejected`). Only terminal outcome states define the entity current session. ## Webhooks Two channels: 1. **Per-request `webhookUrl`** — only if you sent it in `POST /sessions`; fires on terminal status. 2. **Organization webhooks** — subscribe to `biometric.session_*` events in [Webhook configuration](/en/webhooks/configuration). See [Biometric webhook events](/en/webhooks/events/biometric-events). ## Comparison with Synchronous Biometric | | `POST /api/kyc/biometric` | `POST /api/kyc/biometric/sessions` | | - | - | - | | Capture | Your app sends image | Hosted UI (iframe) | | Fraud resistance | Lower | Higher (liveness in hosted UI) | | Async | No | Yes | | `webhookUrl` per request | No | Yes | For step-up authentication and login flows, prefer **embedded sessions**. ## Sandbox Mock Sessions In **sandbox**, when the entity has an **approved KYC mock** (test `taxId` such as `99990001`, or KYC with `metadata.sandboxMock: true`), `POST /api/kyc/biometric/sessions` can return an **immediate mock result** (`approved` or `rejected`) without hosted capture. * Default: `99990001` → biometric **approved**; `99990011` → biometric **rejected** (KYC still approved). * Override on any eligible entity: `"metadata": { "sandboxMockOutcome": "rejected" }`. * Mock responses use `hostedSessionId` prefixed with `sandbox-mock-bio-` and may return `status: approved` or `rejected` in the create response (not only `pending`). Full tables and examples: [Sandbox mock data — Embedded biometric](/en/use-cases/kyc/sandbox-mock-data#embedded-biometric-sandbox-mock). # Face Match (Document + Selfie) Source: https://docs.gu1.ai/en/use-cases/kyc/face-match POST /api/kyc/face-match Verify that a selfie and a document photo belong to the same person via a single API call — in the gu1 KYC API for identity verification flows. ## Overview Face Match is a **Gu1 verification service** that compares two images: a **selfie** (current photo of the person) and a **document reference image** (e.g. the portrait from an ID). The API returns whether the faces match (same person) and a similarity score. No hosted session or real-time liveness is involved—you send the images and get the result in one call. > [!NOTE] > > **When to use which** > > * **Session-based KYC** (`POST /api/kyc/validations`): Full flow with hosted URL, live selfie, liveness, and document capture. Best for onboarding and regulated flows. > * **Face Match** (`POST /api/kyc/face-match`): You send two images (as files or base64); you get back match + score. Best for validating document + selfie you already have (e.g. from your own app). ## Prerequisites Before using Face Match: 1. **Face Match integration enabled**: Your organization must have the Face Match KYC integration activated (e.g. in Marketplace / Integrations). 2. **Credentials configured**: API key and webhook secret for the Face Match integration must be set in your organization's KYC settings (configured by the Gu1 administrator). 3. **Threshold (optional)**: The minimum score required to approve (0–100) is configured in **Organization Settings → KYC** (Face Match card). If not set, the default is 30. Only your organization's admins can change this value. > [!NOTE] > > Face Match is a Gu1 service. All verification is performed by Gu1 infrastructure. ## Request ### Endpoint ``` POST https://api.gu1.ai/api/kyc/face-match ``` ### Content-Type **Only `multipart/form-data`** is accepted. You can send images in either of two ways (or mix): 1. **As file parts**: attach image files to the form fields `documentImage` and `selfieImage`. 2. **As base64 strings**: send the same field names with base64-encoded image strings (with or without `data:image/...;base64,` prefix). If a **required** image is missing (no file and no base64 for that field), the API returns **400**. For each image, if you send both a file and a base64 string, the file takes precedence. ### Headers ``` Authorization: Bearer YOUR_API_KEY Content-Type: multipart/form-data; boundary=----... ``` Do **not** set `Content-Type` manually when using FormData; the client will set it with the correct boundary. If your account uses organization scoping, include: ``` X-Organization-Id: YOUR_ORGANIZATION_ID ``` ### Form Fields **documentImage** `file | string` *required* Reference image (e.g. portrait from ID document). Send as a **file part** (recommended) or as a **string** (base64, with or without `data:image/...;base64,` prefix). Formats: JPEG, PNG, WebP, TIFF. Max 5MB. **selfieImage** `file | string` *required* Selfie image. Same as `documentImage`: file part or base64 string. Required. **entityId** `string` Optional UUID of the person entity to associate with this check. Used for audit and for listing verifications by entity. **scoreThreshold** `number` Optional. Score threshold 0–100; results below are declined. If omitted, the organization's configured threshold (or default 30) is used. **vendorData** `string` Optional reference (e.g. your user ID) for tracking. Stored with the audit record. **doubleCheckRenaper** `boolean` When `true`, after Gu1 face match approves, runs RENAPER **biometric** (`validate-dni` with the selfie) and **data** (`renaper/data`: DNI + trámite) checks. Requires org RENAPER credentials **and** active Marketplace integrations: `ar_renaper_data_enrichment` and `ar_renaper_validate_dni_enrichment`. Query overrides body if both are sent. **doubleCheckRenaper** `boolean` Same as query param `doubleCheckRenaper`. **documentNumber** `string` DNI for RENAPER when `doubleCheckRenaper=true`. Optional if `entityId` resolves `taxId` or `person.idNumber`. **gender** `string` Gender for RENAPER (`M`, `F`, `male`, `female`). Required for double-check unless resolved from linked entity. **personalNumber** `string` *required* Número de trámite for RENAPER data check. **Required** when `doubleCheckRenaper=true`. The **minimum score (threshold)** can be sent in the form; if not sent, it is read from your organization's KYC configuration. The response includes the threshold that was used for the call. ## Response ### Success Response (200 OK) | Field | Type | Description | | - | - | - | | `match` | boolean | Whether the faces were considered a match (score ≥ threshold). | | `score` | number | Similarity score 0–100. | | `status` | string | `"approved"` \| `"declined"` \| `"in_review"`. | | `verificationId` | string | ID of the audit record in `face_match_verifications` (for support and listing). | | `scoreDeclineThreshold` | number | The threshold (0–100) that was used for this verification (from org settings). | | `requestId` | string (optional) | Internal request ID (for support). | | `warnings` | string\[] (optional) | Array of **risk codes** from the verification (e.g. `LOW_FACE_MATCH_SIMILARITY`, `NO_REFERENCE_IMAGE`). See [Warning risk codes](/en/use-cases/kyc/warning-risk-codes) for all possible values. | | `doubleCheckRenaper` | boolean (optional) | `true` when RENAPER double-check was requested. | | `responseDoubleChecks` | object (optional) | When `doubleCheckRenaper=true`: `renaper` with data/trámite and nested `renaper.renaperBiometric` (ABIS). Same shape as [KYC validations RENAPER](/en/use-cases/kyc/create-validation#renaper-double-check-argentina). | If RENAPER double-check fails after provider approval, `match` becomes `false`, `status` becomes `"declined"`, and RENAPER codes (e.g. `RENAPER_BIOMETRIC_NOT_MATCH`) are added to `warnings`. Allow **60+ seconds** HTTP timeout when using double-check (biometric polling). **Example:** ```json theme={null} { "match": true, "score": 85.5, "status": "approved", "verificationId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "scoreDeclineThreshold": 30, "requestId": "req_xyz", "warnings": [] } ``` ## Example Request ```javascript Node.js (files) theme={null} const form = new FormData(); form.append('documentImage', documentFile); // File object form.append('selfieImage', selfieFile); form.append('entityId', '123e4567-e89b-12d3-a456-426614174000'); const response = await fetch('https://api.gu1.ai/api/kyc/face-match', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, body: form, }); const result = await response.json(); console.log('Match:', result.match, 'Score:', result.score); ``` ```javascript Node.js (base64 in form fields) theme={null} const form = new FormData(); form.append('documentImage', 'data:image/jpeg;base64,/9j/4AAQ...'); form.append('selfieImage', 'data:image/jpeg;base64,/9j/4AAQ...'); form.append('entityId', '123e4567-e89b-12d3-a456-426614174000'); const response = await fetch('https://api.gu1.ai/api/kyc/face-match', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, body: form, }); const result = await response.json(); ``` ```python Python (files) theme={null} import requests with open('document.jpg', 'rb') as doc, open('selfie.jpg', 'rb') as selfie: files = { 'documentImage': ('document.jpg', doc, 'image/jpeg'), 'selfieImage': ('selfie.jpg', selfie, 'image/jpeg'), } data = {'entityId': '123e4567-e89b-12d3-a456-426614174000'} response = requests.post( 'https://api.gu1.ai/api/kyc/face-match', headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data=data, ) result = response.json() print('Match:', result['match'], 'Score:', result['score']) ``` ```python Python (base64 in form fields) theme={null} import requests import base64 with open('document.jpg', 'rb') as f: doc_b64 = 'data:image/jpeg;base64,' + base64.b64encode(f.read()).decode() with open('selfie.jpg', 'rb') as f: selfie_b64 = 'data:image/jpeg;base64,' + base64.b64encode(f.read()).decode() response = requests.post( 'https://api.gu1.ai/api/kyc/face-match', headers={'Authorization': 'Bearer YOUR_API_KEY'}, data={ 'documentImage': doc_b64, 'selfieImage': selfie_b64, 'entityId': '123e4567-e89b-12d3-a456-426614174000', }, ) result = response.json() ``` ```curl cURL (files) theme={null} curl -X POST https://api.gu1.ai/api/kyc/face-match \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "documentImage=@document.jpg" \ -F "selfieImage=@selfie.jpg" \ -F "entityId=123e4567-e89b-12d3-a456-426614174000" ``` ```curl cURL (base64) theme={null} curl -X POST https://api.gu1.ai/api/kyc/face-match \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "documentImage=data:image/jpeg;base64,/9j/4AAQ..." \ -F "selfieImage=data:image/jpeg;base64,/9j/4AAQ..." \ -F "entityId=123e4567-e89b-12d3-a456-426614174000" ``` ## Error Responses Common error codes: | Code | HTTP | Meaning | | - | - | - | | `NOT_CONFIGURED` | 403 | Face Match credentials not set in organization KYC settings. | | `NOT_ENABLED` | 403 | Face Match integration is not enabled for this organization. | | `INVALID_REQUEST` | 400 | Content-Type not multipart/form-data, or missing/invalid images (e.g. no file and no base64 for a required field, format/size). | | `UNAUTHORIZED` | 401 | Invalid or missing API/verification credentials. | | `QUOTA_EXCEEDED` | 403 | Verification could not be completed (e.g. quota/credits). | | `SERVICE_UNAVAILABLE` | 503 | Verification service temporarily unavailable. | | `VERIFICATION_FAILED` | 500 | Verification could not be completed; retry or try other images. | ## Audit and Listing Verifications Every Face Match request (success or failure) is stored in **`face_match_verifications`** for audit and compliance. The response includes **`verificationId`** (the audit record ID). Each stored record also saves the **threshold** that was used at the time of the call (so you can show it in history even if the org threshold changes later). ### List Audit Records ``` GET https://api.gu1.ai/api/kyc/face-match/verifications?entityId={entityId}&limit=50&offset=0 ``` **Query parameters:** | Parameter | Type | Description | | - | - | - | | `entityId` | string (UUID) | Optional. Filter by person entity. | | `status` | string | Optional. Filter by status (`approved`, `declined`, `in_review`, `failed`). | | `limit` | number | Max items (default 50, max 100). | | `offset` | number | Pagination offset. | **Response:** `{ "verifications": [ ... ], "scoreDeclineThreshold": 30, "pagination": { "limit", "offset", "total" } }`. Each verification includes `id`, `entityId`, `status`, `match`, `score`, `threshold` (the value used for that run), `createdAt`, and optional image paths for audit. ### Get Verification by ID Retrieve a single Face Match audit record by its `verificationId` (returned in the POST response or in the list). ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/:id ``` **Path parameter:** `id` — UUID of the verification (same as `verificationId` from the POST or list). **Response (200):** One verification object with the same fields as each item in the list: `id`, `organizationId`, `entityId`, `status`, `match`, `score`, `requestId`, `vendorData`, `errorMessage`, `triggeredByUserId`, `createdAt`, `documentStoragePath`, `selfieStoragePath`, `storageProvider`, `threshold`. **Errors:** `404 NOT_FOUND` if the ID does not exist or belongs to another organization; `401 UNAUTHORIZED` if not authenticated. ## Coexistence with Session-Based KYC * **Session flow** creates a `kyc_validations` record, sends the user to a hosted URL, and updates status via webhooks. The stored decision includes document, liveness, and face match from the live session. * **Face Match** creates an audit record in `face_match_verifications` and returns the result in the same request. It does **not** create a `kyc_validations` record. Use it when you need a one-off check (e.g. "are these two images the same person?") without a hosted session. * Both use the same organization KYC configuration. The threshold for Face Match is set in Organization Settings → KYC (Face Match card). ## Next Steps > [card] [Create KYC Validation](/en/use-cases/kyc/create-validation) > > Session-based verification with hosted URL > [card] [List Validations](/en/use-cases/kyc/list-validations) > > List KYC validations by entity # Get Face Match images Source: https://docs.gu1.ai/en/use-cases/kyc/face-match-images GET /api/kyc/face-match/verifications/{id}/document-image Download the document and selfie images for a Face Match verification — in the gu1 KYC API for identity verification flows, with examples for face match images. ## Overview After a successful [Face Match](/en/use-cases/kyc/face-match) request, you can download the **document** and **selfie** that were submitted by calling the two GET endpoints below. Use the same **`verificationId`** (UUID) returned in the POST response (or the `id` from [GET verification](/en/use-cases/kyc/get-face-match-verification)). Use the same **`Authorization: Bearer`** API key and **read KYC** permission as for other Face Match routes. If a copy of an image was not kept for that verification, the corresponding endpoint returns **404** (for example when storage failed during the run). ## Endpoints ### Document image ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/{verificationId}/document-image ``` ### Selfie image ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/{verificationId}/selfie-image ``` ### Path parameters **verificationId** `string` *required* UUID of the Face Match verification (same as `verificationId` from POST or `id` from GET one/list). ### Headers * **`Authorization`**: `Bearer YOUR_API_KEY` (required) Include `X-Organization-Id` if your account is organization-scoped. ### Responses | HTTP | Description | | - | - | | **200** | Raw image bytes (`Content-Type` e.g. `image/jpeg`, `image/png`). | | **404** | Verification not found, not in your organization, or that image is not available for download. | ## Examples ```bash theme={null} # Document (reference image sent in POST) curl -sS -o document.jpg \ -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.gu1.ai/api/kyc/face-match/verifications/VERIFICATION_UUID/document-image" # Selfie curl -sS -o selfie.jpg \ -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.gu1.ai/api/kyc/face-match/verifications/VERIFICATION_UUID/selfie-image" ``` ## Related * [Face Match (POST)](/en/use-cases/kyc/face-match) * [Get Face Match verification](/en/use-cases/kyc/get-face-match-verification) # Get Face Match Verification Source: https://docs.gu1.ai/en/use-cases/kyc/get-face-match-verification GET /api/kyc/face-match/verifications/{id} Retrieve a single Face Match audit record by ID — in the gu1 KYC API for identity verification flows, with examples for get face match verification use cases. ## Overview Returns one Face Match verification by its `id` (the same UUID returned as `verificationId` in the [POST Face Match](/en/use-cases/kyc/face-match) response or in the list endpoint). Use it to fetch full details of a past verification for audit, support, or detail views. **Key points:** * Scoped to your organization; returns 404 if the ID does not exist or belongs to another org. * Same fields as each item in the list: `id`, `entityId`, `status`, `match`, `score`, `threshold`, `createdAt`, and optional image paths. > [!NOTE] > > To download stored **document** and **selfie** bytes, use [Get Face Match images](/en/use-cases/kyc/face-match-images) (`/document-image` and `/selfie-image`). ## Request ### Endpoint ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/:id ``` ### Path Parameters **id** `string` *required* UUID of the Face Match verification (same as `verificationId` from POST or list). ### Headers ```json theme={null} { "Authorization": "Bearer YOUR_API_KEY" } ``` Include `X-Organization-Id` if your account is scoped by organization. ## Response ### Success (200 OK) Single verification object: | Field | Type | Description | | - | - | - | | `id` | string | Verification UUID. | | `organizationId` | string | Organization that owns the record. | | `entityId` | string \| null | Person entity ID if provided in the request. | | `status` | string | `approved` \| `declined` \| `in_review` \| `failed`. | | `match` | boolean | Whether faces were considered a match. | | `score` | number \| null | Similarity score 0–100 (null when `status` is `failed`). | | `requestId` | string \| null | Internal request ID (support). | | `vendorData` | string \| null | Client reference from the request. | | `errorMessage` | string \| null | Error message when `status` is `failed`. | | `triggeredByUserId` | string \| null | User who called the API. | | `createdAt` | string | ISO timestamp. | | `documentStoragePath` | string \| null | Storage path for document image (audit). | | `selfieStoragePath` | string \| null | Storage path for selfie image (audit). | | `storageProvider` | string \| null | `s3` or `local`. | | `threshold` | number \| null | Score threshold used for this verification (from org settings at the time). | ### Error Responses | Code | HTTP | Description | | - | - | - | | `NOT_FOUND` | 404 | Verification ID does not exist or belongs to another organization. | | `UNAUTHORIZED` | 401 | Missing or invalid API key or organization context. | ## Example ```javascript Node.js theme={null} const id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'; const response = await fetch(`https://api.gu1.ai/api/kyc/face-match/verifications/${id}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, }); const verification = await response.json(); ``` ```curl cURL theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.gu1.ai/api/kyc/face-match/verifications/a1b2c3d4-e5f6-7890-abcd-ef1234567890" ``` ## Next Steps > [card] [Face Match (POST)](/en/use-cases/kyc/face-match) > > Verify document + selfie in one call > [card] [List Validations](/en/use-cases/kyc/list-validations) > > List KYC validations by entity # Get ID Verification (List & Single) Source: https://docs.gu1.ai/en/use-cases/kyc/get-id-verification-verification GET /api/kyc/id-verification/verifications List ID verification audit records or get one by ID — in the gu1 KYC API for identity verification flows, with examples for get id verification. ## Overview After submitting document images via [POST ID Verification](/en/use-cases/kyc/id-verification), each request is stored for audit. You can: 1. **List** verifications (with optional filters: `entityId`, `withoutEntity`, `status`, pagination). 2. **Get a single** verification by ID (same UUID as `verificationId` in the POST response). To **download stored document front/back bytes**, use [Get ID Verification images](/en/use-cases/kyc/id-verification-images). All endpoints are scoped to your organization. Each list/get item uses the same `extractedData` shape as POST (see [extractedData fields](/en/use-cases/kyc/id-verification#extracteddata-fields)), including `ejemplar` when present on Argentine DNI. ## 1. List Verifications ``` GET https://api.gu1.ai/api/kyc/id-verification/verifications ``` ### Query Parameters | Parameter | Type | Description | | - | - | - | | `entityId` | string (UUID) | Optional. Filter by person entity. | | `withoutEntity` | boolean | If `true`, only verifications with no associated entity. | | `status` | string | Optional. `approved` \| `declined` \| `failed`. | | `limit` | number | Max items (default 50, max 100). | | `offset` | number | Pagination offset. | ### Response (200 OK) ```json theme={null} { "verifications": [ { "id": "c3d4e5f6-a7b8-9012-cdef-345678901234", "organizationId": "123e4567-e89b-12d3-a456-426614174000", "entityId": "223e4567-e89b-12d3-a456-426614174001", "status": "declined", "requestId": "4e2bf9fb-d75b-4b26-9362-e51436cfe1eb", "vendorData": "my-ref-001", "errorMessage": null, "warnings": ["DOCUMENT_EXPIRED", "POSSIBLE_DUPLICATED_USER"], "extractedData": { "providerStatus": "Declined", "fullName": "Breno Henrique Ferreira Silva", "firstName": "Breno Henrique", "lastName": "Ferreira Silva", "firstSurname": "Ferreira", "secondSurname": "Silva", "documentNumber": "08585626509", "personalNumber": "2156732124SSPBA", "documentType": "Driver's License", "taxNumber": "10584158599", "dateOfBirth": "2004-08-29", "age": 21, "expirationDate": "2025-03-07", "dateOfIssue": "2024-03-08", "firstIssueDate": "2024-03-08", "nationality": "BRA", "gender": "U", "placeOfBirth": "Barreiras/Ba", "maritalStatus": "UNKNOWN", "issuingState": "BRA", "issuingStateName": "Brazil", "warningMeta": { "duplicatedSessionId": "a4bfeef8-6d6e-4e9b-8fcb-44950912b2b4", "duplicatedSessionNumber": 2834, "duplicatedApiService": "ID_VERIFICATION" }, "frontImageQualityScore": { "overall_score": 98.2, "focus_score": 100, "brightness_score": 94, "is_document_fully_visible": true }, "backImageQualityScore": { "overall_score": 97.1, "focus_score": 100 }, "extraFields": { "license_category": "AB", "restrictions": "01" }, "mrz": { "line1": "IDBRA085856265<<<<<<<<<<<<<<<", "line2": "0408299M2503077BRA<<<<<<<<<<<6", "line3": "SILVA< [card] [ID Verification (POST)](/en/use-cases/kyc/id-verification) > > Submit document front/back and get validation > [card] [Face Match](/en/use-cases/kyc/face-match) > > Compare document and selfie # Get KYC Verification URL Source: https://docs.gu1.ai/en/use-cases/kyc/get-kyc-url GET /api/kyc/validations/{id} Retrieve the verification URL to share with your customer — in the gu1 KYC API for identity verification flows, with examples for get kyc url use cases. ## Overview After creating a KYC validation, you can retrieve the verification URL at any time. This URL is what you'll share with your customer so they can complete the identity verification process. ## When to Use This * **Retrieve URL later**: If you didn't store the URL from the creation response * **Resend to customer**: When customer requests a new link * **Check validation details**: View current status and metadata * **Integrate with other systems**: Pass verification URL to notification services ## Request ### Endpoint ``` GET https://api.gu1.ai/api/kyc/validations/{id} ``` ### Path Parameters **id** `string` *required* The validation ID returned when you created the KYC validation ### Headers ```json theme={null} { "Authorization": "Bearer YOUR_API_KEY" } ``` ## Response ### Success Response (200 OK) ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "entityId": "123e4567-e89b-12d3-a456-426614174000", "organizationId": "org_abc123", "validationSessionId": "session_xyz789", "status": "pending", "provider": "kyc_provider", "providerSessionUrl": "https://verify.example.com/session_xyz789", "decision": null, "documentsVerified": [], "biometricResult": null, "riskAssessment": null, "verifiedFields": [], "extractedData": null, "warnings": [], "isCurrent": true, "expiresAt": null, "verifiedAt": null, "metadata": { "userId": "user_12345", "source": "mobile_app" }, "createdAt": "2025-01-15T10:30:00Z", "updatedAt": "2025-01-15T10:30:00Z" } ``` ### Response Fields **providerSessionUrl** `string` **The verification URL to share with your customer**. This is the main field you need. **status** `string` Current validation status: * `pending` - Waiting for customer to start * `in_progress` - Customer is completing verification * `in_review` - Verification completed, requires manual review from compliance team * `approved` - Verification successful * `rejected` - Verification failed * `expired` - Session expired * `abandoned` - Customer abandoned the process * `cancelled` - Validation was cancelled **decision** `object` Final decision details (available after completion): * `document_details` - Information about verified document * `extracted_information` - Personal data extracted from document * `verification_results` - Results of various checks * `warnings` - Any warnings or issues found **documentsVerified** `array` List of documents that were verified (after completion) **biometricResult** `object` Results of biometric verification (after completion) **riskAssessment** `object` Risk assessment information (after completion) **verifiedFields** `array` List of fields successfully verified (e.g., \["firstName", "lastName", "dateOfBirth"]) **extractedData** `object` Personal data extracted from the document **verifiedAt** `string` Timestamp when verification was completed ## Example Request ```javascript Node.js theme={null} const validationId = '550e8400-e29b-41d4-a716-446655440000'; const response = await fetch( `https://api.gu1.ai/api/kyc/validations/${validationId}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const validation = await response.json(); // Extract the URL to share with customer const verificationUrl = validation.providerSessionUrl; console.log('Share this URL with your customer:', verificationUrl); // Check current status console.log('Current status:', validation.status); ``` ```python Python theme={null} import requests validation_id = '550e8400-e29b-41d4-a716-446655440000' response = requests.get( f'https://api.gu1.ai/api/kyc/validations/{validation_id}', headers={ 'Authorization': 'Bearer YOUR_API_KEY' } ) validation = response.json() # Extract the URL to share with customer verification_url = validation['providerSessionUrl'] print('Share this URL with your customer:', verification_url) # Check current status print('Current status:', validation['status']) ``` ```curl cURL theme={null} curl -X GET https://api.gu1.ai/api/kyc/validations/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Alternative: Get Current Validation for Entity If you don't have the validation ID but have the entity ID, you can get the current validation: ### Endpoint ``` GET https://api.gu1.ai/api/kyc/entities/{entityId}/current ``` ### Example ```javascript Node.js theme={null} const entityId = '123e4567-e89b-12d3-a456-426614174000'; const response = await fetch( `https://api.gu1.ai/api/kyc/entities/${entityId}/current`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const validation = await response.json(); const verificationUrl = validation.providerSessionUrl; ``` ```python Python theme={null} entity_id = '123e4567-e89b-12d3-a456-426614174000' response = requests.get( f'https://api.gu1.ai/api/kyc/entities/{entity_id}/current', headers={'Authorization': 'Bearer YOUR_API_KEY'} ) validation = response.json() verification_url = validation['providerSessionUrl'] ``` ## Sharing the URL with Customers Once you have the verification URL, you can share it with your customer through various channels: ### Email Example ```html theme={null}

Hi {{customerName}},

Please complete your identity verification to continue:

Verify Your Identity

This link will expire in 7 days.

``` ### SMS Example ``` Complete your identity verification here: {{providerSessionUrl}} ``` ### In-App Integration ```javascript theme={null} // Redirect user to verification window.location.href = providerSessionUrl; // Or open in new window window.open(providerSessionUrl, '_blank'); // Or embed in iframe ``` Alternatives: full-page redirect to `sessionUrl`, or a compatible Web SDK initialized with the same URL. ## Poll or Sync Status * `GET /api/kyc/biometric/sessions/:id` — one session by ID * `GET /api/kyc/biometric/entities/:entityId/current` — **current session** = most recent by `createdAt` (any status). Returns `200` with `null` if none. * `GET /api/kyc/biometric/entities/by-tax-id/:taxId/current` — same, resolved by tax ID * `GET /api/kyc/biometric/entities/by-external-id/:externalId/current` — same, resolved by external ID * `GET /api/kyc/biometric/sessions?entityId=...` — list; also accepts `entityTaxId` or `entityExternalId` (one at a time). `currentSessionId` is the latest **`approved`** session. * `POST /api/kyc/biometric/sessions/:id/sync` — refresh session state from Gu1 if webhooks are delayed. * `POST /api/kyc/biometric/sessions/:id/cancel` — manually cancel `pending` or `in_progress` sessions (marks `cancelled` in Gu1). If `POST /sessions` returns `409 ACTIVE_SESSION_EXISTS`, the body includes `activeSessionId` so you can cancel without calling `/current`. > [!NOTE] > > The platform may report **In Review** while capture is reviewed; Gu1 maps that to `in_progress` until the final verdict (`approved` or `rejected`). Only terminal outcome states define the entity current session. ## Webhooks Two channels: 1. **Per-request `webhookUrl`** — only if you sent it in `POST /sessions`; fires on terminal status. 2. **Organization webhooks** — subscribe to `biometric.session_*` events in [Webhook configuration](/en/webhooks/configuration). See [Biometric webhook events](/en/webhooks/events/biometric-events). ## Comparison with Synchronous Biometric | | `POST /api/kyc/biometric` | `POST /api/kyc/biometric/sessions` | | - | - | - | | Capture | Your app sends image | Hosted UI (iframe) | | Fraud resistance | Lower | Higher (liveness in hosted UI) | | Async | No | Yes | | `webhookUrl` per request | No | Yes | For step-up authentication and login flows, prefer **embedded sessions**. ## Sandbox Mock Sessions In **sandbox**, when the entity has an **approved KYC mock** (test `taxId` such as `99990001`, or KYC with `metadata.sandboxMock: true`), `POST /api/kyc/biometric/sessions` can return an **immediate mock result** (`approved` or `rejected`) without hosted capture. * Default: `99990001` → biometric **approved**; `99990011` → biometric **rejected** (KYC still approved). * Override on any eligible entity: `"metadata": { "sandboxMockOutcome": "rejected" }`. * Mock responses use `hostedSessionId` prefixed with `sandbox-mock-bio-` and may return `status: approved` or `rejected` in the create response (not only `pending`). Full tables and examples: [Sandbox mock data — Embedded biometric](/en/use-cases/kyc/sandbox-mock-data#embedded-biometric-sandbox-mock). # Face Match (Document + Selfie) Source: https://docs.gu1.ai/en/use-cases/kyc/face-match POST /api/kyc/face-match Verify that a selfie and a document photo belong to the same person via a single API call — in the gu1 KYC API for identity verification flows. ## Overview Face Match is a **Gu1 verification service** that compares two images: a **selfie** (current photo of the person) and a **document reference image** (e.g. the portrait from an ID). The API returns whether the faces match (same person) and a similarity score. No hosted session or real-time liveness is involved—you send the images and get the result in one call. > [!NOTE] > > **When to use which** > > * **Session-based KYC** (`POST /api/kyc/validations`): Full flow with hosted URL, live selfie, liveness, and document capture. Best for onboarding and regulated flows. > * **Face Match** (`POST /api/kyc/face-match`): You send two images (as files or base64); you get back match + score. Best for validating document + selfie you already have (e.g. from your own app). ## Prerequisites Before using Face Match: 1. **Face Match integration enabled**: Your organization must have the Face Match KYC integration activated (e.g. in Marketplace / Integrations). 2. **Credentials configured**: API key and webhook secret for the Face Match integration must be set in your organization's KYC settings (configured by the Gu1 administrator). 3. **Threshold (optional)**: The minimum score required to approve (0–100) is configured in **Organization Settings → KYC** (Face Match card). If not set, the default is 30. Only your organization's admins can change this value. > [!NOTE] > > Face Match is a Gu1 service. All verification is performed by Gu1 infrastructure. ## Request ### Endpoint ``` POST https://api.gu1.ai/api/kyc/face-match ``` ### Content-Type **Only `multipart/form-data`** is accepted. You can send images in either of two ways (or mix): 1. **As file parts**: attach image files to the form fields `documentImage` and `selfieImage`. 2. **As base64 strings**: send the same field names with base64-encoded image strings (with or without `data:image/...;base64,` prefix). If a **required** image is missing (no file and no base64 for that field), the API returns **400**. For each image, if you send both a file and a base64 string, the file takes precedence. ### Headers ``` Authorization: Bearer YOUR_API_KEY Content-Type: multipart/form-data; boundary=----... ``` Do **not** set `Content-Type` manually when using FormData; the client will set it with the correct boundary. If your account uses organization scoping, include: ``` X-Organization-Id: YOUR_ORGANIZATION_ID ``` ### Form Fields **documentImage** `file | string` *required* Reference image (e.g. portrait from ID document). Send as a **file part** (recommended) or as a **string** (base64, with or without `data:image/...;base64,` prefix). Formats: JPEG, PNG, WebP, TIFF. Max 5MB. **selfieImage** `file | string` *required* Selfie image. Same as `documentImage`: file part or base64 string. Required. **entityId** `string` Optional UUID of the person entity to associate with this check. Used for audit and for listing verifications by entity. **scoreThreshold** `number` Optional. Score threshold 0–100; results below are declined. If omitted, the organization's configured threshold (or default 30) is used. **vendorData** `string` Optional reference (e.g. your user ID) for tracking. Stored with the audit record. **doubleCheckRenaper** `boolean` When `true`, after Gu1 face match approves, runs RENAPER **biometric** (`validate-dni` with the selfie) and **data** (`renaper/data`: DNI + trámite) checks. Requires org RENAPER credentials **and** active Marketplace integrations: `ar_renaper_data_enrichment` and `ar_renaper_validate_dni_enrichment`. Query overrides body if both are sent. **doubleCheckRenaper** `boolean` Same as query param `doubleCheckRenaper`. **documentNumber** `string` DNI for RENAPER when `doubleCheckRenaper=true`. Optional if `entityId` resolves `taxId` or `person.idNumber`. **gender** `string` Gender for RENAPER (`M`, `F`, `male`, `female`). Required for double-check unless resolved from linked entity. **personalNumber** `string` *required* Número de trámite for RENAPER data check. **Required** when `doubleCheckRenaper=true`. The **minimum score (threshold)** can be sent in the form; if not sent, it is read from your organization's KYC configuration. The response includes the threshold that was used for the call. ## Response ### Success Response (200 OK) | Field | Type | Description | | - | - | - | | `match` | boolean | Whether the faces were considered a match (score ≥ threshold). | | `score` | number | Similarity score 0–100. | | `status` | string | `"approved"` \| `"declined"` \| `"in_review"`. | | `verificationId` | string | ID of the audit record in `face_match_verifications` (for support and listing). | | `scoreDeclineThreshold` | number | The threshold (0–100) that was used for this verification (from org settings). | | `requestId` | string (optional) | Internal request ID (for support). | | `warnings` | string\[] (optional) | Array of **risk codes** from the verification (e.g. `LOW_FACE_MATCH_SIMILARITY`, `NO_REFERENCE_IMAGE`). See [Warning risk codes](/en/use-cases/kyc/warning-risk-codes) for all possible values. | | `doubleCheckRenaper` | boolean (optional) | `true` when RENAPER double-check was requested. | | `responseDoubleChecks` | object (optional) | When `doubleCheckRenaper=true`: `renaper` with data/trámite and nested `renaper.renaperBiometric` (ABIS). Same shape as [KYC validations RENAPER](/en/use-cases/kyc/create-validation#renaper-double-check-argentina). | If RENAPER double-check fails after provider approval, `match` becomes `false`, `status` becomes `"declined"`, and RENAPER codes (e.g. `RENAPER_BIOMETRIC_NOT_MATCH`) are added to `warnings`. Allow **60+ seconds** HTTP timeout when using double-check (biometric polling). **Example:** ```json theme={null} { "match": true, "score": 85.5, "status": "approved", "verificationId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "scoreDeclineThreshold": 30, "requestId": "req_xyz", "warnings": [] } ``` ## Example Request ```javascript Node.js (files) theme={null} const form = new FormData(); form.append('documentImage', documentFile); // File object form.append('selfieImage', selfieFile); form.append('entityId', '123e4567-e89b-12d3-a456-426614174000'); const response = await fetch('https://api.gu1.ai/api/kyc/face-match', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, body: form, }); const result = await response.json(); console.log('Match:', result.match, 'Score:', result.score); ``` ```javascript Node.js (base64 in form fields) theme={null} const form = new FormData(); form.append('documentImage', 'data:image/jpeg;base64,/9j/4AAQ...'); form.append('selfieImage', 'data:image/jpeg;base64,/9j/4AAQ...'); form.append('entityId', '123e4567-e89b-12d3-a456-426614174000'); const response = await fetch('https://api.gu1.ai/api/kyc/face-match', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, body: form, }); const result = await response.json(); ``` ```python Python (files) theme={null} import requests with open('document.jpg', 'rb') as doc, open('selfie.jpg', 'rb') as selfie: files = { 'documentImage': ('document.jpg', doc, 'image/jpeg'), 'selfieImage': ('selfie.jpg', selfie, 'image/jpeg'), } data = {'entityId': '123e4567-e89b-12d3-a456-426614174000'} response = requests.post( 'https://api.gu1.ai/api/kyc/face-match', headers={'Authorization': 'Bearer YOUR_API_KEY'}, files=files, data=data, ) result = response.json() print('Match:', result['match'], 'Score:', result['score']) ``` ```python Python (base64 in form fields) theme={null} import requests import base64 with open('document.jpg', 'rb') as f: doc_b64 = 'data:image/jpeg;base64,' + base64.b64encode(f.read()).decode() with open('selfie.jpg', 'rb') as f: selfie_b64 = 'data:image/jpeg;base64,' + base64.b64encode(f.read()).decode() response = requests.post( 'https://api.gu1.ai/api/kyc/face-match', headers={'Authorization': 'Bearer YOUR_API_KEY'}, data={ 'documentImage': doc_b64, 'selfieImage': selfie_b64, 'entityId': '123e4567-e89b-12d3-a456-426614174000', }, ) result = response.json() ``` ```curl cURL (files) theme={null} curl -X POST https://api.gu1.ai/api/kyc/face-match \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "documentImage=@document.jpg" \ -F "selfieImage=@selfie.jpg" \ -F "entityId=123e4567-e89b-12d3-a456-426614174000" ``` ```curl cURL (base64) theme={null} curl -X POST https://api.gu1.ai/api/kyc/face-match \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "documentImage=data:image/jpeg;base64,/9j/4AAQ..." \ -F "selfieImage=data:image/jpeg;base64,/9j/4AAQ..." \ -F "entityId=123e4567-e89b-12d3-a456-426614174000" ``` ## Error Responses Common error codes: | Code | HTTP | Meaning | | - | - | - | | `NOT_CONFIGURED` | 403 | Face Match credentials not set in organization KYC settings. | | `NOT_ENABLED` | 403 | Face Match integration is not enabled for this organization. | | `INVALID_REQUEST` | 400 | Content-Type not multipart/form-data, or missing/invalid images (e.g. no file and no base64 for a required field, format/size). | | `UNAUTHORIZED` | 401 | Invalid or missing API/verification credentials. | | `QUOTA_EXCEEDED` | 403 | Verification could not be completed (e.g. quota/credits). | | `SERVICE_UNAVAILABLE` | 503 | Verification service temporarily unavailable. | | `VERIFICATION_FAILED` | 500 | Verification could not be completed; retry or try other images. | ## Audit and Listing Verifications Every Face Match request (success or failure) is stored in **`face_match_verifications`** for audit and compliance. The response includes **`verificationId`** (the audit record ID). Each stored record also saves the **threshold** that was used at the time of the call (so you can show it in history even if the org threshold changes later). ### List Audit Records ``` GET https://api.gu1.ai/api/kyc/face-match/verifications?entityId={entityId}&limit=50&offset=0 ``` **Query parameters:** | Parameter | Type | Description | | - | - | - | | `entityId` | string (UUID) | Optional. Filter by person entity. | | `status` | string | Optional. Filter by status (`approved`, `declined`, `in_review`, `failed`). | | `limit` | number | Max items (default 50, max 100). | | `offset` | number | Pagination offset. | **Response:** `{ "verifications": [ ... ], "scoreDeclineThreshold": 30, "pagination": { "limit", "offset", "total" } }`. Each verification includes `id`, `entityId`, `status`, `match`, `score`, `threshold` (the value used for that run), `createdAt`, and optional image paths for audit. ### Get Verification by ID Retrieve a single Face Match audit record by its `verificationId` (returned in the POST response or in the list). ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/:id ``` **Path parameter:** `id` — UUID of the verification (same as `verificationId` from the POST or list). **Response (200):** One verification object with the same fields as each item in the list: `id`, `organizationId`, `entityId`, `status`, `match`, `score`, `requestId`, `vendorData`, `errorMessage`, `triggeredByUserId`, `createdAt`, `documentStoragePath`, `selfieStoragePath`, `storageProvider`, `threshold`. **Errors:** `404 NOT_FOUND` if the ID does not exist or belongs to another organization; `401 UNAUTHORIZED` if not authenticated. ## Coexistence with Session-Based KYC * **Session flow** creates a `kyc_validations` record, sends the user to a hosted URL, and updates status via webhooks. The stored decision includes document, liveness, and face match from the live session. * **Face Match** creates an audit record in `face_match_verifications` and returns the result in the same request. It does **not** create a `kyc_validations` record. Use it when you need a one-off check (e.g. "are these two images the same person?") without a hosted session. * Both use the same organization KYC configuration. The threshold for Face Match is set in Organization Settings → KYC (Face Match card). ## Next Steps > [card] [Create KYC Validation](/en/use-cases/kyc/create-validation) > > Session-based verification with hosted URL > [card] [List Validations](/en/use-cases/kyc/list-validations) > > List KYC validations by entity # Get Face Match images Source: https://docs.gu1.ai/en/use-cases/kyc/face-match-images GET /api/kyc/face-match/verifications/{id}/document-image Download the document and selfie images for a Face Match verification — in the gu1 KYC API for identity verification flows, with examples for face match images. ## Overview After a successful [Face Match](/en/use-cases/kyc/face-match) request, you can download the **document** and **selfie** that were submitted by calling the two GET endpoints below. Use the same **`verificationId`** (UUID) returned in the POST response (or the `id` from [GET verification](/en/use-cases/kyc/get-face-match-verification)). Use the same **`Authorization: Bearer`** API key and **read KYC** permission as for other Face Match routes. If a copy of an image was not kept for that verification, the corresponding endpoint returns **404** (for example when storage failed during the run). ## Endpoints ### Document image ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/{verificationId}/document-image ``` ### Selfie image ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/{verificationId}/selfie-image ``` ### Path parameters **verificationId** `string` *required* UUID of the Face Match verification (same as `verificationId` from POST or `id` from GET one/list). ### Headers * **`Authorization`**: `Bearer YOUR_API_KEY` (required) Include `X-Organization-Id` if your account is organization-scoped. ### Responses | HTTP | Description | | - | - | | **200** | Raw image bytes (`Content-Type` e.g. `image/jpeg`, `image/png`). | | **404** | Verification not found, not in your organization, or that image is not available for download. | ## Examples ```bash theme={null} # Document (reference image sent in POST) curl -sS -o document.jpg \ -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.gu1.ai/api/kyc/face-match/verifications/VERIFICATION_UUID/document-image" # Selfie curl -sS -o selfie.jpg \ -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.gu1.ai/api/kyc/face-match/verifications/VERIFICATION_UUID/selfie-image" ``` ## Related * [Face Match (POST)](/en/use-cases/kyc/face-match) * [Get Face Match verification](/en/use-cases/kyc/get-face-match-verification) # Get Face Match Verification Source: https://docs.gu1.ai/en/use-cases/kyc/get-face-match-verification GET /api/kyc/face-match/verifications/{id} Retrieve a single Face Match audit record by ID — in the gu1 KYC API for identity verification flows, with examples for get face match verification use cases. ## Overview Returns one Face Match verification by its `id` (the same UUID returned as `verificationId` in the [POST Face Match](/en/use-cases/kyc/face-match) response or in the list endpoint). Use it to fetch full details of a past verification for audit, support, or detail views. **Key points:** * Scoped to your organization; returns 404 if the ID does not exist or belongs to another org. * Same fields as each item in the list: `id`, `entityId`, `status`, `match`, `score`, `threshold`, `createdAt`, and optional image paths. > [!NOTE] > > To download stored **document** and **selfie** bytes, use [Get Face Match images](/en/use-cases/kyc/face-match-images) (`/document-image` and `/selfie-image`). ## Request ### Endpoint ``` GET https://api.gu1.ai/api/kyc/face-match/verifications/:id ``` ### Path Parameters **id** `string` *required* UUID of the Face Match verification (same as `verificationId` from POST or list). ### Headers ```json theme={null} { "Authorization": "Bearer YOUR_API_KEY" } ``` Include `X-Organization-Id` if your account is scoped by organization. ## Response ### Success (200 OK) Single verification object: | Field | Type | Description | | - | - | - | | `id` | string | Verification UUID. | | `organizationId` | string | Organization that owns the record. | | `entityId` | string \| null | Person entity ID if provided in the request. | | `status` | string | `approved` \| `declined` \| `in_review` \| `failed`. | | `match` | boolean | Whether faces were considered a match. | | `score` | number \| null | Similarity score 0–100 (null when `status` is `failed`). | | `requestId` | string \| null | Internal request ID (support). | | `vendorData` | string \| null | Client reference from the request. | | `errorMessage` | string \| null | Error message when `status` is `failed`. | | `triggeredByUserId` | string \| null | User who called the API. | | `createdAt` | string | ISO timestamp. | | `documentStoragePath` | string \| null | Storage path for document image (audit). | | `selfieStoragePath` | string \| null | Storage path for selfie image (audit). | | `storageProvider` | string \| null | `s3` or `local`. | | `threshold` | number \| null | Score threshold used for this verification (from org settings at the time). | ### Error Responses | Code | HTTP | Description | | - | - | - | | `NOT_FOUND` | 404 | Verification ID does not exist or belongs to another organization. | | `UNAUTHORIZED` | 401 | Missing or invalid API key or organization context. | ## Example ```javascript Node.js theme={null} const id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'; const response = await fetch(`https://api.gu1.ai/api/kyc/face-match/verifications/${id}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, }); const verification = await response.json(); ``` ```curl cURL theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.gu1.ai/api/kyc/face-match/verifications/a1b2c3d4-e5f6-7890-abcd-ef1234567890" ``` ## Next Steps > [card] [Face Match (POST)](/en/use-cases/kyc/face-match) > > Verify document + selfie in one call > [card] [List Validations](/en/use-cases/kyc/list-validations) > > List KYC validations by entity # Get ID Verification (List & Single) Source: https://docs.gu1.ai/en/use-cases/kyc/get-id-verification-verification GET /api/kyc/id-verification/verifications List ID verification audit records or get one by ID — in the gu1 KYC API for identity verification flows, with examples for get id verification. ## Overview After submitting document images via [POST ID Verification](/en/use-cases/kyc/id-verification), each request is stored for audit. You can: 1. **List** verifications (with optional filters: `entityId`, `withoutEntity`, `status`, pagination). 2. **Get a single** verification by ID (same UUID as `verificationId` in the POST response). To **download stored document front/back bytes**, use [Get ID Verification images](/en/use-cases/kyc/id-verification-images). All endpoints are scoped to your organization. Each list/get item uses the same `extractedData` shape as POST (see [extractedData fields](/en/use-cases/kyc/id-verification#extracteddata-fields)), including `ejemplar` when present on Argentine DNI. ## 1. List Verifications ``` GET https://api.gu1.ai/api/kyc/id-verification/verifications ``` ### Query Parameters | Parameter | Type | Description | | - | - | - | | `entityId` | string (UUID) | Optional. Filter by person entity. | | `withoutEntity` | boolean | If `true`, only verifications with no associated entity. | | `status` | string | Optional. `approved` \| `declined` \| `failed`. | | `limit` | number | Max items (default 50, max 100). | | `offset` | number | Pagination offset. | ### Response (200 OK) ```json theme={null} { "verifications": [ { "id": "c3d4e5f6-a7b8-9012-cdef-345678901234", "organizationId": "123e4567-e89b-12d3-a456-426614174000", "entityId": "223e4567-e89b-12d3-a456-426614174001", "status": "declined", "requestId": "4e2bf9fb-d75b-4b26-9362-e51436cfe1eb", "vendorData": "my-ref-001", "errorMessage": null, "warnings": ["DOCUMENT_EXPIRED", "POSSIBLE_DUPLICATED_USER"], "extractedData": { "providerStatus": "Declined", "fullName": "Breno Henrique Ferreira Silva", "firstName": "Breno Henrique", "lastName": "Ferreira Silva", "firstSurname": "Ferreira", "secondSurname": "Silva", "documentNumber": "08585626509", "personalNumber": "2156732124SSPBA", "documentType": "Driver's License", "taxNumber": "10584158599", "dateOfBirth": "2004-08-29", "age": 21, "expirationDate": "2025-03-07", "dateOfIssue": "2024-03-08", "firstIssueDate": "2024-03-08", "nationality": "BRA", "gender": "U", "placeOfBirth": "Barreiras/Ba", "maritalStatus": "UNKNOWN", "issuingState": "BRA", "issuingStateName": "Brazil", "warningMeta": { "duplicatedSessionId": "a4bfeef8-6d6e-4e9b-8fcb-44950912b2b4", "duplicatedSessionNumber": 2834, "duplicatedApiService": "ID_VERIFICATION" }, "frontImageQualityScore": { "overall_score": 98.2, "focus_score": 100, "brightness_score": 94, "is_document_fully_visible": true }, "backImageQualityScore": { "overall_score": 97.1, "focus_score": 100 }, "extraFields": { "license_category": "AB", "restrictions": "01" }, "mrz": { "line1": "IDBRA085856265<<<<<<<<<<<<<<<", "line2": "0408299M2503077BRA<<<<<<<<<<<6", "line3": "SILVA< [card] [ID Verification (POST)](/en/use-cases/kyc/id-verification) > > Submit document front/back and get validation > [card] [Face Match](/en/use-cases/kyc/face-match) > > Compare document and selfie # Get KYC Verification URL Source: https://docs.gu1.ai/en/use-cases/kyc/get-kyc-url GET /api/kyc/validations/{id} Retrieve the verification URL to share with your customer — in the gu1 KYC API for identity verification flows, with examples for get kyc url use cases. ## Overview After creating a KYC validation, you can retrieve the verification URL at any time. This URL is what you'll share with your customer so they can complete the identity verification process. ## When to Use This * **Retrieve URL later**: If you didn't store the URL from the creation response * **Resend to customer**: When customer requests a new link * **Check validation details**: View current status and metadata * **Integrate with other systems**: Pass verification URL to notification services ## Request ### Endpoint ``` GET https://api.gu1.ai/api/kyc/validations/{id} ``` ### Path Parameters **id** `string` *required* The validation ID returned when you created the KYC validation ### Headers ```json theme={null} { "Authorization": "Bearer YOUR_API_KEY" } ``` ## Response ### Success Response (200 OK) ```json theme={null} { "id": "550e8400-e29b-41d4-a716-446655440000", "entityId": "123e4567-e89b-12d3-a456-426614174000", "organizationId": "org_abc123", "validationSessionId": "session_xyz789", "status": "pending", "provider": "kyc_provider", "providerSessionUrl": "https://verify.example.com/session_xyz789", "decision": null, "documentsVerified": [], "biometricResult": null, "riskAssessment": null, "verifiedFields": [], "extractedData": null, "warnings": [], "isCurrent": true, "expiresAt": null, "verifiedAt": null, "metadata": { "userId": "user_12345", "source": "mobile_app" }, "createdAt": "2025-01-15T10:30:00Z", "updatedAt": "2025-01-15T10:30:00Z" } ``` ### Response Fields **providerSessionUrl** `string` **The verification URL to share with your customer**. This is the main field you need. **status** `string` Current validation status: * `pending` - Waiting for customer to start * `in_progress` - Customer is completing verification * `in_review` - Verification completed, requires manual review from compliance team * `approved` - Verification successful * `rejected` - Verification failed * `expired` - Session expired * `abandoned` - Customer abandoned the process * `cancelled` - Validation was cancelled **decision** `object` Final decision details (available after completion): * `document_details` - Information about verified document * `extracted_information` - Personal data extracted from document * `verification_results` - Results of various checks * `warnings` - Any warnings or issues found **documentsVerified** `array` List of documents that were verified (after completion) **biometricResult** `object` Results of biometric verification (after completion) **riskAssessment** `object` Risk assessment information (after completion) **verifiedFields** `array` List of fields successfully verified (e.g., \["firstName", "lastName", "dateOfBirth"]) **extractedData** `object` Personal data extracted from the document **verifiedAt** `string` Timestamp when verification was completed ## Example Request ```javascript Node.js theme={null} const validationId = '550e8400-e29b-41d4-a716-446655440000'; const response = await fetch( `https://api.gu1.ai/api/kyc/validations/${validationId}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const validation = await response.json(); // Extract the URL to share with customer const verificationUrl = validation.providerSessionUrl; console.log('Share this URL with your customer:', verificationUrl); // Check current status console.log('Current status:', validation.status); ``` ```python Python theme={null} import requests validation_id = '550e8400-e29b-41d4-a716-446655440000' response = requests.get( f'https://api.gu1.ai/api/kyc/validations/{validation_id}', headers={ 'Authorization': 'Bearer YOUR_API_KEY' } ) validation = response.json() # Extract the URL to share with customer verification_url = validation['providerSessionUrl'] print('Share this URL with your customer:', verification_url) # Check current status print('Current status:', validation['status']) ``` ```curl cURL theme={null} curl -X GET https://api.gu1.ai/api/kyc/validations/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Alternative: Get Current Validation for Entity If you don't have the validation ID but have the entity ID, you can get the current validation: ### Endpoint ``` GET https://api.gu1.ai/api/kyc/entities/{entityId}/current ``` ### Example ```javascript Node.js theme={null} const entityId = '123e4567-e89b-12d3-a456-426614174000'; const response = await fetch( `https://api.gu1.ai/api/kyc/entities/${entityId}/current`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const validation = await response.json(); const verificationUrl = validation.providerSessionUrl; ``` ```python Python theme={null} entity_id = '123e4567-e89b-12d3-a456-426614174000' response = requests.get( f'https://api.gu1.ai/api/kyc/entities/{entity_id}/current', headers={'Authorization': 'Bearer YOUR_API_KEY'} ) validation = response.json() verification_url = validation['providerSessionUrl'] ``` ## Sharing the URL with Customers Once you have the verification URL, you can share it with your customer through various channels: ### Email Example ```html theme={null}

Hi {{customerName}},

Please complete your identity verification to continue:

Verify Your Identity

This link will expire in 7 days.

``` ### SMS Example ``` Complete your identity verification here: {{providerSessionUrl}} ``` ### In-App Integration ```javascript theme={null} // Redirect user to verification window.location.href = providerSessionUrl; // Or open in new window window.open(providerSessionUrl, '_blank'); // Or embed in iframe