ID заказа изменился без ошибки: как JSON-число ломает внешний идентификатор
Показываю на проверенном примере Node.js, почему внешний ID 9007199254740993 незаметно меняется после JSON.parse, как закрепить строковый контракт и проверить повторную доставку в интеграции с 1С-Битрикс.

В этой статье
Если идентификатор относится к заказу, товару или торговому предложению и не участвует в арифметике, передавайте его в JSON строкой. Числовое значение 9007199254740993 после JSON.parse в JavaScript превращается в 9007199254740992 — без исключения и без предупреждения. Для интеграции это означает риск неверного сопоставления, дубля при повторной доставке или обновления не той записи.
Ниже — воспроизводимый пример для пользовательского адаптера на Node.js и правила контракта. Он не описывает ошибку штатного обмена 1С с «1С-Битрикс: Управление сайтом»: проблема возникает на границе систем, когда разработчики сами объявляют непрозрачный идентификатор числом.
Минимальный пример: корректный JSON, неверный идентификатор
Проверка выполнена 4 декабря 2026 года в Node.js 24.22.3 с V8 13.6.233.17-node.63. Скрипт только разбирает фиксированные строки в памяти: файлов, сети, базы данных и рабочего магазина он не меняет.
Сохраните код в отдельный файл external-id-json-test.mjs внутри временного каталога:
const unsafePayload = '{"external_id":9007199254740993}';
const safePayload = '{"external_id":"9007199254740993"}';
const leadingZeroPayload = '{"external_id":"000123"}';
function readExternalId(payload) {
const message = JSON.parse(payload);
if (typeof message.external_id !== 'string') {
throw new TypeError('external_id must be a JSON string');
}
if (!/^[0-9]{1,20}$/.test(message.external_id)) {
throw new RangeError('external_id must contain 1–20 decimal digits');
}
return message.external_id;
}
const unsafe = JSON.parse(unsafePayload);
console.log(`unsafe parsed: ${unsafe.external_id}`);
console.log(`unsafe exact: ${String(unsafe.external_id) === '9007199254740993'}`);
const safe = readExternalId(safePayload);
console.log(`safe parsed: ${safe}`);
console.log(`safe replay stable: ${safe === readExternalId(safePayload)}`);
console.log(`leading zero preserved: ${readExternalId(leadingZeroPayload)}`);
for (const payload of [unsafePayload, '{"external_id":"12.3"}']) {
try {
readExternalId(payload);
} catch (error) {
console.log(`rejected: ${error.message}`);
}
}
Запустите его обычным пользователем:
node external-id-json-test.mjs
Ожидаемый и полученный вывод:
unsafe parsed: 9007199254740992
unsafe exact: false
safe parsed: 9007199254740993
safe replay stable: true
leading zero preserved: 000123
rejected: external_id must be a JSON string
rejected: external_id must contain 1–20 decimal digits
Ключевая строка — unsafe parsed. Отправитель записал 9007199254740993, а получатель уже видит 9007199254740992. Обратное преобразование в строку не восстановит потерянную единицу: String(message.external_id) вернёт искажённое значение.
Почему парсер не считает это ошибкой
Синтаксис JSON допускает такое число. Но RFC 8259 предупреждает об ограничениях совместимости: целые числа в диапазоне от −(2^53)+1 до (2^53)−1 можно ожидать точными в широко используемых реализациях. Значение 9007199254740993 лежит за этой границей.
В JavaScript тип Number хранит число в формате двойной точности. ECMAScript определяет Number.MAX_SAFE_INTEGER как 9007199254740991 и отдельно показывает, что 9007199254740992 и 9007199254740993 представлены одним значением Number. Поэтому JSON.parse успешно возвращает число, но тождество исходному тексту уже потеряно.
Это не означает, что любой JSON-парсер во всех языках обязательно испортит значение. Некоторые библиотеки умеют сохранять произвольную точность. Подвох в другом: контракт, зависящий от конкретного парсера и его настроек, плохо переносится между сервисами. Непрозрачный идентификатор строкой устраняет эту зависимость.
Строка нужна не только из-за 2^53
У идентификатора есть форма, а не числовая величина. Значения 000123 и 123 могут обозначать разные объекты у источника. Если поле объявлено числом, ведущие нули исчезнут ещё до бизнес-логики. Завтра источник может добавить префикс склада, дефис или перейти на UUID — и числовой контракт придётся ломать.
Регулярное выражение из примера — не универсальный стандарт. Оно подходит только для учебного условия «от 1 до 20 десятичных цифр». Для реальной интеграции зафиксируйте собственную грамматику: допустимые символы, длину, регистр, ведущие нули и возможность составного ключа.
Как закрепить безопасный контракт
- Передавайте external_id как JSON-строку на всех участках: отправитель, очередь, адаптер, журнал сообщений и приёмник.
- Проверяйте тип сразу после разбора сообщения. Число отклоняйте; не «чините» его через String(), потому что точность могла быть потеряна раньше.
- Храните внешний идентификатор отдельно от внутреннего числового ID заказа или товара. Для пары «источник + внешний ID» задайте уникальность.
- Согласуйте сравнение строк. Регистронезависимая сортировка базы может неожиданно считать abc и ABC одинаковыми, если источник различает регистр.
- При повторной доставке сначала ищите точное сопоставление, затем обновляйте существующий объект. Создание новой записи — только когда сопоставления нет.
На маленьком примере повтор одного и того же строкового сообщения даёт safe replay stable: true. Это проверяет стабильность чтения, но не доказывает идемпотентность всей интеграции. В рабочем адаптере нужны ещё уникальное ограничение в хранилище сопоставлений и атомарная операция «найти или создать», иначе два параллельных обработчика всё равно могут создать дубль.
Где это место в интеграции с 1С-Битрикс
В пользовательской интеграции внешний ключ лучше проверять до вызова API «1С-Битрикс: Управление сайтом». Сначала адаптер валидирует строку и ищет её в таблице сопоставлений, затем получает внутренний ID элемента, торгового предложения или заказа и только после этого выполняет обновление.
Не подменяйте внешний ключ внутренним ID Битрикс. Внутренний ID принадлежит конкретной базе и может не совпасть после переноса с пересозданием объектов или импорта. Обычное восстановление корректной резервной копии само по себе ID не меняет. Внешний ключ принадлежит источнику и нужен, чтобы повторное сообщение нашло тот же объект.
Если интеграция уже создаёт дубли, сначала сравните фактические внешние ключи и маршрут сообщения. В разборе о дублях товаров при обмене перечислены и другие причины: меняющийся идентификатор, разные каталоги и повторное создание вместо обновления. Для требований к обмену до разработки пригодится спецификация интеграции интернет-магазина с 1С.
Если числовой контракт уже работает
Не меняйте тип поля массово вслепую. Сначала выгрузите таблицу сопоставлений и резервную копию, затем найдите значения за пределами 9007199254740991, ведущие нули в исходной системе и возможные коллизии. Отдельно проверьте, не записан ли уже один и тот же объект под двумя искажёнными ключами.
Переход удобнее делать версионно: новый отправитель посылает строку, получатель временно принимает только явно согласованные версии сообщения, а старый числовой формат журналируется и отклоняется либо обрабатывается изолированным совместимым маршрутом. Условие завершения миграции — ноль сообщений старого формата за согласованный период и успешный повторный прогон контрольных идентификаторов.
Приёмочные проверки
- 9007199254740991 сохраняется без изменения, но всё равно приходит строкой: идентификатор не становится числом только потому, что помещается в безопасный диапазон.
- 9007199254740993 проходит строкой и возвращается побайтно тем же значением.
- 000123 сохраняет ведущие нули.
- Числовой external_id отклоняется на границе, а ошибка содержит безопасное описание без полного клиентского сообщения.
- Повтор того же сообщения обновляет тот же объект и не создаёт дубль.
- Два параллельных повтора упираются в уникальность пары «источник + внешний ID».
- Недопустимый символ, пустая строка и превышение длины дают предсказуемый отказ до обращения к API Битрикс.
Критерий результата простой: идентификатор остаётся точной строкой от входного сообщения до таблицы сопоставлений, а повторная доставка находит прежний внутренний объект. Если на любом участке поле снова становится Number, контракт ещё не исправлен.
If an identifier relates to an order, product, or product variant and is not used in arithmetic, pass it as a string in JSON. The numeric value 9007199254740993 becomes 9007199254740992 after JSON.parse in JavaScript—without exception and without warning. For integration, this means the risk of incorrect matching, duplicates on re-delivery, or updating the wrong record.
Below is a reproducible example for a custom adapter in Node.js and the contract rules. It does not describe an error in the standard 1C to 1C-Bitrix: Site Management exchange; the issue arises at the system boundary when developers themselves declare an opaque identifier as a number.
Minimal example: valid JSON, incorrect identifier
The check was performed on December 4, 2026, in Node.js 24.22.3 with V8 13.6.233.17-node.63. The script only parses fixed strings in memory: it does not modify files, the network, the database, or the working store.
Save the code to a separate file external-id-json-test.mjs inside a temporary directory:
const unsafePayload = '{"external_id":9007199254740993}';
const safePayload = '{"external_id":"9007199254740993"}';
const leadingZeroPayload = '{"external_id":"000123"}';
function readExternalId(payload) {
const message = JSON.parse(payload);
if (typeof message.external_id !== 'string') {
throw new TypeError('external_id must be a JSON string');
}
if (!/^[0-9]{1,20}$/.test(message.external_id)) {
throw new RangeError('external_id must contain 1–20 decimal digits');
}
return message.external_id;
}
const unsafe = JSON.parse(unsafePayload);
console.log(`unsafe parsed: ${unsafe.external_id}`);
console.log(`unsafe exact: ${String(unsafe.external_id) === '9007199254740993'}`);
const safe = readExternalId(safePayload);
console.log(`safe parsed: ${safe}`);
console.log(`safe replay stable: ${safe === readExternalId(safePayload)}`);
console.log(`leading zero preserved: ${readExternalId(leadingZeroPayload)}`);
for (const payload of [unsafePayload, '{"external_id":"12.3"}']) {
try {
readExternalId(payload);
} catch (error) {
console.log(`rejected: ${error.message}`);
}
}
Run it as a regular user:
node external-id-json-test.mjs
Expected and actual output:
unsafe parsed: 9007199254740992
unsafe exact: false
safe parsed: 9007199254740993
safe replay stable: true
leading zero preserved: 000123
rejected: external_id must be a JSON string
rejected: external_id must contain 1–20 decimal digits
The key line is "unsafe parsed". The sender wrote 9007199254740993, but the receiver already sees 9007199254740992. Converting back to a string does not restore the lost unit: String(message.external_id) will return a distorted value.
Why the parser does not treat this as an error
JSON syntax allows such a number. However, RFC 8259 warns about compatibility limitations: integers in the range from −(2^53)+1 to (2^53)−1 can be expected to be exact in widely used implementations. The value 9007199254740993 lies beyond this limit.
In JavaScript, the Number type stores numbers in double-precision format. ECMAScript defines Number.MAX_SAFE_INTEGER as 9007199254740991 and separately shows that 9007199254740992 and 9007199254740993 are represented by the same Number value. Therefore, JSON.parse successfully returns a number, but identity with the original text is already lost.
This does not mean that any JSON parser in any language will necessarily corrupt the value. Some libraries can preserve arbitrary precision. The catch is different: a contract depending on a specific parser and its settings does not transfer well between services. An opaque identifier as a string eliminates this dependency.
A string is needed not only because of 2^53
An identifier has a form, not a numeric value. The values 000123 and 123 may represent different objects at the source. If the field is declared as a number, leading zeros disappear even before business logic. Tomorrow the source may add a warehouse prefix, a hyphen, or switch to UUID, and the numeric contract will have to be broken.
The regular expression from the example is not a universal standard. It fits only the educational condition "from 1 to 20 decimal digits". For real integration, define your own grammar: allowed characters, length, case, leading zeros, and the possibility of a composite key.
How to lock in a safe contract
- Pass external_id as a JSON string at all stages: sender, queue, adapter, message log, and receiver.
- Check the type immediately after parsing the message. Reject numbers; do not "fix" them via String(), as precision may have already been lost.
- Store the external identifier separately from the internal numeric order or product ID. Enforce uniqueness for the "source + external ID" pair.
- Agree on string comparison. Case-insensitive database collation may unexpectedly treat abc and ABC as identical if the source distinguishes case.
- On redelivery, first search for an exact match, then update the existing object. Create a new record only if no match is found.
In a small example, replaying the same string message yields safe replay stable: true. This verifies read stability but does not prove idempotency for the entire integration. A production adapter requires a unique constraint in the mapping store and an atomic "find or create" operation; otherwise, two parallel handlers may still create duplicates.
Where this fits in the 1C-Bitrix integration
In a custom integration, verify the external key before calling the "1C-Bitrix: Site Management" API. First, the adapter validates the string and searches for it in the mapping table, then retrieves the internal ID of the element, product variant, or order, and only then performs the update.
Do not substitute an external key with Bitrix's internal ID. The internal ID belongs to a specific database and may not match after migration involving object recreation or import. Restoring a correct backup does not change the ID by itself. An external key belongs to the source and is needed so that a repeated message finds the same object.
If the integration already creates duplicates, first compare the actual external keys and the message route. The section about product duplicates during exchange lists other causes as well: changing identifiers, different catalogs, and re-creation instead of updates. For exchange requirements before development, the specification for integrating an online store with 1C will be useful.
If the numeric contract is already working
Do not change the field type en masse blindly. First, export the mapping table and a backup, then identify values outside 9007199254740991, leading zeros in the source system, and possible collisions. Separately check whether the same object is already recorded under two distorted keys.
It is more convenient to make the transition versioned: the new sender sends a string, the receiver temporarily accepts only explicitly agreed message versions, and the old numeric format is logged and either rejected or processed via an isolated compatible route. The migration completion condition is zero messages in the old format over an agreed period and a successful re-run of control identifiers.
Acceptance testing
- 9007199254740991 is preserved unchanged but still arrives as a string: the identifier does not become a number just because it fits within the safe range.
- 9007199254740993 passes through as a string and is returned byte-for-byte with the same value.
- 000123 preserves leading zeros.
- A numeric external_id is rejected at the boundary, and the error contains a safe description without the full client message.
- Repeating the same message updates the same object and does not create a duplicate.
- Two parallel repeats hit the uniqueness constraint on the pair "source + external ID".
- An invalid character, an empty string, and exceeding the length limit produce a predictable failure before contacting the Bitrix API.
The result criterion is simple: the identifier remains an exact string from the incoming message to the mapping table, and a repeated delivery finds the original internal object. If the field becomes a Number at any point, the contract is not yet fixed.





Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.