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

# Поиск пользователя

> Поиск пользователя в школе по логину, Telegram ID или внешнему extId

## Заголовки запроса

<ParamField header="Authorization" type="string" required>
  API токен сервисного пользователя в формате Bearer. Получите токен в панели администратора школы. Формат: `Bearer YOUR_TOKEN`.
</ParamField>

<ParamField header="Seller-Id" type="string" required>
  Уникальный идентификатор продавца в системе. Используется для разграничения доступа между разными продавцами.
</ParamField>

<ParamField header="School-Id" type="string" required>
  Уникальный идентификатор школы в системе. Определяет контекст выполнения операции.
</ParamField>

```
GET /saas/v2/user/find
```

Требуется аутентификация и право `SchoolManageUsers`.

## Параметры запроса

##### Для поиска пользователя передайте один из ниже перечисленных параметров

<Info>
  Поиск осуществляется по логину (email/телефон/домен), затем по Telegram ID, затем по внешнему идентификатору `extId`. Приоритет: `login` → `tgId` → `extId`. Если пользователь не найден — возвращается `null`.
  Если переданы несколько параметров — используется параметр с наивысшим приоритетом.
</Info>

<ParamField query="login" type="string" required={false}>
  Логин пользователя. Может быть email адресом, номером телефона в международном формате или `id12345...` — если вы знаете ID пользователя в системе exode.
</ParamField>

<ParamField query="tgId" type="integer" required={false}>
  Telegram ID пользователя. Целое число.
</ParamField>

<ParamField query="extId" type="string" required={false}>
  Внешний идентификатор пользователя из вашей системы.
</ParamField>

<Info>
  **Логином** пользователя может быть:

  * Email адрес (например: `user@example.com`)
  * Номер телефона в международном формате (например: `+9876543210`)
  * Домен пользователя (например, `id12345`)
</Info>

<Warning>
  Необходимо передать **хотя бы один** из параметров. Приоритет выбора: `login` → `tgId` → `extId`.
  Если указаны все три — будет использован `login`.
</Warning>

<RequestExample>
  ```bash cURL theme={null}
  curl --location --request GET 'https://api.exode.biz/saas/v2/user/find?extId=crm_12345' \
    --header 'Seller-Id: {{ sellerId }}' \
    --header 'School-Id: {{ schoolId }}' \
    --header 'Authorization: Bearer YOUR_TOKEN'
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  const findUser = async () => {
    try {
      const response = await axios.get('https://api.exode.biz/saas/v2/user/find', {
        params: { extId: 'crm_12345' },
        headers: {
          'Seller-Id': '{{ sellerId }}',
          'School-Id': '{{ schoolId }}',
          'Authorization': 'Bearer YOUR_TOKEN'
        }
      });

      console.log('User found:', response.data.payload);
    } catch (error) {
      console.error('Error:', error.response?.data || error.message);
    }
  };

  findUser();
  ```

  ```php PHP theme={null}
  <?php

  $url = 'https://api.exode.biz/saas/v2/user/find';
  $params = [ 'extId' => 'crm_12345' ];

  $headers = [
    'Seller-Id: {{ sellerId }}',
    'School-Id: {{ schoolId }}',
    'Authorization: Bearer YOUR_TOKEN'
  ];

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($httpCode === 200) {
    $result = json_decode($response, true);
    if ($result['payload']) {
      echo "User found successfully\n";
      print_r($result['payload']);
    } else {
      echo "User not found\n";
    }
  } else {
    echo "Error: HTTP $httpCode\n";
    echo $response;
  }
  ?>
  ```

  ```python Python theme={null}
  import requests
  import json

  url = 'https://api.exode.biz/saas/v2/user/find'

  params = { 'extId': 'crm_12345' }

  headers = {
    'Seller-Id': '{{ sellerId }}',
    'School-Id': '{{ schoolId }}',
    'Authorization': 'Bearer YOUR_TOKEN'
  }

  try:
    response = requests.get(url, params=params, headers=headers)
    response.raise_for_status()

    result = response.json()
    if result['payload']:
      print('User found successfully:')
      print(json.dumps(result['payload'], indent=2, ensure_ascii=False))
    else:
      print('User not found')

  except requests.exceptions.RequestException as e:
    print(f'Error: {e}')
    if hasattr(e, 'response') and e.response is not None:
      print(f'Response: {e.response.text}')
  ```

  ```bsl 1С theme={null}
  Соединение = Новый HTTPСоединение("api.exode.biz", 443, , , , 30, Новый OpenSSLSecureConnection);

  Запрос = Новый HTTPЗапрос("/saas/v2/user/find?extId=crm_12345");
  Запрос.Заголовки.Вставить("Seller-Id", "{{ sellerId }}");
  Запрос.Заголовки.Вставить("School-Id", "{{ schoolId }}");
  Запрос.Заголовки.Вставить("Authorization", "Bearer YOUR_TOKEN");

  Ответ = Соединение.ВызватьHTTPМетод("GET", Запрос);

  Если Ответ.КодСостояния = 200 Тогда
      ЧтениеJSON = Новый ЧтениеJSON;
      ЧтениеJSON.УстановитьСтроку(Ответ.ПолучитьТелоКакСтроку());
      Результат = ПрочитатьJSON(ЧтениеJSON);
      Сообщить("Пользователь найден");
  Иначе
      Сообщить("Ошибка: HTTP " + Ответ.КодСостояния);
      Сообщить(Ответ.ПолучитьТелоКакСтроку());
  КонецЕсли;
  ```
</RequestExample>

<ResponseExample>
  ```json Success - User Found theme={null}
  {
    "success": true,
    "code": 200,
    "payload": {
      "user": {
        "id": 1683,
        "createdAt": "2026-07-02T11:15:46.896Z",
        "updatedAt": "2026-07-02T11:15:46.940Z",
        "archivedAt": null,
        "uuid": "e-cjTT0CWMCB",
        "active": true,
        "activated": true,
        "banned": false,
        "alive": true,
        "domain": "id1683",
        "email": "user@example.com",
        "phone": "+9876543210",
        "tgId": 987654321,
        "vkId": null,
        "appleId": null,
        "extId": "crm_12345",
        "schoolId": 198,
        "language": "Uz",
        "timezone": 5,
        "lastOnlineAt": "2026-07-02T10:36:11.446Z",
        "starsBalance": 0,
        "currentTime": "2026-07-02T11:15:46+00:00",
        "isSleepingNow": false,
        "profile": {
          "id": 1665,
          "createdAt": "2026-07-02T11:15:46.932Z",
          "updatedAt": "2026-07-02T11:15:46.932Z",
          "archivedAt": null,
          "userId": 1683,
          "official": false,
          "firstName": "Firstname",
          "lastName": "Lastname",
          "fullName": "Firstname Lastname",
          "fullNameShort": "Firstname L.",
          "bdate": null,
          "sex": "Ufo",
          "country": null,
          "city": null,
          "role": "Student",
          "status": null,
          "title": "",
          "emojiTitle": "",
          "avatar": {
            "id": 1665,
            "small": "https://storage.exode.biz/production/user/1683/xK2mVwNib9b0/small/avatar.png",
            "medium": "https://storage.exode.biz/production/user/1683/xK2mVwNib9b0/medium/avatar.png",
            "maximum": "https://storage.exode.biz/production/user/1683/xK2mVwNib9b0/avatar.png"
          },
          "titleState": {
            "manualTitle": null,
            "manualEmojiTitle": null,
            "manualNextTitle": null,
            "manualNextEmojiTitle": null,
            "manualExpiredAt": null,
            "locationTitle": null,
            "locationEmojiTitle": null,
            "achievementTitle": null,
            "achievementEmojiTitle": null
          }
        }
      }
    }
  }
  ```

  ```json Success - User Not Found theme={null}
  {
    "success": true,
    "code": 200,
    "payload": {
      "user": null
    }
  }
  ```

  ```json Error - Invalid Login theme={null}
  {
    "code": 400,
    "success": false,
    "cause": "InvalidLogin",
    "message": "Login must be a valid email or phone number",
    "error": "Login must be a valid email or phone number"
  }
  ```

  ```json Error - Invalid Telegram ID theme={null}
  {
    "code": 400,
    "success": false,
    "cause": "InvalidTgId",
    "message": "Telegram ID must be a valid integer",
    "error": "Telegram ID must be a valid integer"
  }
  ```
</ResponseExample>

## Требования к правам доступа

<Check>
  Для поиска пользователя требуется **право на управление пользователями школы**.
</Check>

<Warning>
  Сервисный пользователь должен быть аутентифицирован по токену и иметь соответствующие права доступа к указанной
  школе.
</Warning>

<Info>
  Поиск осуществляется только в рамках указанной школы. Пользователи из других школ не будут найдены.
</Info>
