Загрузить документ crm.documentgenerator.document.upload

Выберите инструмент для разработки с AI-агентом:

  • используйте Битрикс24 Вайбкод, чтобы создать приложение для Битрикс24 по описанию задачи без знания языков программирования. Агент напишет код и разместит приложение на сервере без ручной настройки хостинга
  • используйте MCP-сервер, чтобы разрабатывать интеграцию через REST API в своем проекте. Агент будет обращаться к официальной REST-документации

Scope: crm

Кто может выполнять метод: пользователь с правом "изменения" документов генератора документов

Метод crm.documentgenerator.document.upload загружает готовый документ и прикрепляет его к CRM-объекту.

Параметры метода

Обязательные параметры отмечены *

Название
тип

Описание

fields*
object

Объект с параметрами загрузки документа (подробнее)

Параметр fields

Обязательные параметры отмечены *

Название
тип

Описание

entityTypeId*
integer

Идентификатор типа CRM-объекта.

Типичные значения:

  • 1 — лид
  • 2 — сделка
  • 3 — контакт
  • 4 — компания
  • 7 — коммерческое предложение

Для смарт-процессов передается их entityTypeId, например 177

entityId*
integer

Идентификатор CRM-объекта, к которому прикрепляется документ

fileContent*
string

Содержимое DOCX-файла в формате base64.

Подробнее: Как загружать файлы

region*
string

Код региона шаблона, например ru

title*
string

Название документа

number*
string

Номер документа

pdfContent
string

Содержимое PDF-файла в формате base64.

Подробнее: Как загружать файлы

imageContent
string

Содержимое изображения в формате base64.

Подробнее: Как загружать файлы

Особенности метода

pdfUrl и imageUrl могут отсутствовать сразу после загрузки, так как конвертация выполняется асинхронно. Для проверки результата используйте crm.documentgenerator.document.get

Примеры кода

Как использовать примеры в документации

Пример загрузки документа, где:

  • entityTypeId — 2 (сделка)
  • entityId — 101
  • region — ru
  • название документа — Демонстрационная реализация товара
  • номер документа — 2026-001
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"entityTypeId":2,"entityId":101,"fileContent":"**base64_docx_content**","region":"ru","title":"Демонстрационная реализация товара","number":"2026-001","pdfContent":"**base64_pdf_content**","imageContent":"**base64_image_content**"}}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/crm.documentgenerator.document.upload
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"entityTypeId":2,"entityId":101,"fileContent":"**base64_docx_content**","region":"ru","title":"Демонстрационная реализация товара","number":"2026-001","pdfContent":"**base64_pdf_content**","imageContent":"**base64_image_content**"},"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/crm.documentgenerator.document.upload
// 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 DocumentUploadResult = {
  document: {
    id: string
    title: string
    number: string
    createTime: ISODate
    updateTime: ISODate
    createdBy: string
    updatedBy: string | null
    changeStampsEnabled: boolean
    changeStampsDisabledReason: string
    changeQrCodeEnabled: boolean
    qrCodeEnabled: boolean
    changeQrCodeDisabledReason: string
    products: {
      currencyId: string
      totalSum: string
      totalRows: number
    }
    stampsEnabled: boolean
    isTransformationError: boolean
    downloadUrl: string
    downloadUrlMachine: string
    publicUrl: string | null
    templateId: string
    pullTag: string
    emailDiskFile: number
    entityTypeId: string
    entityId: string
    values: Record<string, unknown> | null
  }
}

try {
  const response = await $b24.actions.v2.call.make<DocumentUploadResult>({
    method: 'crm.documentgenerator.document.upload',
    params: {
      fields: {
        entityTypeId: 2,
        entityId: 101,
        fileContent: '**base64_docx_content**',
        region: 'ru',
        title: 'Demo Sales Document',
        number: '2026-001',
        pdfContent: '**base64_pdf_content**',
        imageContent: '**base64_image_content**',
      },
    },
    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 uploadDocument() {
    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.upload',
        params: {
          fields: {
            entityTypeId: 2,
            entityId: 101,
            fileContent: '**base64_docx_content**',
            region: 'ru',
            title: 'Demo Sales Document',
            number: '2026-001',
            pdfContent: '**base64_pdf_content**',
            imageContent: '**base64_image_content**',
          },
        },
        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', uploadDocument)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException

try:
    bitrix_response = client.crm.documentgenerator.document.upload(
        fields={
            "entityTypeId": 2,
            "entityId": 101,
            "fileContent": "**base64_docx_content**",
            "region": "ru",
            "title": "Демонстрационная реализация товара",
            "number": "2026-001",
            "pdfContent": "**base64_pdf_content**",
            "imageContent": "**base64_image_content**",
        },
    ).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.upload',
            [
                'fields' => [
                    'entityTypeId' => 2,
                    'entityId' => 101,
                    'fileContent' => '**base64_docx_content**',
                    'region' => 'ru',
                    'title' => 'Демонстрационная реализация товара',
                    'number' => '2026-001',
                    'pdfContent' => '**base64_pdf_content**',
                    'imageContent' => '**base64_image_content**',
                ],
            ]
        );

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

    echo '<pre>';
    print_r($result);
    echo '</pre>';

} catch (Throwable $e) {
    error_log($e->getMessage());
    echo 'Error uploading document: ' . $e->getMessage();
}
BX24.callMethod(
    'crm.documentgenerator.document.upload',
    {
        fields: {
            entityTypeId: 2,
            entityId: 101,
            fileContent: '**base64_docx_content**',
            region: 'ru',
            title: 'Демонстрационная реализация товара',
            number: '2026-001',
            pdfContent: '**base64_pdf_content**',
            imageContent: '**base64_image_content**',
        },
    },
    (result) => {
        result.error()
            ? console.error(result.error())
            : console.info(result.data())
        ;
    },
);
require_once('crest.php');

$result = CRest::call(
    'crm.documentgenerator.document.upload',
    [
        'fields' => [
            'entityTypeId' => 2,
            'entityId' => 101,
            'fileContent' => '**base64_docx_content**',
            'region' => 'ru',
            'title' => 'Демонстрационная реализация товара',
            'number' => '2026-001',
            'pdfContent' => '**base64_pdf_content**',
            'imageContent' => '**base64_image_content**',
        ],
    ]
);

echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "crm.documentgenerator.document.upload", b24.Params{
	"fields": b24.Params{
		"entityTypeId": 2,
		"entityId":     101,
		"fileContent":  "**base64_docx_content**",
		"region":       "ru",
		"title":        "Демонстрационная реализация товара",
		"number":       "2026-001",
		"pdfContent":   "**base64_pdf_content**",
		"imageContent": "**base64_image_content**",
	},
})
if err != nil {
	return fmt.Errorf("crm.documentgenerator.document.upload: %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=63",
            "publicUrl": null,
            "title": "Демонстрационная реализация товара",
            "number": "2026-001",
            "id": "63",
            "createTime": "2026-03-20T17:08:24+03:00",
            "createdBy": "577",
            "updateTime": "2026-03-20T17:08:24+03:00",
            "updatedBy": null,
            "stampsEnabled": false,
            "isTransformationError": false,
            "values": {
                "productsTableVariant": "",
                "_creationMethod": "rest"
            },
            "templateId": "55",
            "pullTag": "TRANSFORMDOCUMENT63",
            "emailDiskFile": 5619,
            "entityId": "101",
            "entityTypeId": "2",
            "downloadUrlMachine": "https://bitrix.bitrix24.ru/rest/crm.documentgenerator.document.download.json?auth=***&token=***"
        }
    },
    "time": {
        "start": 1774015704,
        "finish": 1774015705.08562,
        "duration": 1.0856199264526367,
        "processing": 1,
        "date_start": "2026-03-20T17:08:24+03:00",
        "date_finish": "2026-03-20T17:08:25+03:00",
        "operating_reset_at": 1774016304,
        "operating": 1.0284008979797363
    }
}

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

Название
тип

Описание

result
object

Корневой объект ответа. Содержит структуру result

time
time

Информация о времени выполнения запроса

Тип result

Название
тип

Описание

document
object

Данные загруженного документа. Структура описана в типе document

Тип document

Название
тип

Описание

id
integer | string

Идентификатор документа

title
string

Название документа

number
string

Номер документа

createTime
datetime

Дата создания

updateTime
datetime

Дата обновления

createdBy
integer | string

Идентификатор пользователя, создавшего документ

updatedBy
integer | string | null

Идентификатор пользователя, обновившего документ

changeStampsEnabled
boolean

Можно ли изменить признак подстановки печати и подписи

changeStampsDisabledReason
string

Причина, почему нельзя изменить признак подстановки печати и подписи

changeQrCodeEnabled
boolean

Можно ли включить или выключить QR-код

qrCodeEnabled
boolean

Текущее состояние QR-кода

changeQrCodeDisabledReason
string

Причина, почему нельзя изменить QR-код

products
object

Сводная информация по товарам документа (currencyId, totalSum, totalRows)

stampsEnabled
boolean

Признак подстановки печати и подписи

downloadUrl
string

Ссылка на скачивание документа

downloadUrlMachine
string

Ссылка на скачивание документа для машинного доступа

publicUrl
string | null

Публичная ссылка на документ

isTransformationError
boolean

Признак ошибки конвертации документа

transformationErrorMessage
string

Текст ошибки конвертации, если isTransformationError = true

transformationErrorCode
string

Код ошибки конвертации, если isTransformationError = true

templateId
integer | string

Идентификатор шаблона

pullTag
string

Тег события трансформации документа

emailDiskFile
integer

Идентификатор файла в Диске для отправки по email

entityTypeId
integer | string

Идентификатор типа CRM-объекта

entityId
integer | string

Идентификатор CRM-объекта

values
object | null

Значения полей документа

imageUrl
string

Ссылка на изображение документа, если уже создано

pdfUrl
string

Ссылка на PDF-файл документа, если уже создан

imageUrlMachine
string

Ссылка на изображение документа для машинного доступа

pdfUrlMachine
string

Ссылка на PDF-документ для машинного доступа

Обработка ошибок

HTTP-статус: 400

{
    "error": "100",
    "error_description": "Invalid value {} to match with parameter {fields}. Should be value of type array."
}

Название
тип

Описание

error
string

Строковый код ошибки. Состоит из цифр, латинских букв и знака подчеркивания. Может прийти пустым — тогда причину показывает только error_description

error_description
string

Текст ошибки для разработчика. Не показывайте его конечному пользователю без обработки

Возможные коды ошибок

Код

Описание

Значение

100

Could not find value for parameter

Не передан обязательный параметр fields

100

Invalid value {} to match with parameter {fields}. Should be value of type array.

Параметр fields передан не в формате объекта

0

Empty required fields: entityTypeId, fileContent, region, entityId

Не переданы обязательные поля в fields

0

Empty required fields: fileContent

Не передано обязательное поле fields.fileContent

0

Wrong "entityTypeId" field value

Передан некорректный fields.entityTypeId

0

No provider for entityTypeId

Для fields.entityTypeId не найден подходящий CRM-провайдер

0

Wrong "entityId" field value

Передан некорректный fields.entityId

0

Missing file content

Не передан или не прочитан fields.fileContent

0

Could not save file

Не удалось сохранить загруженный файл

0

Module crm is not installed

Модуль crm недоступен на этапе DG-обработки

0

Wrong provider ...

Некорректно определен провайдер документа

0

Application not found

Не удалось определить текущее REST-приложение

0

Error generating file for template

Не удалось создать служебный файл для скрытого шаблона

0

Error getting template

Не удалось получить или создать скрытый шаблон для загрузки

Пустое значение

You do not have permissions to view documents

Недостаточно прав на просмотр документов

Пустое значение

Module documentgenerator is not installed

Модуль documentgenerator недоступен

Статусы и коды системных ошибок

HTTP-статус: 4xx, 5xx

Описанные ниже ошибки возвращает сам REST API, а не логика конкретного метода. Они могут прийти в ответ на любой метод.

Статус

Код
Текст ошибки

Описание

500

INTERNAL_SERVER_ERROR
Internal server error

Возникла внутренняя ошибка сервера. Повторите вызов, а если ошибка сохраняется, обратитесь к администратору сервера или в техническую поддержку Битрикс24

500

ERROR_UNEXPECTED_ANSWER
Server returned an unexpected response

Сервер вернул неожиданный ответ. Повторите вызов, а если ошибка сохраняется, обратитесь к администратору сервера или в техническую поддержку Битрикс24

503

QUERY_LIMIT_EXCEEDED
Too many requests

Превышен лимит на интенсивность запросов

429

OPERATION_TIME_LIMIT
Method is blocked due to operation time limit

Метод заблокирован из-за превышения лимита на ресурсоемкость запросов. Блокировка снимается автоматически, когда накопленное время выполнения метода перестает превышать лимит

401

NO_AUTH_FOUND
Wrong authorization data

В запросе нет авторизационных данных: не передан ни access-токен, ни код вебхука

401

INVALID_REQUEST
Https required

Методы вызываются только по протоколу HTTPS

401

OVERLOAD_LIMIT
REST API is blocked due to overload

REST API заблокирован из-за перегрузки. Это ручная индивидуальная блокировка. Чтобы ее снять, обратитесь в техническую поддержку Битрикс24

401

ACCESS_DENIED
REST is available only on commercial plans

REST API доступен только на коммерческих тарифах. У вебхука текст ошибки другой — REST is available only by subscription

401

INVALID_CREDENTIALS
Invalid request credentials

Не найден активный вебхук с указанным идентификатором пользователя и секретным кодом

404

ERROR_METHOD_NOT_FOUND
Method not found!

Метод с таким именем не найден. Имя написано с ошибкой, метода нет в REST API или он недоступен без нужного скоупа

401

insufficient_scope
The request requires higher privileges than provided by the webhook token

Запрос требует более широких прав, чем есть у токена: у вебхука это выданные ему права, у приложения — скоуп. У приложения текст ошибки заканчивается на provided by the access token

401

expired_token
The access token provided has expired

Срок действия access-токена истек

401

user_access_error
The user does not have access to the application

Приложение установлено, но администратор Битрикс24 открыл доступ к нему только конкретным пользователям

403

PORTAL_DELETED
Portal was deleted

Публичная часть сайта закрыта. Чтобы открыть ее на коробочной установке, отключите опцию «Временное закрытие публичной части сайта». Путь к настройке: Рабочий стол > Настройки > Настройки продукта > Настройки модулей > Главный модуль > Временное закрытие публичной части сайта

Продолжите изучение