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

# 人脸比对 API：1:1 人脸比对

> Didit 提供 1:1 人脸比对接口 POST /v3/face-match/，适用于身份验证、门禁控制和重新验证。推理耗时低于2s，按次计费，无月度最低消费。



## OpenAPI

````yaml zh/openapi-25.json POST /v3/face-match/
openapi: 3.0.0
info:
  version: 3.0.0
  title: Didit Verification API
  description: 身份证件验证 API。使用 x-api-key 请求头进行身份验证。
servers:
  - url: https://verification.didit.me
security: []
tags: []
paths:
  /v3/face-match/:
    post:
      tags:
        - Standalone APIs
      summary: 人脸比对
      description: >-
        比对两张人脸图像（1:1）并返回相似度 `score`（0–100）以及 `Approved`/`Declined` 状态 `status`。


        **工作原理。** 两张图像均由生物识别模型进行解码和分析（如果拍摄可能横向或倒置，请设置
        `rotate_image=true`），随后计算两个人脸之间的相似度分数。分数**严格高于**
        `face_match_score_decline_threshold`（默认 `30`）返回 `status:
        "Approved"`；分数等于或低于该阈值返回 `Declined`，并带有 `LOW_FACE_MATCH_SIMILARITY`
        警告。如果完全无法对任何人脸对进行评分，调用仍返回 `200`，状态为 `status: "Declined"`，并带有
        `NO_REFERENCE_IMAGE` 警告：在默认保存路径下 `score` 为 `null`，设置
        `save_api_request=false` 时为 `0`。为获得最佳结果，每张图像请提交一张清晰的正面人脸。


        **计费。** 每个 `200` 响应消耗一个人脸比对 API
        额度（从您的套餐额度或充值余额中扣除）。当组织的余额不足以支付本次调用时，endpoint 会在进行任何图像处理之前返回 `403`
        并提示额度不足错误。


        **会话持久化（`save_api_request`，默认 `true`）。** 当为 `true` 时，该调用将作为 API
        类型会话持久化：它会显示在 Business Console 中，返回的 `request_id` 是一个真实的会话 ID，您可以将其传递给
        `GET
        /v3/session/{sessionId}/decision/`，两张图像都会作为该会话的人脸比对源/目标图像进行存储，并且会向您配置的
        Webhook endpoint 发送 `status.updated` Webhook。当为 `false` 时，不会存储任何内容，且
        `request_id` 是一个一次性的关联 UUID，无法在后续进行查询。


        **人脸搜索索引。** 此 endpoint 绝不会将人脸录入到您的人脸搜索索引中，也绝不运行黑名单或重复筛查：如需这些功能，请使用 `POST
        /v3/passive-liveness/` 或 `POST /v3/face-search/`。


        **沙盒。** 沙盒 API 密钥会跳过所有处理和计费：在请求验证之后（格式错误的输入仍会返回 `400`），endpoint 会返回静态的
        `Approved` 模拟 payload，不会持久化会话，也不会消耗额度。


        **身份验证。** 在 `x-api-key` 请求头中发送您应用的 API 密钥。缺失或无效的凭证将返回 `403`（`{"detail":
        "You do not have permission to perform this action."}`）：此 API 绝不返回
        `401`。


        **速率限制。** 每个 API 密钥在所有 POST/PATCH/DELETE endpoint 之间共享每分钟 300
        次请求的写入预算；超出将返回 `429`。
      operationId: post_v3face-match
      parameters: []
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - user_image
                - ref_image
              properties:
                user_image:
                  type: string
                  format: binary
                  description: >-
                    待验证的真人或候选人脸图像（例如自拍照）。请提交一张主体面部清晰可见且光线充足的正脸照片。允许的扩展名：`tiff`、`jpg`、`jpeg`、`png`、`webp`。最大上传大小：**5
                    MB**（超出限制的文件将被拒绝并返回 `400`）。图像在处理前会自动压缩至约 0.5
                    MB，因此极高分辨率并不会提高准确度。
                ref_image:
                  type: string
                  format: binary
                  description: 用于比对的参考人脸图像（例如身份证件人像照或先前登记的照片）。格式和大小限制与 `user_image` 相同。
                face_match_score_decline_threshold:
                  type: number
                  format: float
                  default: 30
                  minimum: 0
                  maximum: 100
                  description: >-
                    决定响应 `status` 的相似度阈值（0–100）。计算得出的分数**小于或等于**此值会将 `status`
                    设置为 `Declined` 并添加 `LOW_FACE_MATCH_SIMILARITY` 警告；严格高于此分数则返回
                    `Approved`。默认值 `30` 较为宽松，如需更严格的验证，可调高该值（例如 `50`–`60`）。超出
                    0–100 范围的值将返回 `400`。
                  example: 50
                rotate_image:
                  type: boolean
                  default: false
                  description: >-
                    为 `true` 时，服务会按 90
                    度递增（0、90、180、270）尝试输入图像，并使用人脸检测效果最佳的方向，这对于缺少 EXIF
                    方向信息的移动设备拍摄非常有用。这会增加延迟，因此仅在您无法保证图像为正向时启用。
                  example: false
                save_api_request:
                  type: boolean
                  default: true
                  description: >-
                    为 `true`（默认）时，将此次调用持久化为 API 类型的会话，在 Business Console
                    中可见，可使用返回的 `request_id` 通过 `GET
                    /v3/session/{sessionId}/decision/` 检索，并通过 `status.updated`
                    Webhook 发出通知。为 `false` 时，不存储任何内容，且 `request_id` 仅为用于关联响应的临时
                    UUID。
                  example: true
                vendor_data:
                  type: string
                  description: >-
                    可选的不透明字符串（您的内部用户 ID、邮箱、UUID 等），存储在持久化会话中并在响应中回显。可用于将 API
                    调用与您自己的记录相关联，并在稍后筛选会话。
                  example: user-123
                metadata:
                  type: object
                  additionalProperties: true
                  description: >-
                    与会话一同存储（当 `save_api_request=true` 时）并在响应中原样返回的可选 JSON 对象。在
                    multipart 请求中，请将其作为 JSON 编码的字符串字段发送（例如
                    `metadata={"flow":"login"}`），它将被解析为对象。
                  example:
                    flow: login
                    device_id: abc123
            example:
              user_image: (binary JPEG/PNG of the live selfie)
              ref_image: (binary JPEG/PNG of the reference photo)
              face_match_score_decline_threshold: 50
              rotate_image: false
              save_api_request: true
              vendor_data: user-123
              metadata:
                flow: login
      responses:
        '200':
          description: >-
            人脸比对已计算。`face_match.score` 为 0–100 的浮点数（保留两位小数）；当分数严格高于
            `face_match_score_decline_threshold` 时，`status` 为 `Approved`，否则为
            `Declined` 并附带说明性警告。相似度较低或无法评分的人脸对仍会返回 `200`，请检查 `face_match.status`
            和 `face_match.warnings`，而不仅仅是 HTTP 状态码。当 `save_api_request=true`
            时，`request_id` 为持久化的会话 ID。
          content:
            application/json:
              examples:
                Approved:
                  summary: 同一人：分数高于阈值
                  value:
                    request_id: f9f5a777-8002-44c6-baaf-128bcfd6e226
                    face_match:
                      status: Approved
                      score: 99.41
                      user_image:
                        entities:
                          - bbox:
                              - 661
                              - 728
                              - 1688
                              - 2188
                            confidence: 0.732973
                            age: 26.91
                            gender: male
                            race: null
                        best_angle: 0
                      ref_image:
                        entities:
                          - bbox:
                              - 653
                              - 745
                              - 1691
                              - 2185
                            confidence: 0.722082
                            age: 27
                            gender: male
                            race: null
                        best_angle: 0
                      warnings: []
                    vendor_data: user-123
                    metadata:
                      flow: login
                    created_at: '2026-06-12T01:04:42.763237+00:00'
                Declined - low similarity:
                  summary: 等于或低于拒绝阈值的分数
                  value:
                    request_id: 7cdda24e-311a-46d3-a3bb-e5d9b564ce73
                    face_match:
                      status: Declined
                      score: 24.87
                      user_image:
                        entities:
                          - bbox:
                              - 661
                              - 728
                              - 1688
                              - 2188
                            confidence: 0.732973
                            age: 26.91
                            gender: male
                            race: null
                        best_angle: 0
                      ref_image:
                        entities:
                          - bbox:
                              - 156
                              - 234
                              - 679
                              - 898
                            confidence: 0.717775
                            age: 41.2
                            gender: male
                            race: null
                        best_angle: 0
                      warnings:
                        - risk: LOW_FACE_MATCH_SIMILARITY
                          feature: FACEMATCH
                          additional_data: null
                          log_type: error
                          short_description: Low face match similarity
                          long_description: >-
                            The facial features of the provided image don't
                            closely match the reference image, suggesting a
                            potential identity mismatch.
                    vendor_data: user-123
                    metadata: null
                    created_at: '2026-06-12T01:08:19.859116+00:00'
              schema:
                type: object
                properties:
                  request_id:
                    type: string
                    format: uuid
                    description: >-
                      当 `save_api_request=true` 时持久化的会话 ID（可用于 `GET
                      /v3/session/{sessionId}/decision/`）；否则为一个临时的关联 UUID。
                  face_match:
                    type: object
                    properties:
                      status:
                        type: string
                        enum:
                          - Approved
                          - Declined
                        description: >-
                          当相似度分数严格高于 `face_match_score_decline_threshold`
                          且能够计算出分数时为 `Approved`；否则为 `Declined`（会有警告说明原因）。
                      score:
                        type: number
                        format: float
                        nullable: true
                        minimum: 0
                        maximum: 100
                        description: >-
                          相似度分数，范围为 0 到 100，即模型对两张图像代表同一人的置信度。仅在
                          `save_api_request` 为 true 时四舍五入保留两位小数；当
                          `save_api_request=false` 时返回原始浮点数。当无法对人脸对进行评分时为
                          `null`（在默认的 `save_api_request=true` 情况下）；当
                          `save_api_request=false` 时，相同情况可能表现为 `score:
                          0`。无论哪种情况，都会出现 `NO_REFERENCE_IMAGE` 警告且 `status` 为
                          `Declined`。
                        example: 99.41
                      user_image:
                        type: object
                        description: 所分析图像的各项人脸检测结果。
                        properties:
                          entities:
                            type: array
                            items:
                              type: object
                              properties:
                                bbox:
                                  type: array
                                  items:
                                    type: integer
                                  minItems: 4
                                  maxItems: 4
                                  description: >-
                                    检测到的人脸边界框，表示为处理后图像中的 `[x_min, y_min, x_max,
                                    y_max]` 像素坐标。
                                  example:
                                    - 661
                                    - 728
                                    - 1688
                                    - 2188
                                confidence:
                                  type: number
                                  format: float
                                  minimum: 0
                                  maximum: 1
                                  description: 人脸检测置信度（0–1）。
                                  example: 0.732973
                                age:
                                  type: number
                                  format: float
                                  description: 检测到的人脸的模型估算年龄（以岁为单位）。仅供参考，不影响人脸比对决策。
                                  example: 26.91
                                gender:
                                  type: string
                                  description: 模型预测的检测人脸性别（`male` 或 `female`）。仅供参考。
                                  example: male
                                race:
                                  type: string
                                  nullable: true
                                  description: 保留字段 — 在此 endpoint 的响应中始终为 `null`。
                                  example: null
                            description: 每张检测到的人脸对应一个条目。
                          best_angle:
                            type: integer
                            description: >-
                              产生最佳人脸检测结果的旋转角度（度：0、90、180 或 270）。仅当
                              `rotate_image=true` 纠正了方向时才为非零值。
                            example: 0
                      ref_image:
                        type: object
                        description: 参考图像的人脸检测结果，结构与 `user_image` 相同。
                        properties:
                          entities:
                            type: array
                            items:
                              type: object
                              properties:
                                bbox:
                                  type: array
                                  items:
                                    type: integer
                                  minItems: 4
                                  maxItems: 4
                                  description: >-
                                    检测到的人脸边界框，表示为处理后图像中的 `[x_min, y_min, x_max,
                                    y_max]` 像素坐标。
                                  example:
                                    - 661
                                    - 728
                                    - 1688
                                    - 2188
                                confidence:
                                  type: number
                                  format: float
                                  minimum: 0
                                  maximum: 1
                                  description: 人脸检测置信度（0–1）。
                                  example: 0.732973
                                age:
                                  type: number
                                  format: float
                                  description: 检测到的人脸的模型估算年龄（以岁为单位）。仅供参考，不影响人脸比对决策。
                                  example: 26.91
                                gender:
                                  type: string
                                  description: 模型预测的检测人脸性别（`male` 或 `female`）。仅供参考。
                                  example: male
                                race:
                                  type: string
                                  nullable: true
                                  description: 保留字段 — 在此 endpoint 的响应中始终为 `null`。
                                  example: null
                            description: 每张检测到的人脸对应一个条目。
                          best_angle:
                            type: integer
                            example: 0
                      warnings:
                        type: array
                        description: >-
                          完全通过审核时为空。`NO_REFERENCE_IMAGE`（`error`）—
                          无法对人脸对进行评分；`LOW_FACE_MATCH_SIMILARITY`（`error`）—
                          分数等于或低于拒绝阈值。其中任何一项都会将 `status` 设置为 `Declined`。
                        items:
                          type: object
                          properties:
                            risk:
                              type: string
                              enum:
                                - NO_REFERENCE_IMAGE
                                - LOW_FACE_MATCH_SIMILARITY
                              description: 机器可读的风险代码。
                            feature:
                              type: string
                              enum:
                                - FACEMATCH
                              description: 引发该警告的功能。在此 endpoint 上始终为 `FACEMATCH`。
                            additional_data:
                              type: object
                              nullable: true
                              additionalProperties: true
                              description: 对于人脸比对警告始终为 `null`。
                            log_type:
                              type: string
                              enum:
                                - error
                                - warning
                                - information
                              description: >-
                                严重程度。`error` 警告会导致 `status` 变为
                                `Declined`；`warning` 和 `information`
                                条目仅供参考，本身绝不会导致拒绝。
                            short_description:
                              type: string
                              description: 易于阅读的单行风险摘要。
                            long_description:
                              type: string
                              description: 风险的便于人类阅读的说明。
                  vendor_data:
                    type: string
                    nullable: true
                    description: 您发送的 `vendor_data` 回显，或 `null`。
                  metadata:
                    type: object
                    nullable: true
                    additionalProperties: true
                    description: 您发送的 `metadata` 对象回显，或 `null`。
                  created_at:
                    type: string
                    format: date-time
                    description: >-
                      响应生成时的 ISO 8601 时间戳（UTC），例如
                      `2026-06-12T01:04:42.763237+00:00`。
        '400':
          description: >-
            验证错误。当必需的图像缺失、超过 5 MB、扩展名不受支持，或选项超出范围时返回。响应体为 DRF
            的标准字段错误响应格式：每个有问题的字段对应一个消息数组。
          content:
            application/json:
              examples:
                Missing required image:
                  summary: 表单数据中未包含 `ref_image`（或 `user_image`）
                  value:
                    ref_image:
                      - No file was submitted.
                Unsupported file extension:
                  summary: 文件扩展名不在 tiff/jpg/jpeg/png/webp 范围内
                  value:
                    user_image:
                      - >-
                        File extension “txt” is not allowed. Allowed extensions
                        are: tiff, jpg, jpeg, png, webp.
                File too large:
                  summary: 上传内容超过 5 MB 限制
                  value:
                    user_image:
                      - File size should not exceed 5 MB
                Threshold out of range:
                  summary: '`face_match_score_decline_threshold` 超出 0–100 范围'
                  value:
                    face_match_score_decline_threshold:
                      - Ensure this value is less than or equal to 100.
        '403':
          description: >-
            权限被拒绝。当缺少 `x-api-key` 请求头，或调用组织的余额无法覆盖此次调用时返回；错误、已撤销或已过期的密钥返回
            `401`。缺少密钥时返回 `403` 及 `{"detail": ...}`；错误、已撤销或已过期的密钥返回
            `401`。额度不足时会在进行任何图像处理之前返回 `403` 及 `{"error": ...}`。
          content:
            application/json:
              examples:
                Missing or invalid API key:
                  summary: 缺少 `x-api-key` 请求头，或者密钥无效/已被吊销
                  value:
                    detail: You do not have permission to perform this action.
                Not enough credits:
                  summary: 组织余额不足以支付本次调用
                  value:
                    error: >-
                      You don't have enough credits to perform this request.
                      Please top up at https://business.didit.me
        '429':
          description: >-
            超出速率限制。POST/PATCH/DELETE endpoint 每个 API 密钥每分钟共享 300
            次写入请求的额度（交易创建和事件摄入具有单独的 600 次额度）。响应包含
            `X-RateLimit-Limit`、`X-RateLimit-Remaining`、`X-RateLimit-Reset` 和
            `Retry-After` 响应头。
          content:
            application/json:
              examples:
                Write rate limit exceeded:
                  summary: 当前分钟内的写入请求超过 300 次
                  value:
                    detail: >-
                      Write request rate limit exceeded. You can make up to 300
                      requests per minute.
              schema:
                type: object
                properties:
                  detail:
                    type: string
      security:
        - ApiKeyAuth: []
      x-codeSamples:
        - lang: curl
          label: cURL
          source: |-
            curl -X POST 'https://verification.didit.me/v3/face-match/' \
              -H 'x-api-key: YOUR_API_KEY' \
              -F 'user_image=@./selfie.jpg' \
              -F 'ref_image=@./id_portrait.jpg' \
              -F 'face_match_score_decline_threshold=50' \
              -F 'save_api_request=true' \
              -F 'vendor_data=user-123'
        - lang: python
          label: Python
          source: |-
            from didit import Didit

            # Reads DIDIT_API_KEY.
            client = Didit()

            result = client.face_match.compare(
                user_image=open("user_image.jpg", "rb"),
                ref_image=open("ref_image.jpg", "rb"),
                face_match_score_decline_threshold=50.0,
                rotate_image=False,
                save_api_request=True,
                vendor_data="user-123",
                metadata={"flow": "login"},
            )
            print(result)
        - lang: javascript
          label: Node.js
          source: |-
            import Didit, { fileFromPath } from "@didit-protocol/sdk-node";

            // Reads DIDIT_API_KEY.
            const didit = new Didit();

            const result = await didit.faceMatch.compare({
              user_image: await fileFromPath("user_image.jpg"),
              ref_image: await fileFromPath("ref_image.jpg"),
              face_match_score_decline_threshold: 50.0,
              rotate_image: false,
              save_api_request: true,
              vendor_data: "user-123",
              metadata: { flow: "login" },
            });
            console.log(result);
        - lang: go
          label: Go
          source: "ctx := context.Background()\n// Reads DIDIT_API_KEY.\nclient := didit.NewClient()\n\nresult, err := client.FaceMatch.Compare(ctx, didit.FaceMatchCompareParams{\n\tUserImage:                      didit.FileFromPath(\"user_image.jpg\"),\n\tRefImage:                       didit.FileFromPath(\"ref_image.jpg\"),\n\tFaceMatchScoreDeclineThreshold: didit.Float(50.0),\n\tRotateImage:                    didit.Bool(false),\n\tSaveAPIRequest:                 didit.Bool(true),\n\tVendorData:                     didit.String(\"user-123\"),\n\tMetadata:                       didit.Some(map[string]any{\"flow\": \"login\"}),\n})\nif err != nil {\n\tlog.Fatal(err)\n}\nfmt.Printf(\"%+v\\n\", result)"
        - lang: java
          label: Java
          source: >-
            import java.nio.file.Path;

            import java.util.Map;

            import me.didit.Didit;

            import me.didit.types.FaceMatchCompareParams;


            // Reads DIDIT_API_KEY.

            Didit client = new Didit();


            var result =
            client.faceMatch().compare(FaceMatchCompareParams.builder()
                    .userImage(Path.of("user_image.jpg"))
                    .refImage(Path.of("ref_image.jpg"))
                    .faceMatchScoreDeclineThreshold(50.0)
                    .rotateImage(false)
                    .saveApiRequest(true)
                    .vendorData("user-123")
                    .metadata(Map.of("flow", "login"))
                    .build());
            System.out.println(result);
        - lang: php
          label: PHP
          source: |-
            <?php

            require 'vendor/autoload.php';

            use Didit\DiditClient;
            use Didit\File;

            // Reads DIDIT_API_KEY.
            $didit = new DiditClient();

            $result = $didit->faceMatch->compare([
                'user_image' => File::fromPath('user_image.jpg'),
                'ref_image' => File::fromPath('ref_image.jpg'),
                'face_match_score_decline_threshold' => 50.0,
                'rotate_image' => false,
                'save_api_request' => true,
                'vendor_data' => 'user-123',
                'metadata' => ['flow' => 'login'],
            ]);
            print_r($result->toArray());
        - lang: ruby
          label: Ruby
          source: |-
            require "didit"

            # Reads DIDIT_API_KEY.
            didit = Didit::Client.new

            result = didit.face_match.compare(
              user_image: Pathname("user_image.jpg"),
              ref_image: Pathname("ref_image.jpg"),
              face_match_score_decline_threshold: 50.0,
              rotate_image: false,
              save_api_request: true,
              vendor_data: "user-123",
              metadata: { flow: "login" }
            )
            puts result.to_h
        - lang: csharp
          label: .NET
          source: >-
            using System;

            using System.Collections.Generic;

            using System.Text.Json;

            using Didit;


            // Reads DIDIT_API_KEY.

            using var client = new DiditClient();


            var result = await client.FaceMatch.CompareAsync(new
            FaceMatchCompareParams

            {
                UserImage = FileUpload.FromPath("user_image.jpg"),
                RefImage = FileUpload.FromPath("ref_image.jpg"),
                FaceMatchScoreDeclineThreshold = 50.0,
                RotateImage = false,
                SaveApiRequest = true,
                VendorData = "user-123",
                Metadata = new Dictionary<string, object> { ["flow"] = "login" },
            });

            Console.WriteLine(JsonSerializer.Serialize(result));
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        您的应用 API 密钥，可在 Business Console 的“开发者 -> API
        密钥”中获取。主密钥拥有完整访问权限。指定名称的密钥可设置作用域：针对每个资源设为无权限、只读或读写，限定于特定工作流或已通过的会话、限定于
        IP 地址列表，以及设置到期日期。401 表示密钥错误、已撤销或已过期；403 表示未发送密钥、密钥无权访问该资源或操作，或请求来自其 IP
        列表之外的地址；在会话路由上返回 404 表示该会话不在该密钥允许的工作流或状态范围内。没有媒体访问权限的密钥获取到的图片、视频和 PDF
        URL 将为 null；没有会话写入权限的密钥获取到的会话链接和 token 将为 null。请参阅
        https://docs.didit.me/console/api-keys。

````

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