> ## Documentation Index
> Fetch the complete documentation index at: https://docs.didit.me/llms.txt
> Use this file to discover all available pages before exploring further.

# KYC en Lovable: añade verificación de identidad con Didit

> Añade KYC, verificación de edad o análisis AML con Didit a una app de Lovable con dos Edge Functions de Supabase y usa el MCP de Didit en el chat.

Didit añade verificación de identidad (KYC), verificación de edad y análisis AML a una aplicación creada en Lovable mediante dos funciones del lado del servidor: una crea una sesión de verificación de Didit y devuelve su enlace, y la otra recibe el webhook firmado de Didit y guarda el resultado de ese usuario en tu base de datos.

También puedes conectar el servidor MCP de Didit al chat de Lovable, para que el agente de Lovable pueda crear flujos de verificación (workflow), sesiones de prueba y destinos de webhook en tu cuenta de Didit mientras desarrolla la aplicación.

Esta página incluye un prompt para pegar en Lovable en cada paso y el código que ese prompt debería generar, para que puedas comprobar lo que ha escrito Lovable.

***

## Cómo funciona

Todo lo que usa tu clave de API de Didit se ejecuta en el servidor, en Supabase Edge Functions (el backend de un proyecto de Lovable Cloud o conectado a Supabase).
El navegador nunca ve la clave.

1. Un usuario que ha iniciado sesión hace clic en **Verificar mi identidad**. El frontend llama a la función `didit-create-session`.
2. La función llama a [`POST /v3/session/`](https://docs.didit.me/es/sessions-api/create-session) con el ID de tu flujo de verificación (workflow), el ID del usuario como `vendor_data` y una URL de `callback`, y devuelve la `url` de la sesión. Si la última sesión del usuario todavía no ha terminado, devuelve el enlace de esa sesión.
3. El frontend envía al usuario a esa `url`. La página de verificación alojada de Didit ejecuta las comprobaciones de tu flujo y, después, redirige al usuario a la URL de `callback`.
4. Didit envía un [webhook](https://docs.didit.me/es/integration/webhooks.md) `status.updated` a la función `didit-webhook`. La función verifica la firma, lee de Didit la decisión actual de la sesión y guarda su estado (`Approved`, `Declined`, `In Review`, etc.) y el `environment` (`live` o `sandbox`) en tu tabla `user_verifications`. Solo entonces responde `200`.
5. Tu aplicación lee el estado desde su propia base de datos. Nunca confía en el estado que aparece en la URL de redirección.

***

## Antes de empezar

**1. Crea una cuenta en Didit y un flujo de verificación (workflow)**

Regístrate en [business.didit.me](https://business.didit.me). En **Workflows**, crea un flujo a partir de una plantilla y copia su **ID del flujo**. El flujo determina el proceso que seguirá el usuario (consulta [Elige qué verificar](#elige-qué-verificar)).

**2. Copia una clave de API**

En **Developers** y luego en **API keys**, copia una clave de API para la aplicación. Consulta [Claves de API](https://docs.didit.me/es/console/api-keys.md) para darle solo el acceso que necesita.

**3. Ten usuarios y un backend en tu proyecto de Lovable**

Tu proyecto necesita inicio de sesión (para que cada usuario tenga un ID) y un backend que ejecute Edge Functions. Lovable Cloud te ofrece ambas cosas; un proyecto de Supabase conectado funciona de la misma manera.

### Elige qué verificar

Eliges las comprobaciones al elegir el flujo. El código de esta página no cambia; solo cambia el ID del flujo.

| Lo que necesitas | Flujo | Lo que hace el usuario |
| - | - | - |
| KYC completo | Plantilla **KYC** con [verificación de identidad](https://docs.didit.me/es/core-technology/id-verification/overview.md), [prueba de vida](https://docs.didit.me/es/core-technology/liveness/overview.md) y [coincidencia facial](https://docs.didit.me/es/core-technology/face-match/overview.md) | Escanea un documento de identidad y se toma un selfie en vivo que se compara con la foto del documento |
| Verificación de edad | Plantilla **Adaptive Age Verification** ([estimación de edad](https://docs.didit.me/es/core-technology/age-estimation/overview.md)) | Se toma un selfie; solo se pide un documento de identidad a los usuarios cercanos a tu umbral de edad |
| KYC con AML | Plantilla **KYC** con [análisis AML](https://docs.didit.me/es/core-technology/aml-screening/overview.md) añadido | Igual que el KYC completo; Didit también contrasta a la persona con las listas de sanciones, PEP y medios adversos |

Consulta [Workflows](https://docs.didit.me/es/console/workflows.md) para ver todas las plantillas y funciones, y [Precios](https://docs.didit.me/es/getting-started/pricing.md) para saber cuánto cuesta cada comprobación.

***

## Parte 1: Añade Didit a tu aplicación de Lovable

### Paso 1: Guarda tus secretos

Añádelos como secretos de tu proyecto (en Lovable, pide que añada un secreto, o añádelo en la configuración de secretos de tu backend). Nunca los pongas en código de frontend ni en una variable `VITE_`: todo lo que está en el frontend es público.

| Secreto | Valor |
| - | - |
| `DIDIT_API_KEY` | La clave de API de **Developers > API keys**. Ambas funciones la usan |
| `DIDIT_WORKFLOW_ID` | El ID del flujo de verificación (workflow) de **Workflows** |
| `DIDIT_WEBHOOK_SECRET` | El secreto de firma de tu destino de webhook (lo creas en el [Paso 4](#paso-4-registra-el-webhook-en-didit)) |
| `APP_URL` | La dirección pública de tu aplicación, por ejemplo `https://your-app.lovable.app` |

Pega esto en Lovable:

```text theme={null}
Add four backend secrets to this project: DIDIT_API_KEY, DIDIT_WORKFLOW_ID, DIDIT_WEBHOOK_SECRET and APP_URL. Ask me for their values. They must only ever be read inside Edge Functions with Deno.env.get, never in frontend code.
```

### Paso 2: Crea la sesión de verificación

Pega esto en Lovable:

````text theme={null}
Add identity verification with Didit.

1. Database: run this SQL migration exactly as written.

```sql
-- One row per user who started a verification. Users read their own row; only the two functions below write it.
create table public.user_verifications (
  user_id uuid primary key references auth.users (id) on delete cascade,
  session_id text not null,        -- the Didit session this user started last
  status text not null default 'Not Started',
  environment text,                -- 'live' or 'sandbox', as Didit reports it
  updated_at timestamptz not null default now()
);
alter table public.user_verifications enable row level security;
create policy "Users read their own verification" on public.user_verifications
  for select to authenticated using ((select auth.uid()) = user_id);
-- Data API access: the signed-in user reads their row, the Edge Functions write it with the service role.
grant select on public.user_verifications to authenticated;
grant select, insert, update on public.user_verifications to service_role;
```

2. Create a Supabase Edge Function named didit-create-session that:
   - handles CORS (including OPTIONS) so the frontend can call it with supabase.functions.invoke;
   - reads the signed-in user from the Authorization header with supabase.auth.getUser(); returns 401 if there is none;
   - reads the user's row with the service role key (returns 500 if that read fails);
   - when the row has a session_id, reads GET https://verification.didit.me/v3/session/{session_id}/decision/ with
     the header x-api-key: DIDIT_API_KEY, and decides from Didit's answer, not from the row:
     - status 'Approved' with environment 'live': returns 409 with { status, environment };
     - status 'Declined', 'Abandoned', 'Expired' or 'Kyc Expired', a sandbox 'Approved', or a 404: goes on to create
       a new session;
     - any other status (Not Started, In Progress, In Review, Resubmitted and so on): returns { "url": <its
       session_url> } and never creates a new session; returns 502 if it has no session_url;
     - any other error: returns 502;
   - to create a session, calls POST https://verification.didit.me/v3/session/ with the header x-api-key: DIDIT_API_KEY
     and the JSON body { "workflow_id": DIDIT_WORKFLOW_ID, "vendor_data": <the user's id>,
     "callback": APP_URL + "/verification-complete" };
   - upserts the user's row with the new session_id, status 'Not Started' and environment null; returns 500 without
     the link if that write fails;
   - returns { "url": <the url field of Didit's response> }. The field is called url, not verification_url.
   Never accept the user id from the request body, and never send DIDIT_API_KEY to the browser.

3. Frontend: on the account page, read the user's row from user_verifications. The user is verified only when
   status = 'Approved' AND environment = 'live'. When environment is 'sandbox', show the status labelled "Test result".
   When status is 'In Review', show "Your verification is being reviewed" and no button.
   Otherwise, if the user is not verified, show a "Verify my identity" button that calls didit-create-session and
   then does window.location.href = url. On a 409 answer, re-read the user's row and show its status.
   Add a /verification-complete page that says "Thanks, we're checking your verification" and re-reads the user's
   status and environment every 3 seconds until status is 'Approved', 'Declined' or 'In Review', for up to 2 minutes;
   if it is still pending after that, show a "Refresh" button. If a read fails, stop and show "Try again" (or
   "Sign in" when the user is signed out), not the pending message. Do not trust the status query parameter Didit
   adds to that URL.
````

La función debería verse así:

```typescript supabase/functions/didit-create-session/index.ts theme={null}
import { createClient } from "npm:@supabase/supabase-js@2";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

// Sessions that allow a new attempt. A sandbox approval does too; a live approval does not.
const CAN_RETRY = ["Declined", "Abandoned", "Expired", "Kyc Expired"];

function json(body: unknown, status = 200) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { ...corsHeaders, "Content-Type": "application/json" },
  });
}

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

  // Who is asking: the signed-in user, from their own session token.
  const supabase = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_ANON_KEY")!,
    { global: { headers: { Authorization: req.headers.get("Authorization") ?? "" } } },
  );
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return json({ error: "Not signed in" }, 401);

  const admin = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
  );
  const didit = { "x-api-key": Deno.env.get("DIDIT_API_KEY")!, "Content-Type": "application/json" };

  const { data: current, error: readError } = await admin
    .from("user_verifications")
    .select("session_id")
    .eq("user_id", user.id)
    .maybeSingle();
  if (readError) return json({ error: "Could not start verification" }, 500);

  // Ask Didit how the tracked session stands: its webhook may not have arrived yet.
  if (current) {
    const check = await fetch(
      `https://verification.didit.me/v3/session/${encodeURIComponent(current.session_id)}/decision/`,
      { headers: didit },
    );
    if (check.ok) {
      const tracked = await check.json();
      if (tracked.status === "Approved" && tracked.environment === "live") {
        return json({ error: "Already verified", status: tracked.status, environment: tracked.environment }, 409);
      }
      // Unfinished (Not Started, In Progress, In Review, Resubmitted): resume it, never start a second one.
      if (!CAN_RETRY.includes(tracked.status) && tracked.status !== "Approved") {
        return tracked.session_url
          ? json({ url: tracked.session_url })
          : json({ error: "Could not resume verification" }, 502);
      }
    } else if (check.status !== 404) {
      // 404: the session no longer exists, so a new one is fine. Anything else: do not guess.
      return json({ error: "Could not start verification" }, 502);
    }
  }

  const response = await fetch("https://verification.didit.me/v3/session/", {
    method: "POST",
    headers: didit,
    body: JSON.stringify({
      workflow_id: Deno.env.get("DIDIT_WORKFLOW_ID"),
      vendor_data: user.id,
      callback: `${Deno.env.get("APP_URL")}/verification-complete`,
    }),
  });
  const session = await response.json();
  if (!response.ok) {
    console.error("Didit session error", response.status, session);
    return json({ error: "Could not start verification" }, 502);
  }

  // Track the new session before handing out its link: the webhook saves results for this session only.
  const { error } = await admin.from("user_verifications").upsert({
    user_id: user.id,
    session_id: session.session_id,
    status: "Not Started",
    environment: null,
    updated_at: new Date().toISOString(),
  });
  if (error) return json({ error: "Could not start verification" }, 500);

  return json({ url: session.url });
});
```

El botón:

```typescript theme={null}
const { data, error } = await supabase.functions.invoke("didit-create-session");
if (data?.url) window.location.href = data.url;
else if (error?.context?.status === 409) await loadVerification(); // Re-read the user's row and show its status.
else showError();
```

La página de finalización espera al webhook, porque el usuario puede llegar antes de que llegue el webhook:

```typescript theme={null}
// Re-read the user's own row every 3 seconds, for up to 2 minutes.
const SETTLED = ["Approved", "Declined", "In Review"];
type Decision = { status: string; environment: string | null };
async function waitForDecision(userId: string): Promise<Decision | "pending" | "error"> {
  for (let attempt = 0; attempt < 40; attempt++) {
    const { data, error } = await supabase
      .from("user_verifications")
      .select("status, environment")
      .eq("user_id", userId)
      .maybeSingle();
    // A failed read is not a pending decision: show "Try again", or "Sign in" when the user is signed out.
    if (error) return "error";
    // environment 'sandbox' is labelled "Test result".
    if (data && SETTLED.includes(data.status)) return data;
    await new Promise((resolve) => setTimeout(resolve, 3000));
  }
  return "pending"; // Still pending: show a Refresh button.
}
```

> [!NOTE]
>
> Mientras la sesión que sigue el usuario esté sin terminar (`Not Started`, `In Progress`, `In Review`, `Resubmitted`), la función devuelve el enlace de esa sesión y no crea ninguna nueva, de modo que un usuario que espera la revisión de tu equipo permanece en la sesión que se está revisando. Lee el estado desde Didit, porque el webhook podría no haber llegado todavía. Crea una sesión nueva solo después de `Declined`, `Abandoned`, `Expired`, `Kyc Expired` o una aprobación en sandbox, y responde `409` después de una aprobación en producción. En un flujo de Verificación de usuarios (KYC), Didit también devuelve la sesión sin terminar existente cuando dos llamadas compiten entre sí, de modo que un doble clic no crea dos sesiones; un flujo de Verificación de empresas crea una sesión nueva en cada llamada. Si tu aplicación restringe los **dominios permitidos**, el `callback` debe estar en uno de ellos. Consulta [Crear sesión](https://docs.didit.me/es/sessions-api/create-session.md).

¿Prefieres mantener al usuario dentro de tu aplicación? Abre la misma `url` en el modal del [SDK de JavaScript](https://docs.didit.me/es/integration/web-sdks/javascript-sdk.md) de Didit en lugar de redirigir.

### Paso 3: Recibe el resultado

Pega esto en Lovable:

```text theme={null}
Create a Supabase Edge Function named didit-webhook that receives Didit webhooks. It is called by Didit, not by a
signed-in user, so deploy it without JWT verification (verify_jwt = false for this function in supabase/config.toml).

For each POST request:
1. Read the body as raw bytes with req.arrayBuffer(). Do not call req.json() and do not re-serialize the body
   before the signature check. Parse it with JSON.parse only to read its fields.
2. Signature: compute HMAC-SHA256 with DIDIT_WEBHOOK_SECRET, hex encoded, over the raw bytes, and compare it in
   constant time (timingSafeEqual from node:crypto, on TextEncoder bytes; Deno has no global Buffer) with the
   X-Signature header and, when present, X-Signature-Previous. Return 401 if neither matches. Parse the body only
   after this check.
3. Timestamp: return 401 unless X-Timestamp is an integer, the body's timestamp field equals it, and
   abs(now_in_seconds - X-Timestamp) <= 300.
4. Return 200 without writing anything when the header X-Didit-Test-Webhook is "true" or webhook_type is not
   "status.updated", or when vendor_data is not a user id (a UUID).
5. Do not save the status from the body: deliveries can arrive late or out of order. Read the session's current
   decision with GET https://verification.didit.me/v3/session/{session_id}/decision/ and the header
   x-api-key: DIDIT_API_KEY. Return 200 on a 404 (the session no longer exists) and 500 on any other error.
6. With the service role key, update user_verifications set status and environment from that decision, and
   updated_at = now(), where user_id = vendor_data from the body and session_id = session_id from the body.
   No ordering logic: the decision Didit returns is the current one.
7. Return 200 only after the update succeeds. If it fails, return 500 so Didit retries the delivery.
```

La función debería verse así. Sigue la [verificación de firma](https://docs.didit.me/es/integration/webhooks.md#verificación-de-firma) de la página de Webhooks con `X-Signature`, el HMAC de los bytes exactos que envió Didit. `X-Signature-V2` existe para marcos de trabajo que vuelven a codificar el cuerpo antes de que tu código lo vea; una Edge Function lee los bytes sin modificar con `req.arrayBuffer()`, así que no necesita JSON canónico, que tendría que reproducir byte a byte el formato numérico propio de Didit.

```typescript supabase/functions/didit-webhook/index.ts theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";
import { createClient } from "npm:@supabase/supabase-js@2";

const SECRET = Deno.env.get("DIDIT_WEBHOOK_SECRET")!;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const encoder = new TextEncoder();

// Constant-time comparison of two hex digests, as bytes.
function sameDigest(expected: string, received: string | null): boolean {
  if (!received) return false;
  const a = encoder.encode(expected);
  const b = encoder.encode(received);
  return a.length === b.length && timingSafeEqual(a, b);
}

const ok = () => Response.json({ ok: true });
const reject = (message: string) => new Response(message, { status: 401 });
const retry = (message: string) => new Response(message, { status: 500 });

Deno.serve(async (req) => {
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });

  // 1. The exact bytes Didit sent.
  const raw = new Uint8Array(await req.arrayBuffer());

  // 2. Signature over those bytes. X-Signature-Previous is sent for 24 hours after you rotate the signing secret.
  const digest = createHmac("sha256", SECRET).update(raw).digest("hex");
  if (
    !sameDigest(digest, req.headers.get("X-Signature")) &&
    !sameDigest(digest, req.headers.get("X-Signature-Previous"))
  ) {
    return reject("Invalid signature");
  }
  const body = JSON.parse(new TextDecoder().decode(raw));

  // 3. Freshness, from the signed body: its timestamp must match X-Timestamp and be under 5 minutes old.
  const timestamp = Number(req.headers.get("X-Timestamp"));
  if (
    !Number.isInteger(timestamp) ||
    body.timestamp !== timestamp ||
    Math.abs(Date.now() / 1000 - timestamp) > 300
  ) {
    return reject("Stale or mismatched timestamp");
  }

  // 4. Test deliveries carry sample data, and this app stores session results only.
  if (req.headers.get("X-Didit-Test-Webhook") === "true") return ok();
  if (body.webhook_type !== "status.updated") return ok();
  if (!UUID.test(String(body.vendor_data ?? ""))) {
    console.warn("status.updated without an app user id", body.session_id);
    return ok();
  }

  // 5. Didit is the source of truth: read the session's current decision, not the event's status.
  const check = await fetch(
    `https://verification.didit.me/v3/session/${encodeURIComponent(body.session_id)}/decision/`,
    { headers: { "x-api-key": Deno.env.get("DIDIT_API_KEY")! } },
  );
  if (check.status === 404) return ok();
  if (!check.ok) return retry("Could not read the decision");
  const decision = await check.json();

  // 6. Save it on the user's row, only for the session the user started last.
  const admin = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
  );
  const { error } = await admin
    .from("user_verifications")
    .update({ status: decision.status, environment: decision.environment, updated_at: new Date().toISOString() })
    .eq("user_id", body.vendor_data)
    .eq("session_id", body.session_id);

  // 7. Acknowledge only what is saved: a 500 makes Didit retry the delivery.
  if (error) {
    console.error("Could not save the Didit decision", body.event_id, error);
    return retry("Could not save");
  }
  return ok();
});
```

```toml supabase/config.toml theme={null}
[functions.didit-webhook]
verify_jwt = false
```

> [!WARNING]
>
> Desactivar la verificación de JWT es correcto solo para esta función: Didit no puede enviar un token de Supabase, así que la firma HMAC es lo que demuestra que la solicitud procede de Didit. Mantén activada la verificación de JWT para `didit-create-session`.

Lo que protege el código:

* **Entregas tardías o repetidas.** Didit no garantiza el [orden de entrega](https://docs.didit.me/es/integration/webhooks.md#orden-de-entrega) y reintenta una entrega fallida. La función trata cada entrega como una señal y guarda la decisión actual de la sesión desde [`GET /v3/session/{session_id}/decision/`](https://docs.didit.me/es/sessions-api/retrieve-session), como recomienda la página de Webhooks, de modo que una entrega tardía no restaura el estado que traía.
* **Otras sesiones.** La actualización coincide con el `session_id` que sigue el usuario, así que el resultado de una sesión anterior nunca reemplaza a la que el usuario inició por última vez. Iniciar una sesión nueva restablece la fila a `Not Started`.
* **Repeticiones.** `X-Timestamp` no está firmado por sí mismo, así que la función también exige que el `timestamp` del cuerpo firmado sea igual a él antes de aplicar la ventana de 5 minutos.
* **Decisiones perdidas.** La función responde `200` solo después de guardar la decisión. Si el guardado falla, responde `500`, y Didit [reintenta](https://docs.didit.me/es/integration/webhooks.md#política-de-reintentos) dos veces durante unos cinco minutos; después de eso, reenvía la entrega desde la pestaña **Deliveries** del destino.

Para el payload completo, todos los valores de estado y los demás eventos, consulta [Webhooks](https://docs.didit.me/es/integration/webhooks.md).

### Paso 4: Registra el webhook en Didit

1. En la Business Console, ve a **Developers** y después a **Webhooks**, y añade un destino.
2. Configura su URL con tu función: `https://<your-project-ref>.supabase.co/functions/v1/didit-webhook`.
3. Suscríbelo a `status.updated`.
4. Copia su secreto de firma en el secreto `DIDIT_WEBHOOK_SECRET`.
5. Envía un webhook de prueba desde el destino. La función responde `200`, y como las entregas de prueba llevan `X-Didit-Test-Webhook: true`, no escribe nada.

También puedes crear el destino con [`POST /v3/webhook/destinations/`](https://docs.didit.me/es/integration/webhooks), o pedir al agente de Lovable que lo haga a través del servidor MCP de Didit ([Parte 2](#parte-2-usa-didit-en-el-chat-de-lovable)).

### Paso 5: Prueba de extremo a extremo

1. Usa una [aplicación sandbox](https://docs.didit.me/es/integration/sandbox-testing.md) mientras desarrollas, para que no se cobren verificaciones reales. Por ahora, su clave de API, su ID de flujo de verificación y el secreto de su destino de webhook son los valores de tus secretos.
2. Inicia sesión en tu aplicación, haz clic en **Verify my identity** y completa el flujo alojado.
3. De vuelta en `/verification-complete`, la página muestra `Approved`, `Declined` o `In Review` en cuanto llega el webhook, marcado como resultado de prueba porque su `environment` es `sandbox`. Una sesión en `In Review` cambia de nuevo cuando tu equipo toma una decisión al respecto en la consola, y el webhook actualiza la fila otra vez; mientras tanto, el usuario ve que su verificación está en revisión.
4. Restringe las funciones que requieren un usuario verificado a `status = 'Approved'` **y** `environment = 'live'`, leyendo en el servidor o mediante una política de seguridad a nivel de fila, no solo en el frontend. Una aprobación en sandbox nunca las desbloquea.

### Paso 6: Pasa a producción

Sandbox y producción son aplicaciones separadas, cada una con su propia clave de API, flujos de verificación y destinos de webhook, así que cambia las tres a la vez:

1. En tu aplicación de producción, publica el flujo de verificación que probaste y copia su ID.
2. Copia una clave de API de la aplicación de producción.
3. Añade un destino de webhook en la aplicación de producción con la misma URL de `didit-webhook`, suscrito a `status.updated`, y copia su secreto de firma.
4. Reemplaza `DIDIT_API_KEY`, `DIDIT_WORKFLOW_ID` y `DIDIT_WEBHOOK_SECRET` por estos tres valores al mismo tiempo, y vuelve a desplegar ambas funciones. Una clave de producción no puede abrir una sesión en un flujo de sandbox, y un destino de sandbox nunca recibe decisiones de producción.
5. Borra los resultados de sandbox, para que una sesión de prueba que haya quedado en `In Review` no impida a su usuario iniciar una sesión en producción:

   ```sql theme={null}
   delete from public.user_verifications where environment = 'sandbox';
   ```

   Después, cada usuario vuelve a verificarse una vez más en una sesión en producción: una aprobación en sandbox no cuenta, y la nueva sesión comienza en `Not Started`.

***

## Parte 2: Usa Didit en el chat de Lovable

El agente de Lovable puede usar servidores MCP personalizados; consulta la página de Lovable [Custom MCP servers](https://docs.lovable.dev/integrations/custom-mcp) para saber quién puede añadir uno. Añade el servidor MCP alojado de Didit y el agente de Lovable podrá leer y modificar tu cuenta de Didit mientras construyes: crear el flujo de verificación (workflow), registrar el destino de webhook e iniciar una sesión de prueba.

> [!NOTE]
>
> Una conexión MCP solo aporta contexto al **chat** de Lovable. Nunca forma parte de tu aplicación publicada, que se comunica con Didit mediante las funciones de la [Parte 1](#parte-1-añade-didit-a-tu-aplicación-de-lovable).

1. En Lovable, abre **Connectors**, selecciona **Add custom** y elige **MCP server**. Si **MCP server** aparece en gris, un administrador del espacio de trabajo ha desactivado el ajuste **Custom MCP**.
2. **Server name:** `Didit`.
3. **Server URL:** `https://mcp.didit.me/mcp`.
4. Mantén **OAuth** como opción de autenticación y haz clic en **Add & authorize**.
5. Completa **Log in with Didit** en la ventana que se abre y aprueba las organizaciones que Lovable puede usar.

Después, el servidor aparecerá en tus conectores del chat. La conexión es personal: cada compañero de equipo que quiera usarla debe conectarla por su cuenta.

> [!NOTE]
>
> **No necesitas una clave de API.** Con OAuth, el servidor actúa en tu nombre, en las organizaciones que apruebes al iniciar sesión, con los permisos de tu rol. Para conectarlo con una clave de API de la aplicación, elige **Bearer token or API key**, pega la clave y haz clic en **Add server**: el servidor la acepta como token Bearer. Consulta [Autenticación](https://docs.didit.me/es/integration/mcp/authentication.md).

### Comprueba que funciona

En un chat de Lovable, pregunta:

```text theme={null}
Use the Didit MCP server to call didit_context_get and list my organizations and applications.
```

Después, ponlo a prueba:

* "Crea un flujo KYC de sandbox con verificación de identidad, prueba de vida y coincidencia facial, y dame su ID de flujo."
* "Registra un destino de webhook de Didit para status.updated que apunte a mi Edge Function didit-webhook, y dime dónde encontrar su secreto de firma."
* "Crea una sesión de prueba para el ID de mi usuario y dame el enlace de verificación."

Lovable ejecuta las herramientas de solo lectura sin preguntar y te pide aprobación antes de cualquier herramienta que modifique algo.

### Solución de problemas

* **El inicio de sesión falla o se repite.** Inicia sesión primero en [business.didit.me](https://business.didit.me) en el mismo navegador y, a continuación, haz clic de nuevo en **Add & authorize**.
* **Una herramienta responde con `missing_scope`.** Tu rol en esa organización no tiene el permiso necesario. Consulta [roles y permisos](https://docs.didit.me/es/integration/mcp/authentication.md#roles-y-permisos).
* **La función del webhook devuelve `401`.** Comprueba que `DIDIT_WEBHOOK_SECRET` sea el secreto del destino que envía el webhook, que la función esté desplegada con `verify_jwt = false` y que lea el cuerpo con `req.arrayBuffer()` antes de que se analice o se vuelva a codificar. Un `401` en la comprobación de la marca de tiempo significa que la entrega tiene más de cinco minutos de antigüedad o que el reloj del servidor está desajustado.
* **`didit-create-session` devuelve `409`.** Didit indica que la sesión del usuario registrada está aprobada en producción. La página vuelve a leer la fila, que el webhook actualiza.
* **`didit-create-session` devuelve `502`.** No se pudo conectar con Didit, o una sesión sin terminar no tiene un enlace para reanudarla. No se crea nada nuevo; inténtalo de nuevo.
* **La solicitud de sesión devuelve `400` en `callback`.** Añade la dirección de tu aplicación a los dominios permitidos de la aplicación, o revisa `APP_URL`.

***

## Próximos pasos

> [card] [Webhooks](https://docs.didit.me/es/integration/webhooks.md)
>
> Todos los eventos, campos del payload y encabezados de firma.

> [card] [Crear sesión](https://docs.didit.me/es/sessions-api/create-session.md)
>
> Todos los campos de la solicitud, como los detalles esperados y los metadatos.

> [card] [Referencia de herramientas MCP](https://docs.didit.me/es/integration/mcp/tools.md)
>
> Todo lo que puede invocar el agente de Lovable, herramienta por herramienta.

> [card] [Precios](https://docs.didit.me/es/getting-started/pricing.md)
>
> Lo que cuesta cada verificación de tu flujo.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.