> ## 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 AppにDiditでKYCを追加する

> Diditの本人確認、年齢確認、AMLスクリーニングを、2つのSupabase Edge Functionsとコピペ用プロンプトでLovableアプリに追加。Lovableチャットでは Didit MCP も利用可能。

Diditは、Lovableで作成したアプリに本人確認(KYC)、年齢確認、AMLスクリーニングを追加します。仕組みは2つのサーバーサイド関数で構成されています。1つ目はDiditの検証セッションを作成し、そのリンクを返します。2つ目はDiditが送信する署名付きのWebhookを受け取り、その結果をユーザーごとにデータベースへ保存します。

また、Didit MCPサーバーをLovableのチャットに接続できます。そうすると、Lovableのエージェントがアプリを構築する間に、ご自身のDiditアカウントでワークフロー、テストセッション、Webhookの送信先を作成できます。

このページでは、各ステップでLovableに貼り付けるプロンプトと、そのプロンプトによって生成されるはずのコードを紹介します。Lovableが生成したコードを確認できます。

***

## How it works

DiditのAPIキーに関わる処理はすべて、サーバー側の Supabase Edge Functions（Lovable CloudまたはSupabaseに接続されたプロジェクトのバックエンド）で実行されます。
ブラウザがAPIキーを目にすることはありません。

1. サインイン済みのユーザーが**本人確認を行う**をクリックします。フロントエンドが`didit-create-session`関数を呼び出します。
2. 関数は、ワークフローIDとユーザーIDを`vendor_data`として、`callback`のURLを添えて[`POST /v3/session/`](https://docs.didit.me/ja/sessions-api/create-session)を呼び出し、セッションの`url`を返します。ユーザーの直前のセッションがまだ完了していない場合は、そのセッションのリンクを返します。
3. フロントエンドは、ユーザーをその`url`に移動させます。Diditのホスト型ページがワークフローのチェックを実行し、その後ユーザーを`callback`のURLにリダイレクトします。
4. Diditは`status.updated`の[Webhook](https://docs.didit.me/ja/integration/webhooks.md)を`didit-webhook`関数に送信します。関数は署名を検証し、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/ja/console/api-keys.md)を参照してください。

**3. Lovableプロジェクトにユーザーとバックエンドを用意する**

プロジェクトには、ユーザーを識別できるようにサインイン機能（各ユーザーにIDがある状態）と、Edge Functionsを実行できるバックエンドが必要です。Lovable Cloudでは両方が利用できます。接続済みのSupabaseプロジェクトでも同様に動作します。

### 確認内容を選ぶ

確認内容は、ワークフローを選ぶことで決まります。このページのコードは変わらず、変更するのはワークフローIDだけです。

| 必要な確認 | ワークフロー | ユーザーの操作 |
| - | - | - |
| 完全なKYC | **KYC**テンプレート、[本人確認](https://docs.didit.me/ja/core-technology/id-verification/overview.md)、[ライブネス検知](https://docs.didit.me/ja/core-technology/liveness/overview.md)、[顔照合](https://docs.didit.me/ja/core-technology/face-match/overview.md) | ID書類をスキャンし、ライブセルフィーを撮影して書類の写真と照合する |
| 年齢確認 | **Adaptive Age Verification**テンプレート（[年齢推定](https://docs.didit.me/ja/core-technology/age-estimation/overview.md)） | セルフィーを撮影する。年齢のしきい値付近のユーザーだけ、ID書類の提示を求められる |
| AMLを含むKYC | [AMLスクリーニング](https://docs.didit.me/ja/core-technology/aml-screening/overview.md)を追加した**KYC**テンプレート | 完全なKYCと同じ。Diditは、制裁リスト、重要な公的地位を有する者（PEP）、ネガティブメディアのリストに対しても本人をスクリーニングする |

すべてのテンプレートと機能については[ワークフロー](https://docs.didit.me/ja/console/workflows.md)を、各確認の費用については[料金](https://docs.didit.me/ja/getting-started/pricing.md)を参照してください。

***

## パート1: LovableアプリにDiditを追加する

### ステップ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`）の間、関数はそのセッションのリンクを返し、新しいセッションは作成しません。そのため、チームのレビューを待っているユーザーは、レビュー中のセッションのまま維持されます。Webhookがまだ届いていない可能性があるため、関数はDiditからステータスを読み取ります。新しいセッションを作成するのは、`Declined`、`Abandoned`、`Expired`、`Kyc Expired`の後、またはサンドボックスでの承認の後だけです。本番環境での承認の後は`409`を返します。ユーザー認証（KYC）ワークフローでは、2つの呼び出しが競合した場合も、Diditは未完了の既存セッションを返すため、ダブルクリックで2つのセッションが作成されることはありません。法人確認 (KYB)ワークフローでは、呼び出しのたびに新しいセッションを作成します。アプリケーションで**許可ドメイン**を制限している場合、`callback`はそのいずれかに含まれている必要があります。詳しくは[セッションの作成](https://docs.didit.me/ja/sessions-api/create-session.md)を参照してください。

アプリ内にユーザーをとどめたい場合は、リダイレクトする代わりに、同じ`url`をDiditの[JavaScript SDK](https://docs.didit.me/ja/integration/web-sdks/javascript-sdk.md)のモーダルで開いてください。

### ステップ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/ja/integration/webhooks.md#署名検証)に従い、`X-Signature`を使います。これは、Diditが送信した正確なバイト列に対するHMACです。`X-Signature-V2`は、コードがリクエストを受け取る前にフレームワークがボディを再エンコードする場合のためのものです。Edge Functionは`req.arrayBuffer()`で加工されていないバイト列を読み取るため、Diditの数値の書式をバイト単位で再現する必要がある正規化されたJSONは不要です。

```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のトークンを送信できないため、リクエストがDiditから送られたことを証明するのはHMACの署名だけです。`didit-create-session`では、JWT検証をオンのままにしてください。

このコードが防ぐ問題は次のとおりです：

* **遅延した配信や重複した配信。** Diditは[配信順序](https://docs.didit.me/ja/integration/webhooks.md#配信順序)を保証せず、失敗した配信を再試行します。関数は各配信を通知として扱い、Webhookページの推奨どおり、[`GET /v3/session/{session_id}/decision/`](https://docs.didit.me/ja/sessions-api/retrieve-session)からそのセッションの現在の判定を保存します。そのため、遅れて届いた配信によって、その配信が持っていた古いステータスに戻ることはありません。
* **他のセッション。** 更新はユーザーの追跡中の`session_id`と一致したものだけに適用されるため、以前のセッションの結果が、ユーザーが最後に開始したセッションを置き換えることはありません。新しいセッションを開始すると、行は`Not Started`にリセットされます。
* **再送攻撃。** `X-Timestamp`自体は署名されていないため、関数は5分のウィンドウを適用する前に、署名済みボディの`timestamp`がそれと一致することも要求します。
* **判定の取りこぼし。** 関数は判定を保存した後にのみ`200`を返します。保存に失敗すると`500`を返し、Diditは約5分間で2回[再試行](https://docs.didit.me/ja/integration/webhooks.md#再試行ポリシー)します。その後は、送信先の**Deliveries**タブから配信を再送してください。

完全なペイロード、すべてのステータス値、その他のイベントについては、[Webhook](https://docs.didit.me/ja/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/ja/integration/webhooks)で作成することもできます。または、LovableのエージェントにDiditのMCPサーバー（[パート2](#パート2-lovableのチャットでdiditを使う)）を使って作成するよう依頼することもできます。

### ステップ5: エンドツーエンドでテストする

1. 開発中は[サンドボックスアプリケーション](https://docs.didit.me/ja/integration/sandbox-testing.md)を使用してください。実際のチェックには課金されません。当面は、そのAPIキー、ワークフローID、Webhook送信先のシークレットを、シークレットの値として設定します。
2. アプリにサインインし、**Verify my identity**をクリックして、ホスト型のフローを完了します。
3. `/verification-complete`に戻ると、Webhookが届き次第、ページに`Approved`、`Declined`、`In Review`のいずれかが表示されます。`environment`が`sandbox`のため、テスト結果としてラベルが付きます。`In Review`のセッションは、チームがコンソールで判定すると変わり、Webhookによって行が再び更新されます。それまでは、ユーザーには本人確認がレビュー中であることが表示されます。
4. 本人確認済みのユーザーを必要とする機能は、`status = 'Approved'`**かつ**`environment = 'live'`の条件で制限してください。フロントエンドだけでなく、サーバー側で読み取るか、行レベルセキュリティポリシーを使って制限してください。サンドボックスでの承認では、これらの機能は決して利用可能になりません。

### ステップ6: 本番環境に移行する

サンドボックスと本番環境は別々のアプリケーションであり、それぞれに独自のAPIキー、ワークフロー、Webhook送信先があります。そのため、3つすべてを同時に切り替えてください：

1. 本番環境のアプリケーションで、テストしたワークフローを公開し、そのワークフローIDをコピーします。
2. 本番環境のアプリケーションのAPIキーをコピーします。
3. 本番環境のアプリケーションに、同じ`didit-webhook`のURLでWebhook送信先を追加し、`status.updated`を購読させ、その署名シークレットをコピーします。
4. `DIDIT_API_KEY`、`DIDIT_WORKFLOW_ID`、`DIDIT_WEBHOOK_SECRET`を、これら3つの値に同時に置き換え、両方の関数を再デプロイします。本番環境のキーでは、サンドボックスのワークフローでセッションを開くことはできず、サンドボックスの送信先が本番環境の判定を受け取ることもありません。
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-lovableアプリにdiditを追加する)の関数を通じて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**をクリックします。サーバーはそのキーをベアラートークンとして受け付けます。[認証](https://docs.didit.me/ja/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 Edge Functionに送信するDidit Webhookの送信先を登録し、その署名用シークレットの場所を教えてください。」
* 「私のユーザーIDのテストセッションを作成し、認証リンクを教えてください。」

Lovableは読み取り専用のツールを確認なしで実行します。何かを変更するツールを実行する前には、承認を求めます。

### トラブルシューティング

* **サインインに失敗する、またはサインインがループする。** まず同じブラウザで[business.didit.me](https://business.didit.me)にログインし、もう一度**Add & authorize**をクリックします。
* **ツールが`missing_scope`を返す。** その組織における役割に、必要な権限がありません。[役割と権限](https://docs.didit.me/ja/integration/mcp/authentication.md#役割と権限)を参照してください。
* **Webhook関数が`401`を返す。** `DIDIT_WEBHOOK_SECRET`がWebhookを送信する送信先のシークレットと一致しているか確認してください。関数が`verify_jwt = false`でデプロイされているか、また、解析や再エンコードの前に`req.arrayBuffer()`でボディを読み取っているかも確認してください。タイムスタンプの確認で`401`が返る場合は、配信から5分を超えているか、サーバーの時計がずれています。
* **`didit-create-session`が`409`を返す。** Diditが、そのユーザーの追跡中のセッションを本番環境で承認済みと報告しています。ページは、Webhookによって更新される行を再読み込みします。
* **`didit-create-session`が`502`を返す。** Diditに接続できなかったか、未完了のセッションに再開用のリンクがありません。新しいセッションは作成されていないので、もう一度お試しください。
* **セッションのリクエストが`callback`で`400`を返す。** アプリのアドレスをアプリケーションの許可されたドメインに追加するか、`APP_URL`を確認してください。

***

## 次のステップ

> [card] [Webhook](https://docs.didit.me/ja/integration/webhooks.md)
>
> すべてのイベント、ペイロードのフィールド、署名ヘッダー。

> [card] [セッションの作成](https://docs.didit.me/ja/sessions-api/create-session.md)
>
> 期待される詳細情報やメタデータなど、すべてのリクエストフィールド。

> [card] [MCPツールリファレンス](https://docs.didit.me/ja/integration/mcp/tools.md)
>
> Lovableのエージェントが呼び出せるすべてのツールを、ツールごとに示します。

> [card] [料金](https://docs.didit.me/ja/getting-started/pricing.md)
>
> ワークフロー内の各チェックの料金。


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