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

# 为 Lovable 应用添加 KYC（Didit）

> 使用 Didit 为 Lovable 应用添加 KYC、年龄估算或 AML 筛查：借助两个 Supabase Edge Functions 和可直接复制的提示词，并在 Lovable 聊天中使用 Didit MCP。

Didit 通过两个服务端函数为使用 Lovable 构建的应用添加身份验证（KYC）、年龄验证和 AML 筛查。其中一个函数创建 Didit 验证会话并返回其链接，另一个函数接收 Didit 已签名的 Webhook，并将该用户的结果保存到您的数据库中。

您还可以将 Didit MCP 服务器连接到 Lovable 的聊天功能。这样，Lovable 的智能体在构建应用时，就能在您的 Didit 账户中创建工作流、测试会话和 Webhook 目标。

本页为每个步骤提供一段可粘贴到 Lovable 中的提示词，以及该提示词应生成的代码，方便您核对 Lovable 生成的内容。

***

## 工作原理

所有涉及您 Didit API 密钥的操作都在服务器端运行，具体是在 Supabase Edge Functions 中运行（即 Lovable Cloud 或已连接 Supabase 的项目的后端）。
浏览器永远不会接触到该密钥。

1. 已登录的用户点击 **验证我的身份**。前端调用 `didit-create-session` 函数。
2. 该函数使用您的工作流 ID、用户 ID（作为 `vendor_data`）和 `callback` URL 调用 [`POST /v3/session/`](https://docs.didit.me/zh/sessions-api/create-session)，并返回会话的 `url`。如果用户最近一次的会话尚未完成，则改为返回该会话的链接。
3. 前端将用户跳转到该 `url`。Didit 的托管验证页面会执行您工作流中的检查，然后将用户重定向到 `callback` URL。
4. Didit 向 `didit-webhook` 函数发送 `status.updated` [Webhook](https://docs.didit.me/zh/integration/webhooks.md)。该函数会验证签名，从 Didit 读取会话的当前决策，然后将状态（`Approved`、`Declined`、`In Review` 等）和 `environment`（`live` 或 `sandbox`）保存到您的 `user_verifications` 表中，之后才返回 `200`。
5. 您的应用从自己的数据库读取状态。它绝不信任重定向 URL 中的状态。

***

## 开始之前

**1. 创建 Didit 账户和工作流**

在 [business.didit.me](https://business.didit.me) 注册。在 **Workflows** 下，从模板创建一个工作流，并复制其 **workflow ID**。工作流决定用户需要完成的步骤（参见 [选择要验证的内容](#选择要验证的内容)）。

**2. 复制 API 密钥**

在 **Developers** 下点击 **API keys**，为应用复制一个 API 密钥。参见 [API 密钥](https://docs.didit.me/zh/console/api-keys.md)，了解如何只授予其所需的访问权限。

**3. 让您的 Lovable 项目具备用户和后端**

您的项目需要登录功能（使每位用户都有 ID），以及一个运行 Edge Functions 的后端。Lovable Cloud 同时提供这两项；连接的 Supabase 项目使用方式相同。

### 选择要验证的内容

您通过选择工作流来决定验证项。本页的代码不会改变，只需更改工作流 ID。

| 您的需求 | 工作流 | 用户的操作 |
| - | - | - |
| 完整 KYC | **KYC** 模板，包含[身份证件验证](https://docs.didit.me/zh/core-technology/id-verification/overview.md)、[活体检测](https://docs.didit.me/zh/core-technology/liveness/overview.md)和[人脸比对](https://docs.didit.me/zh/core-technology/face-match/overview.md) | 扫描身份证件，并拍摄一张实时自拍，与证件照片进行比对 |
| 年龄验证 | **Adaptive Age Verification** 模板（[年龄估算](https://docs.didit.me/zh/core-technology/age-estimation/overview.md)） | 拍摄自拍；只有年龄接近您设定的年龄阈值的用户才需要提供身份证件 |
| 结合 AML 的 KYC | 添加了[AML 筛查](https://docs.didit.me/zh/core-technology/aml-screening/overview.md)的 **KYC** 模板 | 与完整 KYC 相同；Didit 还会根据制裁名单、政治公众人物（PEP）名单和负面新闻名单对该人员进行筛查 |

查看所有模板和功能，请参阅[工作流](https://docs.didit.me/zh/console/workflows.md)；了解每项验证的费用，请参阅[定价](https://docs.didit.me/zh/getting-started/pricing.md)。

***

## 第 1 部分: 将 Didit 添加到您的 Lovable 应用

### 第 1 步: 存储您的密钥

将这些值添加为项目的密钥（在 Lovable 中，让它添加一个密钥，或在后端的密钥设置中添加）。切勿把它们放入前端代码或 `VITE_` 变量：前端中的任何内容都是公开的。

| 密钥 | 值 |
| - | - |
| `DIDIT_API_KEY` | 来自 **Developers > API keys** 的 API 密钥。两个函数都会使用它 |
| `DIDIT_WORKFLOW_ID` | 来自 **Workflows** 的工作流 ID |
| `DIDIT_WEBHOOK_SECRET` | Webhook 目标的签名密钥（您在 [第 4 步](#第-4-步-在-didit-中注册-webhook) 中创建它） |
| `APP_URL` | 您应用的公开地址，例如 `https://your-app.lovable.app` |

将以下内容粘贴到 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.
```

### 第 2 步: 创建验证会话

将以下内容粘贴到 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.
````

该函数应如下所示：

```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 });
});
```

按钮代码：

```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();
```

完成页面会等待 Webhook，因为用户可能先于 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]
>
> 当用户跟踪的会话仍未完成（`Not Started`、`In Progress`、`In Review`、`Resubmitted`）时，函数会返回该会话的链接，且不会创建新会话，因此等待贵团队审核的用户会留在正在审核的会话上。函数会从 Didit 读取状态，因为 Webhook 可能尚未到达。只有在 `Declined`、`Abandoned`、`Expired`、`Kyc Expired` 或沙盒批准之后，它才会创建新会话；生产环境批准之后则返回 `409`。对于用户验证（KYC）工作流，当两次调用发生竞争时，Didit 也会返回已存在的未完成会话，因此双击不会创建两个会话；企业验证（KYB）工作流则每次调用都会创建新会话。如果您的应用限制了**允许的域名**，则 `callback` 必须位于其中之一。请参阅[创建会话](https://docs.didit.me/zh/sessions-api/create-session.md)。

希望让用户留在您的应用内？请在 Didit 的 [JavaScript SDK](https://docs.didit.me/zh/integration/web-sdks/javascript-sdk.md) 弹窗中打开同一个 `url`，而不是进行跳转。

### 第 3 步: 接收结果

将以下内容粘贴到 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.
```

该函数应如下所示。它遵循 Webhook 页面中的 [签名验证](https://docs.didit.me/zh/integration/webhooks.md#签名验证) 方式，使用 `X-Signature`，即 Didit 所发送的确切字节的 HMAC。`X-Signature-V2` 适用于在代码读取前会重新编码请求体的框架；Edge Function 通过 `req.arrayBuffer()` 读取未经修改的字节，因此无需规范化 JSON（那样就必须逐字节复现 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]
>
> 关闭 JWT 验证仅适用于此函数：Didit 无法发送 Supabase 令牌，因此 HMAC 签名才是证明请求来自 Didit 的依据。请为 `didit-create-session` 保持开启 JWT 验证。

该代码可防范以下情况：

* **延迟或重复的投递。** Didit 不保证[投递顺序](https://docs.didit.me/zh/integration/webhooks.md#投递顺序)，并会重试失败的投递。函数会将每次投递视为一个信号，并按 Webhook 页面的建议，从 [`GET /v3/session/{session_id}/decision/`](https://docs.didit.me/zh/sessions-api/retrieve-session) 保存会话的当前决策，因此延迟的投递不会让其所携带的状态重新出现。
* **其他会话。** 更新会匹配用户跟踪的 `session_id`，因此较早会话的结果绝不会替换用户最近发起的会话。发起新会话会将该记录重置为 `Not Started`。
* **重放攻击。** `X-Timestamp` 本身不参与签名，因此函数在应用 5 分钟时间窗口之前，还要求已签名请求体中的 `timestamp` 与其相等。
* **丢失的决策。** 只有在决策保存之后，函数才会返回 `200`。保存失败则返回 `500`，Didit 会在约 5 分钟内[重试](https://docs.didit.me/zh/integration/webhooks.md#重试策略)两次；此后，请从目标的 **Deliveries** 选项卡中重新发送该投递。

有关完整负载、所有状态值及其他事件，请参阅 [Webhook](https://docs.didit.me/zh/integration/webhooks.md)。

### 第 4 步: 在 Didit 中注册 Webhook

1. 在 Business Console 中，进入 **Developers**，然后进入 **Webhooks**，并添加一个目标。
2. 将其 URL 设置为您的函数地址：`https://<your-project-ref>.supabase.co/functions/v1/didit-webhook`。
3. 订阅 `status.updated` 事件。
4. 将其签名密钥复制到 `DIDIT_WEBHOOK_SECRET` 密钥中。
5. 从该目标发送一个测试 Webhook。函数会返回 `200`；由于测试投递携带 `X-Didit-Test-Webhook: true`，因此不会写入任何内容。

您也可以使用 [`POST /v3/webhook/destinations/`](https://docs.didit.me/zh/integration/webhooks) 创建该目标，或让 Lovable 的 Agent 通过 Didit MCP 服务器完成此操作（见[第 2 部分](#第-2-部分：在-lovable-聊天中使用-didit)）。

### 第 5 步: 端到端测试

1. 在构建期间请使用[沙盒应用](https://docs.didit.me/zh/integration/sandbox-testing.md)，这样不会产生真实检查的费用。目前，其 API 密钥、工作流 ID 和 Webhook 目标密钥就是您密钥的取值。
2. 登录您的应用，点击 **验证我的身份**，并完成托管流程。
3. 返回 `/verification-complete` 后，一旦 Webhook 到达，页面就会显示 `Approved`、`Declined` 或 `In Review`，并因其 `environment` 为 `sandbox` 而标注为测试结果。当您的团队在控制台中作出决定时，处于 `In Review` 的会话会再次变化，Webhook 也会再次更新该记录；在此之前，用户看到的是其验证正在审核中。
4. 对需要已验证用户的功能设置访问控制：仅当 `status = 'Approved'` **且** `environment = 'live'` 时才开放，并在服务器端或通过行级安全策略进行读取，而不能只在前端判断。沙盒批准永远不会解锁这些功能。

### 第 6 步: 正式上线

沙盒和生产环境是两个独立的应用，各自拥有独立的 API 密钥、工作流和 Webhook 目标，因此请三项同时切换：

1. 在您的生产环境应用中，发布您测试过的工作流，并复制其工作流 ID。
2. 复制生产环境应用的一个 API 密钥。
3. 在生产环境应用中添加一个 Webhook 目标，使用相同的 `didit-webhook` URL，订阅 `status.updated`，并复制其签名密钥。
4. 同时将 `DIDIT_API_KEY`、`DIDIT_WORKFLOW_ID` 和 `DIDIT_WEBHOOK_SECRET` 替换为这三个值，并重新部署两个函数。生产环境密钥无法在沙盒工作流上发起会话，沙盒目标也永远不会收到生产环境的决策。
5. 清除沙盒结果，以免停留在 `In Review` 的测试会话阻止其用户发起生产环境会话：

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

   随后，每位用户都需要在生产环境中的会话里再次验证：沙盒中的通过结果不计入，新会话从 `Not Started` 状态开始。

***

## 第 2 部分：在 Lovable 聊天中使用 Didit

Lovable 的智能体可以使用自定义 MCP 服务器。谁可以添加服务器，请参阅 Lovable 的[自定义 MCP 服务器](https://docs.lovable.dev/integrations/custom-mcp)页面。添加托管的 Didit MCP 服务器后，Lovable 智能体就能在您构建应用时读取并修改您的 Didit 账户，例如创建工作流、注册 Webhook 目标、发起测试会话。

> [!NOTE]
>
> MCP 连接只为 Lovable 的**聊天**提供上下文。它从不属于您发布的应用，该应用通过 [第 1 部分](#第-1-部分-将-didit-添加到您的-lovable-应用) 中的函数与 Didit 通信。

1. 在 Lovable 中打开 **Connectors**，选择 **Add custom**，然后选择 **MCP server**。如果 **MCP server** 显示为灰色，说明工作区管理员已关闭 **Custom MCP** 设置。
2. **Server name:** `Didit`。
3. **Server URL:** `https://mcp.didit.me/mcp`。
4. 保持 **OAuth** 为身份验证方式，然后点击 **Add & authorize**。
5. 在打开的窗口中完成 **Log in with Didit**，并批准 Lovable 可以使用的组织。

此后，该服务器会出现在您的聊天连接器中。此连接属于个人：每位需要使用的团队成员都需要自行连接。

> [!NOTE]
>
> **无需 API 密钥。** 使用 OAuth 时，服务器以您的身份行事，作用范围为您在登录时批准的组织，并受您角色的权限约束。如果要改用应用 API 密钥进行连接，请选择 **Bearer token or API key**，粘贴密钥后点击 **Add server**：服务器会将其作为 bearer token 接受。请参阅[身份验证](https://docs.didit.me/zh/integration/mcp/authentication.md)。

### 检查是否正常工作

在 Lovable 聊天中输入：

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

然后让它开始工作：

* "创建一个沙盒 KYC 工作流，包含身份证件验证、活体检测和人脸比对，并把工作流 ID 告诉我。"
* "为 status.updated 注册一个 Didit Webhook 目标，指向我的 didit-webhook Edge Function，并告诉我在哪里找到它的签名密钥。"
* "为我的用户 ID 创建一个测试会话，并把验证链接发给我。"

Lovable 会直接运行只读工具；对于会进行修改的任何工具，它会先请求您的批准。

### 故障排除

* **登录失败或不断循环。** 请先在同一浏览器中登录 [business.didit.me](https://business.didit.me)，然后再次点击 **Add & authorize**。
* **某个工具返回 `missing_scope`。** 您在该组织中的角色缺少相应权限。请参阅[角色和权限](https://docs.didit.me/zh/integration/mcp/authentication.md#角色与权限)。
* **Webhook 函数返回 `401`。** 请检查 `DIDIT_WEBHOOK_SECRET` 是否为发送 Webhook 的目标的密钥，函数是否以 `verify_jwt = false` 部署，以及在任何解析或重新编码之前，函数是否使用 `req.arrayBuffer()` 读取请求体。如果时间戳检查返回 `401`，说明该投递已超过五分钟，或服务器时钟有误。
* **`didit-create-session` 返回 `409`。** Didit 报告该用户所跟踪的会话已在生产环境中通过。页面会重新读取该记录，而该记录由 Webhook 更新。
* **`didit-create-session` 返回 `502`。** 无法连接到 Didit，或者未完成的会话没有可继续的链接。不会创建任何新会话；请重试。
* **会话请求在 `callback` 上返回 `400`。** 请将您应用的地址添加到应用的允许域名中，或检查 `APP_URL`。

***

## 后续步骤

> [card] [Webhooks](https://docs.didit.me/zh/integration/webhooks.md)
>
> 所有事件、payload 字段和签名请求头。

> [card] [创建会话](https://docs.didit.me/zh/sessions-api/create-session.md)
>
> 所有请求字段，例如预期的详细信息和元数据。

> [card] [MCP 工具参考](https://docs.didit.me/zh/integration/mcp/tools.md)
>
> Lovable 的智能体可以调用的所有工具，逐一列出。

> [card] [定价](https://docs.didit.me/zh/getting-started/pricing.md)
>
> 工作流中每项检查的费用。


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