crm.documentgenerator.document.add
Создать новый документ
Описание
Метод crm.documentgenerator.document.add создает документ по шаблону для CRM-объекта.
Параметры
templateId
integer
необязательный
Идентификатор шаблона документа
entityTypeId
integer
необязательный
Идентификатор типа CRM-объекта, для которого создается документ.
Типичные значения:
- 1 — лид
- 2 — сделка
- 3 — контакт
- 4 — компания
- 5 — счет (старая версия)
- 7 — коммерческое предложение
- 31 — счет
Для смарт-процессов передается их entityTypeId, например 177
entityId
integer
необязательный
Идентификатор CRM-объекта, по данным которого создается документ
values
object
необязательный
Объект со значениями полей документа.
Формат:
{
"field_1": "value_1",
"field_2": "value_2"
}
где:
- field_n — код поля документа
- value_n — значение поля
Набор ключей зависит от конкретного шаблона и провайдера данных. Посмотреть доступные поля можно методом crm.documentgenerator.document.getfields
stampsEnabled
integer
необязательный
Подставлять печать и подпись:
- 1 — подставлять
- 0 — не подставлять
По умолчанию 0
fields
object
необязательный
Дополнительные описания полей документа для генерации.
Параметр fields используется для более точечной настройки полей. В большинстве сценариев достаточно параметра values.
В fields передается объект-описание поля (descriptor). Пример:
{
"DocumentTitle": {
"title": "Название документа",
"value": "Демонстрационная реализация товара 1",
"required": "Y",
"default": "Демонстрационная реализация товара 1",
"chain": [
{},
"getTitle"
],
"VALUE": "Тест через fields"
}
}
Список ключей fields не фиксированный и зависит от шаблона.
Как получить доступные параметры:
- до создания документа — crm.documentgenerator.template.getfields, поле templateFields
- для созданного документа — crm.documentgenerator.document.getfields, поле documentFields
Служебные поля SOURCE и DOCUMENT игнорируются.
Некоторые вычисляемые поля могут не переопределяться через fields
Примеры запроса
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"templateId":39,"entityTypeId":2,"entityId":101,"values":{"DocumentNumber":"2026-001"},"fields":{"DocumentTitle":{"title":"Название документа","value":"Демонстрационная реализация товара 1","required":"Y","default":"Демонстрационная реализация товара 1","chain":[{},"getTitle"],"VALUE":"Тест через fields"}},"stampsEnabled":1}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/crm.documentgenerator.document.add
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"templateId":39,"entityTypeId":2,"entityId":101,"values":{"DocumentNumber":"2026-001"},"fields":{"DocumentTitle":{"title":"Название документа","value":"Демонстрационная реализация товара 1","required":"Y","default":"Демонстрационная реализация товара 1","chain":[{},"getTitle"],"VALUE":"Тест через fields"}},"stampsEnabled":1,"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/crm.documentgenerator.document.add
// 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, ISODate } from '@bitrix24/b24jssdk'
declare const $b24: B24Frame
// Shape of the payload returned in result (match the "response handling" section of the page)
type DocumentAddResult = {
document: {
id: number
title: string
number: string
createTime: ISODate
updateTime: ISODate
createdBy: number
updatedBy: number | null
changeStampsEnabled: boolean
changeStampsDisabledReason: string
changeQrCodeEnabled: boolean
qrCodeEnabled: boolean
changeQrCodeDisabledReason: string
products: {
currencyId: string
totalSum: string
totalRows: number
}
stampsEnabled: boolean
downloadUrl: string
downloadUrlMachine: string
publicUrl: string | null
isTransformationError: boolean
transformationErrorMessage: string
transformationErrorCode: string
templateId: string
pullTag: string
emailDiskFile: number
entityTypeId: string
entityId: string
values: Record<string, unknown>
imageUrl: string
pdfUrl: string
}
}
try {
const response = await $b24.actions.v2.call.make<DocumentAddResult>({
method: 'crm.documentgenerator.document.add',
params: {
templateId: 39,
entityTypeId: 2,
entityId: 101,
values: {
DocumentNumber: '2026-001',
},
fields: {
DocumentTitle: {
title: 'Document title',
value: 'Demo product delivery 1',
required: 'Y',
default: 'Demo product delivery 1',
chain: [{}, 'getTitle'],
VALUE: 'Test via fields',
},
},
stampsEnabled: 1,
},
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(result.document.id, result.document.title, result.document.downloadUrl)
}
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
<!-- 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 addDocument() {
try {
// Initialize the SDK inside a Bitrix24 frame
const $b24 = await B24Js.initializeB24Frame()
const response = await $b24.actions.v2.call.make({
method: 'crm.documentgenerator.document.add',
params: {
templateId: 39,
entityTypeId: 2,
entityId: 101,
values: {
DocumentNumber: '2026-001',
},
fields: {
DocumentTitle: {
title: 'Document title',
value: 'Demo product delivery 1',
required: 'Y',
default: 'Demo product delivery 1',
chain: [{}, 'getTitle'],
VALUE: 'Test via fields',
},
},
stampsEnabled: 1,
},
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(result.document.id, result.document.title, result.document.downloadUrl)
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
}
document.addEventListener('DOMContentLoaded', addDocument)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
try:
bitrix_response = client.crm.documentgenerator.document.add(
template_id=39,
entity_type_id=2,
entity_id=101,
values={
"DocumentNumber": "2026-001",
},
fields={
"DocumentTitle": {
"title": "Название документа",
"value": "Демонстрационная реализация товара 1",
"required": "Y",
"default": "Демонстрационная реализация товара 1",
"chain": [
{},
"getTitle",
],
"VALUE": "Тест через fields",
},
},
stamps_enabled=1,
).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}")
try {
$response = $b24Service
->core
->call(
'crm.documentgenerator.document.add',
[
'templateId' => 39,
'entityTypeId' => 2,
'entityId' => 101,
'values' => [
'DocumentNumber' => '2026-001',
],
'fields' => [
'DocumentTitle' => [
'title' => 'Название документа',
'value' => 'Демонстрационная реализация товара 1',
'required' => 'Y',
'default' => 'Демонстрационная реализация товара 1',
'chain' => [
[],
'getTitle',
],
'VALUE' => 'Тест через fields',
],
],
'stampsEnabled' => 1,
]
);
$result = $response
->getResponseData()
->getResult();
echo '<pre>';
print_r($result);
echo '</pre>';
} catch (Throwable $e) {
error_log($e->getMessage());
echo 'Error adding document: ' . $e->getMessage();
}
BX24.callMethod(
'crm.documentgenerator.document.add',
{
templateId: 39,
entityTypeId: 2,
entityId: 101,
values: {
DocumentNumber: '2026-001',
},
fields: {
DocumentTitle: {
title: 'Название документа',
value: 'Демонстрационная реализация товара 1',
required: 'Y',
default: 'Демонстрационная реализация товара 1',
chain: [{}, 'getTitle'],
VALUE: 'Тест через fields',
}
},
stampsEnabled: 1,
},
(result) => {
result.error()
? console.error(result.error())
: console.info(result.data())
;
},
);
require_once('crest.php');
$result = CRest::call(
'crm.documentgenerator.document.add',
[
'templateId' => 39,
'entityTypeId' => 2,
'entityId' => 101,
'values' => [
'DocumentNumber' => '2026-001',
],
'fields' => [
'DocumentTitle' => [
'title' => 'Название документа',
'value' => 'Демонстрационная реализация товара 1',
'required' => 'Y',
'default' => 'Демонстрационная реализация товара 1',
'chain' => [
[],
'getTitle',
],
'VALUE' => 'Тест через fields',
],
],
'stampsEnabled' => 1,
]
);
echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "crm.documentgenerator.document.add", b24.Params{
"templateId": 39,
"entityTypeId": 2,
"entityId": 101,
"values": b24.Params{
"DocumentNumber": "2026-001",
},
"fields": b24.Params{
"DocumentTitle": b24.Params{
"title": "Название документа",
"value": "Демонстрационная реализация товара 1",
"required": "Y",
"default": "Демонстрационная реализация товара 1",
"chain": []any{
b24.Params{},
"getTitle",
},
"VALUE": "Тест через fields",
},
},
"stampsEnabled": 1,
})
if err != nil {
return fmt.Errorf("crm.documentgenerator.document.add: %w", err)
}
// Метод заворачивает ответ в объект с ключом "document".
raw, ok := b24.Unwrap(res.Result, "document")
if !ok {
return fmt.Errorf("в ответе нет ключа document")
}
var item struct {
ChangeStampsEnabled bool `json:"changeStampsEnabled"`
ChangeStampsDisabledReason string `json:"changeStampsDisabledReason"`
ChangeQrCodeEnabled bool `json:"changeQrCodeEnabled"`
QrCodeEnabled bool `json:"qrCodeEnabled"`
ChangeQrCodeDisabledReason string `json:"changeQrCodeDisabledReason"`
DownloadUrl string `json:"downloadUrl"`
}
if err := json.Unmarshal(raw, &item); err != nil {
return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.ChangeStampsEnabled, item.ChangeStampsDisabledReason)
Ответ
HTTP-статус: 200
{
"result": {
"document": {
"changeStampsEnabled": false,
"changeStampsDisabledReason": "В шаблоне нет печатей и подписей",
"changeQrCodeEnabled": false,
"qrCodeEnabled": false,
"changeQrCodeDisabledReason": "В шаблоне нет QR-кода",
"products": {
"currencyId": "UAH",
"totalSum": "0.00",
"totalRows": 0
},
"downloadUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.download&SITE_ID=s1&id=61",
"downloadUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.download.json?...",
"publicUrl": null,
"id": 61,
"title": "Демонстрационная реализация товара 2026-001",
"number": "2026-001",
"createTime": "2026-03-20T13:51:45+03:00",
"createdBy": 577,
"updateTime": "2026-03-20T13:51:45+03:00",
"updatedBy": null,
"stampsEnabled": true,
"isTransformationError": false,
"values": {
"productsTableVariant": "",
"_creationMethod": "rest",
"stampsEnabled": true,
"DocumentNumber": "2026-001"
},
"templateId": "39",
"pullTag": "TRANSFORMDOCUMENT61",
"imageUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.getImage&SITE_ID=s1&id=61",
"pdfUrl": "https://bitrix.bitrix24.ru/bitrix/services/main/ajax.php?action=crm.documentgenerator.document.getPdf&SITE_ID=s1&id=61",
"emailDiskFile": 5605,
"entityId": "101",
"entityTypeId": "2"
}
},
"time": {
"start": 1774003904,
"finish": 1774003905.448804,
"duration": 1.4488039016723633,
"processing": 1,
"date_start": "2026-03-20T13:51:44+03:00",
"date_finish": "2026-03-20T13:51:45+03:00",
"operating_reset_at": 1774004504,
"operating": 0.9240179061889648
}
}
Возвращаемые данные
result
object
Корневой элемент ответа. Возвращает объект result
time
time
Информация о времени выполнения запроса
Обработка ошибок
HTTP-статус: 400
{
"error": "0",
"error_description": "No provider for entityTypeId"
}
| Код | Описание | Значение |
|---|---|---|
0 |
No provider for entityTypeId | Не найден провайдер данных для переданного entityTypeId |
0 |
Empty required parameter "value" | Не передан или передан пустой entityId |
0 |
Cannot create document on deleted template | Нельзя создать документ по удаленному шаблону |
0 |
Cannot create document | Ошибка при создании документа по шаблону |
DOCGEN_ACCESS_ERROR |
Access denied | Нет доступа к созданию документа |
DOCGEN_LIMIT_ERROR |
Maximum count of documents has been reached | Превышен лимит количества документов в тарифе |
0 |
Error getting next number | Не удалось получить следующий номер документа из нумератора |
100 |
Bitrix\\DocumentGenerator\\Template constructor must be is public | Низкоуровневая ошибка при вызове без корректного templateId |
0 |
Module documentgenerator is not installed | Модуль documentgenerator недоступен |
0 |
Шаблон не найден | Шаблон с указанным templateId не найден или недоступен |

