# crm.entity.mergeBatch

URL: https://chugunov.pro/api-bitrix24/crm/duplicates/crm-entity-merge-batch/
Проверено на Битрикс24 REST API, обновлено 11.09.2026 (ревизия источника fb39d6c).
Источник: официальная документация Битрикс24 (bitrix-tools/b24-rest-docs, лицензия MIT, © Bitrix). Справочник независимый, официальной документацией не является.

Объединить дубликаты
Scope: `crm`
Кто может выполнять метод: пользователь с правом на изменение главного элемента и правом на удаление остальных объединяемых элементов

## Описание

Метод `crm.entity.mergeBatch` объединяет несколько элементов в один.

## Параметры

- `params` `object` — обязательный. Объект с элементами для объединения [(подробное описание)](#params)

### Параметр params

- `entityTypeId` `integer` — обязательный. Идентификатор [типа объекта CRM](https://apidocs.bitrix24.ru/api-reference/crm/data-types.html#object_type). Возможные значения:
  - `1` — [лид](https://chugunov.pro/api-bitrix24/crm/leads/)
  - `2` — [сделка](https://chugunov.pro/api-bitrix24/crm/deals/)
  - `3` — [контакт](https://chugunov.pro/api-bitrix24/crm/contacts/)
  - `4` — [компания](https://chugunov.pro/api-bitrix24/crm/companies/)
  - `7` — [предложение](https://chugunov.pro/api-bitrix24/crm/quote/)
  - `31` — [счет](https://apidocs.bitrix24.ru/api-reference/crm/universal/invoice.html)
  - `128` — [смарт-процесс](https://chugunov.pro/api-bitrix24/crm/universal/). Идентификатор конкретного смарт-процесса можно узнать методами [crm.enum.ownertype](https://chugunov.pro/api-bitrix24/crm/auxiliary/enum/crm-enum-owner-type/) и [crm.type.list](https://chugunov.pro/api-bitrix24/crm/universal/user-defined-object-types/crm-type-list/)
- `entityIds` `integer[]` — обязательный. Массив идентификаторов элементов, которые необходимо объединить. Минимум два элемента

## Ответ

HTTP-статус: 200

```json
{
    "result": {
        "STATUS": "SUCCESS",
        "ENTITY_IDS": [101, 102]
    },
    "time": {
        "start": 1750754639.300838,
        "finish": 1750754641.350269,
        "duration": 2.049431085586548,
        "processing": 2.0271031856536865,
        "date_start": "2025-06-24T11:43:59+03:00",
        "date_finish": "2025-06-24T11:44:01+03:00",
        "operating_reset_at": 1750755239,
        "operating": 0
    }
}
```

### Возвращаемые данные

- `STATUS` `string`. Статус выполнения операции. Возможные значения:
  - `SUCCESS` — объединение прошло успешно
  - `CONFLICT` — возник конфликт данных, автоматическое объединение невозможно
  - `ERROR` — произошла [ошибка](#errors)
- `ENTITY_IDS` `integer[]`. Массив идентификаторов элементов, которые были удалены при объединении
- `time` `time`. Информация о времени выполнения запроса

## Ошибки

HTTP-статус: 400

```json
{
    "error": 0,
    "error_description": "The parameter entityIds must contains at least two elements."
}
```

- `403` — `Access denied`. У пользователя нет прав на изменение или удаление элементов CRM
- `400` — `The parameter entityTypeId is required.`. Не указан обязательный параметр `entityTypeId`
- `400` — `The parameter entityIds does not contains valid elements.`. Не переданы или не найдены элементы для объединения
- `400` — `The parameter entityIds must contains at least two elements.`. Для объединения требуется минимум два элемента
- `400` — `Owner was not found`. Объект не найден
- `400` — `Entity type {entityTypeName} is not supported`. Указан неподдерживаемый тип объекта
- `400` — `CRM_FEATURE_RESTRICTION_ERROR`. Ограничение тарифа

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

### cURL (Webhook)

```bash
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -d '{"params":{"entityTypeId":3,"entityIds":[100,101,102]}}' \
     https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/crm.entity.mergeBatch
```

### cURL (OAuth)

```bash
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -d '{"auth":"**put_access_token_here**","params":{"entityTypeId":3,"entityIds":[100,101,102]}}' \
     https://**put_your_bitrix24_address**/rest/crm.entity.mergeBatch
```

### JS (TS)

```ts
// This snippet is an ES module: top-level await requires type="module" or a bundler.
// $b24 is an already-initialized SDK instance (see the SDK "Get started" guide).
import { Text } from '@bitrix24/b24jssdk'
import type { B24Frame } from '@bitrix24/b24jssdk'

declare const $b24: B24Frame

// Shape of the payload returned in result (match the "response handling" section of the page)
type MergeBatchResult = {
  STATUS: 'SUCCESS' | 'CONFLICT' | 'ERROR'
  ENTITY_IDS: number[]
}

try {
  const response = await $b24.actions.v2.call.make<MergeBatchResult>({
    method: 'crm.entity.mergeBatch',
    params: {
      params: {
        entityTypeId: 3,
        entityIds: [100, 101, 102],
      },
    },
    requestId: Text.getUuidRfc4122()
  })

  // The payload is available only on a successful response
  if (!response.isSuccess) {
    console.error(response.getErrorMessages().join('; '))
  } else {
    const result = response.getData()!.result
    console.info('Merge status:', result.STATUS, '| Deleted entity IDs:', result.ENTITY_IDS)
  }
} catch (error) {
  // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
  console.error(error)
}
```

### JS (UMD)

```html
<!-- Load the SDK (UMD build); it is exposed as the global B24Js -->
<script src="https://unpkg.com/@bitrix24/b24jssdk@1/dist/umd/index.min.js"></script>
<script>
  async function mergeEntities() {
    try {
      // Initialize the SDK inside a Bitrix24 frame
      const $b24 = await B24Js.initializeB24Frame()

      const response = await $b24.actions.v2.call.make({
        method: 'crm.entity.mergeBatch',
        params: {
          params: {
            entityTypeId: 3,
            entityIds: [100, 101, 102],
          },
        },
        requestId: B24Js.Text.getUuidRfc4122()
      })

      // The payload is available only on a successful response
      if (!response.isSuccess) {
        console.error(response.getErrorMessages().join('; '))
        return
      }

      const result = response.getData().result
      console.info('Merge status:', result.STATUS, '| Deleted entity IDs:', result.ENTITY_IDS)
    } catch (error) {
      // Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
      console.error(error)
    }
  }

  document.addEventListener('DOMContentLoaded', mergeEntities)
</script>
```

### Python

```python
from b24pysdk.errors import BitrixAPIError, BitrixSDKException

try:
    bitrix_response = client.crm.entity.merge_batch(
        params={
            "entityTypeId": 3,
            "entityIds": [
                100,
                101,
                102,
            ],
        },
    ).response
    result = bitrix_response.result
    print(result)
except BitrixAPIError as error:
    print(
        "Ошибка Bitrix API",
        f"error: {error.error}",
        f"error_description: {error.error_description}",
        sep="\n",
    )
except BitrixSDKException as error:
    print(f"Ошибка Bitrix SDK: {error.message}")
except Exception as error:
    print(f"Непредвиденная ошибка: {error}")
```

### PHP

```php
try {
    $response = $b24Service
        ->core
        ->call(
            'crm.entity.mergeBatch',
            [
                'params' => [
                    'entityTypeId' => 3,
                    'entityIds'    => [100, 101, 102]
                ]
            ]
        );

    $result = $response
        ->getResponseData()
        ->getResult();

    if ($result->error()) {
        error_log($result->error());
    } else {
        echo 'Success: ' . print_r($result->data(), true);
    }

} catch (Throwable $e) {
    error_log($e->getMessage());
    echo 'Error merging entities: ' . $e->getMessage();
}
```

### BX24.js

```js
BX24.callMethod(
    'crm.entity.mergeBatch',
    {
        params: {
            entityTypeId: 3,
            entityIds: [100, 101, 102]
        }
    },
    function(result) {
        if(result.error())
            console.error(result.error());
        else
            console.dir(result.data());
    }
);
```

### PHP CRest

```php
require_once('crest.php');

$result = CRest::call(
    'crm.entity.mergeBatch',
    [
        'params' => [
            'entityTypeId' => 3,
            'entityIds' => [100, 101, 102]
        ]
    ]
);

echo '<PRE>';
print_r($result);
echo '</PRE>';
```

### Go

```go
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "crm.entity.mergeBatch", b24.Params{
	"params": b24.Params{
		"entityTypeId": 3,
		"entityIds":    []int{100, 101, 102},
	},
})
if err != nil {
	return fmt.Errorf("crm.entity.mergeBatch: %w", err)
}

var item struct {
	Status string `json:"STATUS"`
}
if err := json.Unmarshal(res.Result, &item); err != nil {
	return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.Status)
```

Оригинал в официальной документации: https://apidocs.bitrix24.ru/api-reference/crm/duplicates/crm-entity-merge-batch.html
