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

# Проверка email через API: получение учетных данных Didit

> POST /programmatic/verify-email/ подтверждает email и выдает токены доступа, client_id и api_key. Онбординг для агентов, оплата за использование.



Промпт для проверки электронной почты и получения учётных данных
        Скопировать промпт в буфер обмена



      
      

\<pre>

\`Exchange the email verification code for usable Didit credentials — step 2 of programmatic onboarding.

Endpoint:
POST https://apx.didit.me/auth/v2/programmatic/verify-email/

Authentication:
None. The email + code pair is the credential.

Request body:
\- email (string, required) — Same email used in /programmatic/register/.
\- code (string, required) — 6-character alphanumeric code from the registration email (e.g. "A3K9F2"). Valid for 15 minutes.

curl example:
curl -X POST https://apx.didit.me/auth/v2/programmatic/verify-email/ \
-H "Content-Type: application/json" \
-d '{
"email": "you@yourdomain.com",
"code": "A3K9F2"
}'

Response (200 OK):
\{
"access_token": "eyJ...RS256 JWT",
"refresh_token": "eyJ...RS256 JWT",
"expires_in": 86400,
"organization": {
"uuid": "a1b2c3d4-5678-...",
"name": "you"
},
"application": {
"uuid": "b2c3d4e5-6789-...",
"name": "you",
"client_id": "S9LIYGSoWNuGMLHsvEt9dQ",
"api_key": "sk_live_example_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"data_location": "eu"
}
}

What happens server-side:
1\. The pending account is marked email-verified.
2\. A default organization is created (named after the local part of the email, e.g. "you" from "you@yourdomain.com").
3\. A default application is created inside the organization with a fresh client_id and api_key, in the European Union (data_location "eu"). Its location can be chosen once with PATCH /organizations/me/{org_id}/applications/{app_id}/ before the application is used; see /auth-api/update-application.
4\. JWTs are issued (RS256, default 24h / 86400 seconds lifetime).

How to use the response:
\- application.api_key → set as the x-api-key header on EVERY call to https://verification.didit.me/v3/... (sessions, workflows, questionnaires, billing, etc.). PERSIST IT SECURELY. You can read it again later with GET /organizations/me/{org_id}/applications/{app_id}/.
\- access_token → use as "Authorization: Bearer <access_token>" against Account Management endpoints on https://apx.didit.me/auth/v2 (e.g. to create more applications).
\- refresh_token → exchange for a new access_token after expiry.

Save the api_key, the organization.uuid (org_id), and the application.uuid (app_id) — you will need all three to manage applications later.

Failure modes (400 unless noted):
\- Field-level: { "email": ["Enter a valid email address."] } or { "code": ["Ensure this field has at least 6 characters."] }.
\- Wrong or expired code CURRENTLY returns a BARE ARRAY ["Invalid or expired verification code."] — known server-side inconsistency; treat as { "code": [...] } client-side.
\- Unknown email: { "detail": "User not found." }

Recovery if you lose the api_key later:
Call POST /programmatic/login/ with email + password to get a fresh access_token, then GET /organizations/me/{org_id}/applications/{app_id}/ to read the api_key back. See /auth-api/login and /auth-api/get-credentials.

For end-to-end Didit integration, paste in the full prompt at /integration/integration-prompt.`

\</pre>



      
      

Вставьте в



## OpenAPI

````yaml ru/openapi-auth.json POST /programmatic/verify-email/
openapi: 3.0.0
info:
  version: 1.0.0
  title: Didit Auth API
  description: >-
    API программной регистрации и аутентификации для разработчиков и AI-агентов.
    Регистрация за 2 вызова API: без использования браузера. Самая удобная для
    агентов платформа верификации личности.


    ## Базовый URL


    Все endpoint в этой спецификации размещены по адресу
    `https://apx.didit.me/auth/v2`. Это другой хост, отличный от API верификации
    (`https://verification.didit.me/v3`). Не путайте их: этот хост
    аутентификации выдаёт ваши **токены доступа JWT** и позволяет просматривать
    список и управлять вашими **организациями** и **приложениями**. На хосте
    верификации вы вызываете сессии, сценарии, AML и т. д., аутентифицируясь с
    помощью **`api_key`**, возвращаемого этим API.


    ## Как устроен процесс аутентификации


    1. `POST /programmatic/register/`: отправьте email + пароль.

    2. Получите 6-значный буквенно-цифровой код по электронной почте.

    3. `POST /programmatic/verify-email/`: отправьте код. Вы получите обратно
    JWT `access_token`, `refresh_token`, организацию и стандартное приложение с
    `client_id` + `api_key`.

    4. Сохраните `api_key`. Используйте его в качестве `x-api-key` для каждого
    вызова к `https://verification.didit.me/v3/...`.

    5. В дальнейшем с любой машины `POST /programmatic/login/` обменивает ваши
    email + пароль на свежий JWT, после чего вызовите `GET /organizations/me/` и
    endpoint приложений для восстановления или ротации учётных данных.


    JWT требуется только для endpoint **Управления аккаунтом** в этой
    спецификации; трафик к API верификации использует долгоживущий `api_key`, а
    не JWT.


    ## Соглашения


    - Все тела запросов и ответов представляют собой JSON (`Content-Type:
    application/json`).

    - **Используйте реальный, доставляемый адрес электронной почты при
    тестировании `POST /programmatic/register/`.** Endpoint отправляет код
    подтверждения синхронно, поэтому адреса на зарезервированных тестовых
    доменах (`@example.com`, `@example.org`, `@*.test`, `@*.example`,
    `@*.invalid`) отклоняются службой доставки почты, и запрос возвращает `500`.
    Замените плейсхолдер `you@yourdomain.com` в примерах на почтовый ящик,
    который вы действительно можете прочитать.

    - Ошибки валидации возвращают HTTP `400` в одном из двух форматов:
    `{"field": ["message", ...]}` для проблем на уровне полей или `{"detail":
    "message"}` для ошибок бизнес-правил. Некоторые валидаторы (сложность пароля
    при регистрации, истечение срока действия кода при проверке email) в
    настоящее время возвращают простой массив `["message"]` вместо структуры с
    ключами полей - это известная несогласованность на стороне сервера, поэтому
    клиентский код должен принимать оба формата.

    - Ошибки аутентификации возвращаются в виде `{"detail": "..."}` с кодом HTTP
    `401` (недействительный bearer token) или `403` (отсутствует bearer token /
    недостаточно прав).

    - Ответы с ограничением частоты запросов содержат поле `wait` с временем
    задержки в секундах.
servers:
  - url: https://apx.didit.me/auth/v2
    description: Продакшн-сервер аутентификации
security: []
tags:
  - name: Programmatic Auth
    description: >-
      Жизненный цикл аккаунта с электронной почтой и паролем: регистрация,
      подтверждение, вход. Возвращает JWT `access_token`, который вы используете
      для endpoint'ов управления аккаунтом, а также (при подтверждении)
      `client_id` и `api_key` вашего первого приложения.
  - name: Account Management
    description: >-
      Аутентифицированные endpoint (JWT bearer), которые возвращают список
      организаций и позволяют создавать, получать или обновлять приложения.
      Используйте их для восстановления или ротации `api_key`, с помощью
      которого вы аутентифицируете вызовы API верификации.
paths:
  /programmatic/verify-email/:
    post:
      tags:
        - Programmatic Auth
      summary: Проверить электронную почту и выпустить учетные данные
      description: >-
        Шаг 2 онбординга. Обменивает 6-значный код на подтвержденную учетную
        запись, организацию и приложение по умолчанию, а также пару JWT.
        Сохраните возвращенный `api_key`.
      operationId: programmatic_verify_email
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/VerifyEmailRequest'
            examples:
              Default:
                summary: Отправить код из электронного письма о регистрации
                value:
                  email: you@yourdomain.com
                  code: A3K9F2
      responses:
        '200':
          description: >-
            Электронная почта подтверждена. Ответ содержит токены для этого API
            аутентификации, а также `client_id` и `api_key` нового приложения.
            Сохраните `api_key` в безопасном месте — это долгосрочный API-ключ,
            используемый при каждом вызове API верификации.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VerifyEmailResponse'
              examples:
                Success:
                  value:
                    access_token: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
                    refresh_token: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
                    expires_in: 86400
                    organization:
                      uuid: a1b2c3d4-5678-90ab-cdef-111111111111
                      name: developer
                    application:
                      uuid: b2c3d4e5-6789-01bc-defg-222222222222
                      name: developer
                      client_id: S9LIYGSoWNuGMLHsvEt9dQ
                      api_key: sk_live_example_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                      data_location: eu
        '400':
          description: >-
            Ошибка валидации. Предполагаемая обёртка: `{"field": ["..."]}` для
            проблем на уровне полей и `{"detail": "..."}` для ошибок
            бизнес-правил (например, пользователь не найден). Ошибки неверного
            или истёкшего кода в настоящее время возвращают простой массив
            `["Invalid or expired verification code."]` (известная
            несогласованность на стороне сервера); обрабатывайте её как
            `{"code": ["..."]}`, пока она не будет исправлена.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationError'
              examples:
                MissingFields:
                  summary: Пустое тело
                  value:
                    email:
                      - This field is required.
                    code:
                      - This field is required.
                CodeTooShort:
                  summary: Код короче 6 символов
                  value:
                    code:
                      - Ensure this field has at least 6 characters.
                InvalidEmail:
                  summary: Некорректный email
                  value:
                    email:
                      - Enter a valid email address.
                InvalidCode:
                  summary: Неверный или истёкший код
                  value:
                    - Invalid or expired verification code.
                UserNotFound:
                  summary: Для этого адреса электронной почты нет ожидающего аккаунта
                  value:
                    detail: User not found.
        '429':
          description: >-
            Сервис в данный момент проверяет максимально возможное количество
            паролей или кодов одновременно. Отправляется с заголовком
            `Retry-After: 5`; повторите попытку через указанное количество
            секунд.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitError'
              examples:
                PasswordChecksBusy:
                  summary: Слишком много проверок пароля выполняется одновременно
                  value:
                    detail: >-
                      Too many sign-in attempts are being processed right now.
                      Please try again in a few seconds.
      security:
        - {}
      x-codeSamples:
        - lang: curl
          label: cURL
          source: >-
            curl -X POST https://apx.didit.me/auth/v2/programmatic/verify-email/
            \
              -H "Content-Type: application/json" \
              -d '{
                "email": "you@yourdomain.com",
                "code": "A3K9F2"
              }'
        - lang: python
          label: Python
          source: |-
            from didit import Didit

            # This call needs no API key.
            client = Didit()

            result = client.account.verify_email(
                email="you@yourdomain.com",
                code="A3K9F2",
            )
            print(result)
        - lang: javascript
          label: Node.js
          source: |-
            import Didit from "@didit-protocol/sdk-node";

            // This call needs no API key.
            const didit = new Didit();

            const result = await didit.account.verifyEmail({
              email: "you@yourdomain.com",
              code: "A3K9F2",
            });
            console.log(result);
        - lang: go
          label: Go
          source: "ctx := context.Background()\n// This call needs no API key.\nclient := didit.NewClient()\n\nresult, err := client.Account.VerifyEmail(ctx, didit.VerifyEmailRequest{\n\tEmail: \"you@yourdomain.com\",\n\tCode:  \"A3K9F2\",\n})\nif err != nil {\n\tlog.Fatal(err)\n}\nfmt.Printf(\"%+v\\n\", result)"
        - lang: java
          label: Java
          source: >-
            import me.didit.Didit;

            import me.didit.types.VerifyEmailRequest;


            // This call needs no API key.

            Didit client = new Didit();


            var result =
            client.account().verifyEmail(VerifyEmailRequest.builder()
                    .email("you@yourdomain.com")
                    .code("A3K9F2")
                    .build());
            System.out.println(result);
        - lang: php
          label: PHP
          source: |-
            <?php

            require 'vendor/autoload.php';

            use Didit\DiditClient;

            // This call needs no API key.
            $didit = new DiditClient();

            $result = $didit->account->verifyEmail([
                'email' => 'you@yourdomain.com',
                'code' => 'A3K9F2',
            ]);
            print_r($result->toArray());
        - lang: ruby
          label: Ruby
          source: |-
            require "didit"

            # This call needs no API key.
            didit = Didit::Client.new

            result = didit.account.verify_email(
              email: "you@yourdomain.com",
              code: "A3K9F2"
            )
            puts result.to_h
        - lang: csharp
          label: .NET
          source: >-
            using System;

            using System.Text.Json;

            using Didit;


            // This call needs no API key.

            using var client = new DiditClient();


            var result = await client.Account.VerifyEmailAsync(new
            VerifyEmailRequest

            {
                Email = "you@yourdomain.com",
                Code = "A3K9F2",
            });

            Console.WriteLine(JsonSerializer.Serialize(result));
components:
  schemas:
    VerifyEmailRequest:
      type: object
      required:
        - email
        - code
      properties:
        email:
          type: string
          format: email
          description: >-
            Адрес электронной почты, использованный при `POST
            /programmatic/register/`.
          example: you@yourdomain.com
        code:
          type: string
          minLength: 6
          maxLength: 6
          description: >-
            6-значный буквенно-цифровой код из электронного письма с
            подтверждением. Срок действия кодов истекает через 10 минут после
            отправки последнего кода.
          example: A3K9F2
    VerifyEmailResponse:
      type: object
      properties:
        access_token:
          type: string
          description: >-
            Подписанный по алгоритму RS256 JWT. Используйте как `Authorization:
            Bearer <token>` для endpoints управления аккаунтом на
            `apx.didit.me/auth/v2`.
        refresh_token:
          type: string
          description: Токен обновления в паре с токеном доступа.
        expires_in:
          type: integer
          description: Срок действия токена доступа в секундах (по умолчанию 86400).
          example: 86400
        organization:
          $ref: '#/components/schemas/OrganizationSummary'
        application:
          $ref: '#/components/schemas/ApplicationCredentialsSummary'
    ValidationError:
      description: >-
        Тело ошибки валидации. Предполагаемый формат обёртки представляет собой
        словарь `{field: ["message", ...]}` для ошибок на уровне полей или
        одноключевую обёртку `{detail: "..."}` для ошибок бизнес-правил.
        Некоторые валидаторы (стойкость пароля при регистрации, действительность
        кода при verify-email) в настоящее время возвращают простой массив
        `["message"]` (известная несогласованность на стороне сервера). Схема
        ниже сохраняет эту ветку с простым массивом, чтобы клиентский код,
        сгенерированный из этой спецификации, мог десериализовать текущие
        ответы, однако новому клиентскому коду следует обрабатывать её в формате
        с ключом соответствующего поля (`{password: [...]}` или `{code:
        [...]}`), и контракт сервера со временем придёт к этому виду.
      oneOf:
        - type: object
          additionalProperties:
            type: array
            items:
              type: string
          example:
            email:
              - Enter a valid email address.
        - type: object
          properties:
            detail:
              type: string
          example:
            detail: An account with this email already exists.
        - type: array
          items:
            type: string
          example:
            - Invalid or expired verification code.
    RateLimitError:
      type: object
      description: >-
        Ответ о превышении лимита запросов или прогрессивной блокировке. `wait`
        указывает время ожидания в секундах.
      properties:
        detail:
          type: string
          example: >-
            Too many login attempts from this IP address. Please wait before
            trying again.
    OrganizationSummary:
      type: object
      description: >-
        Минимальная структура организации, возвращаемая инлайн в ответе `POST
        /programmatic/verify-email/`.
      properties:
        uuid:
          type: string
          format: uuid
          example: a1b2c3d4-5678-90ab-cdef-111111111111
        name:
          type: string
          example: developer
    ApplicationCredentialsSummary:
      type: object
      description: >-
        Минимальная структура приложения, возвращаемая инлайн в ответе `POST
        /programmatic/verify-email/`. Немедленно сохраните `api_key`.
      properties:
        uuid:
          type: string
          format: uuid
          example: b2c3d4e5-6789-01bc-defg-222222222222
        name:
          type: string
          example: developer
        client_id:
          type: string
          example: S9LIYGSoWNuGMLHsvEt9dQ
        api_key:
          type: string
          description: >-
            Используйте это значение как `x-api-key` при каждом вызове API
            верификации. Новые ключи начинаются с `sk_live_`
            (продакшн-приложение) или `sk_test_` (приложение в песочнице), за
            которыми следуют 43 URL-безопасных символа (буквы, цифры, `-` и
            `_`). Ключи, созданные до введения этого формата, не имеют префикса
            и продолжают работать без изменений.
          example: sk_live_example_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        data_location:
          $ref: '#/components/schemas/ApplicationDataLocation'
    ApplicationDataLocation:
      type: string
      enum:
        - eu
        - au
        - mx
      description: >-
        Место хранения и обработки данных верификации приложения выбирается при
        создании приложения. `eu`: Европейский союз (Ирландия), по умолчанию.
        `au` (Австралия, Сидней) и `mx` (Мексика) станут доступны в ближайшее
        время: запрос с их указанием возвращает 400 `This data location is not
        available yet.` Приложение песочницы организации всегда располагается в
        Европейском союзе.
      example: eu

````

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