sale.basketitem.addCatalogProduct
Добавить позицию с товаром или услугой из модуля catalog в корзину существующего заказа
Описание
Метод sale.basketitem.addCatalogProduct добавляет позицию с товаром или услугой из модуля catalog в корзину существующего заказа.
Параметры
fields
object
обязательный
Значения полей для создания элемента (позиции) корзины в заказе
Параметр fields
orderId
sale_order.id
обязательный
Идентификатор заказа. Может быть указан только при создании позиции корзины.
Должен быть получен ранее методами sale.order.add или sale.order.list
sort
integer
необязательный
Положение в списке позиций заказа
productid
catalog_product.id
обязательный
Идентификатор товара/вариации
price
double
необязательный
Цена с учетом наценок и скидок (смотрите поле customPrice ниже). Если не указать, будет рассчитана на основе данных каталога.
Поле будет заполнено автоматически, если customPrice !== ‘Y’
basePrice
double
необязательный
Исходная цена без учета наценок и скидок (смотрите поле customPrice ниже). Если не указать, будет рассчитана на основе данных каталога.
Поле будет заполнено автоматически, если customPrice !== ‘Y’
discountPrice
double
необязательный
Величина итоговой скидки или наценки (смотрите поле customPrice ниже). Если не указать, будет рассчитана на основе данных каталога.
Поле будет заполнено автоматически, если customPrice !== ‘Y’
currency
crm_currency.CURRENCY
обязательный
Валюта цены. Должна совпадать с валютой заказа
customPrice
string
необязательный
Указана ли цена вручную:
- Y — цена задана вручную
- N — цена получена из каталога товаров
По умолчанию значение N.
Если указывается значение Y, то данные цены из каталога будут игнорироваться. Необходимо явно задать параметры price, basePrice и discountPrice так, чтобы выполнялось условие basePrice = price + discountPrice
quantity
double
обязательный
Количество товара
xmlId
string
необязательный
Внешний код позиции корзины
name
string
обязательный
Название товара
Примеры запроса
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"orderId":5147,"quantity":1,"productId":4347,"currency":"RUB"}}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/sale.basketitem.addCatalogProduct
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"orderId":5147,"quantity":1,"productId":4347,"currency":"RUB"},"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/sale.basketitem.addCatalogProduct
// 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 AddCatalogProductResult = {
basketItem: {
basePrice: number
canBuy: string
catalogXmlId: string
currency: string
customPrice: string
dateInsert: ISODate | null
dateUpdate: ISODate | null
dimensions: string
discountPrice: number
id: number
measureCode: string
measureName: string
name: string
orderId: number
price: number
productId: number
productXmlId: string
properties: object[]
quantity: number
reservations: object[]
sort: number
type: number
vatIncluded: string
vatRate: number | null
weight: number
xmlId: string
}
}
try {
const response = await $b24.actions.v2.call.make<AddCatalogProductResult>({
method: 'sale.basketitem.addCatalogProduct',
params: {
fields: {
orderId: 5147,
quantity: 1,
productId: 4347,
currency: 'RUB',
},
},
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.basketItem.id, result.basketItem.name, result.basketItem.price)
}
} 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 addCatalogProduct() {
try {
// Initialize the SDK inside a Bitrix24 frame
const $b24 = await B24Js.initializeB24Frame()
const response = await $b24.actions.v2.call.make({
method: 'sale.basketitem.addCatalogProduct',
params: {
fields: {
orderId: 5147,
quantity: 1,
productId: 4347,
currency: 'RUB',
},
},
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.basketItem.id, result.basketItem.name, result.basketItem.price)
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
}
document.addEventListener('DOMContentLoaded', addCatalogProduct)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
fields = {
"orderId": 5147,
"quantity": 1,
"productId": 4347,
"currency": "RUB",
}
try:
bitrix_response = client.sale.basketitem.add_catalog_product(
fields=fields,
).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(
'sale.basketitem.addCatalogProduct',
[
'fields' => [
'orderId' => 5147,
'quantity' => 1,
'productId' => 4347,
'currency' => 'RUB',
],
]
);
$result = $response
->getResponseData()
->getResult();
echo 'Success: ' . print_r($result, true);
// Нужная вам логика обработки данных
processData($result);
} catch (Throwable $e) {
error_log($e->getMessage());
echo 'Error adding catalog product: ' . $e->getMessage();
}
BX24.callMethod(
"sale.basketitem.addCatalogProduct",
{
fields: {
orderId: 5147,
quantity: 1,
productId: 4347,
currency: 'RUB',
}
},
)
.then(
function(result)
{
if (result.error())
{
console.error(result.error());
}
else
{
console.log(result.data());
}
},
function(error)
{
console.info(error);
}
);
require_once('crest.php');
$result = CRest::call(
'sale.basketitem.addCatalogProduct',
[
'fields' => [
'orderId' => 5147,
'quantity' => 1,
'productId' => 4347,
'currency' => 'RUB',
]
]
);
echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "sale.basketitem.addCatalogProduct", b24.Params{
"fields": b24.Params{
"orderId": 5147,
"quantity": 1,
"productId": 4347,
"currency": "RUB",
},
})
if err != nil {
return fmt.Errorf("sale.basketitem.addCatalogProduct: %w", err)
}
// Метод заворачивает ответ в объект с ключом "basketItem".
raw, ok := b24.Unwrap(res.Result, "basketItem")
if !ok {
return fmt.Errorf("в ответе нет ключа basketItem")
}
var item struct {
BasePrice int `json:"basePrice"`
CanBuy string `json:"canBuy"`
CatalogXmlID string `json:"catalogXmlId"`
Currency string `json:"currency"`
CustomPrice string `json:"customPrice"`
DateInsert string `json:"dateInsert"`
}
if err := json.Unmarshal(raw, &item); err != nil {
return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.BasePrice, item.CanBuy)
Ответ
HTTP-статус: 200
{
"result": {
"basketItem": {
"basePrice": 1234,
"canBuy": "Y",
"catalogXmlId": "FUTURE-ERP-CATALOG",
"currency": "RUB",
"customPrice": "N",
"dateInsert": "2024-04-22T16:36:43+02:00",
"dateUpdate": "2024-04-22T16:36:43+02:00",
"dimensions": "a:3:{s:5:\"WIDTH\";N;s:6:\"HEIGHT\";N;s:6:\"LENGTH\";N;}",
"discountPrice": 124,
"id": 6784,
"measureCode": "796",
"measureName": "шт",
"name": "Услуга2",
"orderId": 5147,
"price": 1110,
"productId": 4347,
"productXmlId": "4347",
"properties": [],
"quantity": 1,
"reservations": [],
"sort": 100,
"type": 2,
"vatIncluded": "N",
"vatRate": null,
"weight": 0,
"xmlId": "bx_662675fba6516"
}
},
"total": 1,
"time": {
"start": 1713796602.830767,
"finish": 1713796604.315251,
"duration": 1.4844841957092285,
"processing": 0.6749260425567627,
"date_start": "2024-04-22T16:36:42+02:00",
"date_finish": "2024-04-22T16:36:44+02:00",
"operating": 0
}
}
Возвращаемые данные
result
object
Корневой элемент ответа
basketItem
sale_basket_item
Объект с данными созданного элемента (позиции) корзины
total
integer
Число обработанных записей
time
time
Информация о времени выполнения запроса
Обработка ошибок
HTTP-статус: 400
{
"error":0,
"error_description":"error"
}
| Код | Описание | Значение |
|---|---|---|
200140400006 |
Module catalog is not exists
Отсутствует модуль Торговый каталог (catalog) |
|
200140400007 |
basket item is not saved - bad data
Позиция не была создана. Ошибка возникает, если передан неверный идентификатор товара или же товар неактивен |
|
200140400008 |
Required fields: fields[ORDER_ID]
Не указан идентификатор заказа |
|
200140400009 |
Order not found
Заказ не найден |
|
200140400011 |
Currency must be the currency of the order
Валюта позиции не совпадает с валютой заказа |
|
200040300010 |
Недостаточно прав для добавления | |
100 |
Не указаны обязательные параметры | |
0 |
Другие ошибки (например, фатальные ошибки) |

