catalog.priceType.add
Создать тип цены
Описание
Метод добавляет новый тип цены.
Параметры
fields
object
обязательный
Значения полей для создания нового типа цены (подробное описание)
Параметр fields
name
string
обязательный
Код типа цены.
Чтобы обеспечить стабильную работу внутренних сервисов, код типа цены необходимо указывать только английскими символами
base
string
необязательный
Является ли тип цены базовым. Возможные значения:
- Y — да
- N — нет
По умолчанию N.
Одновременно может существовать только один базовый тип цены. При добавлении нового базового типа предыдущий потеряет это свойство и перестанет быть базовым
sort
integer
необязательный
Сортировка.
По умолчанию 100
xmlId
string
необязательный
Внешний код.
Можно использовать для синхронизации текущего типа цены с аналогичной позицией во внешней системе
Примеры запроса
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"name":"Wholesale price","base":"N","sort":10,"xmlId":"wholesale"}}' \
https://**put_your_bitrix24_address**/rest/**put_your_user_id_here**/**put_your_webhook_here**/catalog.priceType.add
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"fields":{"name":"Wholesale price","base":"N","sort":10,"xmlId":"wholesale"},"auth":"**put_access_token_here**"}' \
https://**put_your_bitrix24_address**/rest/catalog.priceType.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 AddPriceTypeResult = {
priceType: {
base: string
createdBy: number
dateCreate: ISODate | null
id: number
modifiedBy: number
name: string
sort: number
timestampX: ISODate | null
xmlId: string
}
}
try {
const response = await $b24.actions.v2.call.make<AddPriceTypeResult>({
method: 'catalog.priceType.add',
params: {
fields: {
name: 'Wholesale price',
base: 'N',
sort: 10,
xmlId: 'wholesale',
},
},
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('Created price type id:', result.priceType.id, 'name:', result.priceType.name)
}
} 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 addPriceType() {
try {
// Initialize the SDK inside a Bitrix24 frame
const $b24 = await B24Js.initializeB24Frame()
const response = await $b24.actions.v2.call.make({
method: 'catalog.priceType.add',
params: {
fields: {
name: 'Wholesale price',
base: 'N',
sort: 10,
xmlId: 'wholesale',
},
},
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('Created price type id:', result.priceType.id, 'name:', result.priceType.name)
} catch (error) {
// Thrown on transport or SDK failures (AjaxError, SdkError, etc.)
console.error(error)
}
}
document.addEventListener('DOMContentLoaded', addPriceType)
</script>
from b24pysdk.errors import BitrixAPIError, BitrixSDKException
try:
bitrix_response = client.catalog.price_type.add(
fields={
"name": "Wholesale price",
"base": "N",
"sort": 10,
"xmlId": "wholesale",
},
).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(
'catalog.priceType.add',
[
'fields' => [
'name' => "Wholesale price",
'base' => "N",
'sort' => 10,
'xmlId' => "wholesale",
],
]
);
$result = $response
->getResponseData()
->getResult();
if ($result->error()) {
error_log($result->error()->ex);
} else {
echo 'Success: ' . print_r($result->data(), true);
}
} catch (Throwable $e) {
error_log($e->getMessage());
echo 'Error adding price type: ' . $e->getMessage();
}
BX24.callMethod(
'catalog.priceType.add',
{
fields: {
name: "Wholesale price",
base: "N",
sort: 10,
xmlId: "wholesale"
}
},
function(result) {
if (result.error())
console.error(result.error().ex);
else
console.log(result.data());
}
);
require_once('crest.php');
$result = CRest::call(
'catalog.priceType.add',
[
'fields' => [
'name' => 'Wholesale price',
'base' => 'N',
'sort' => 10,
'xmlId' => 'wholesale'
]
]
);
echo '<PRE>';
print_r($result);
echo '</PRE>';
// client и ctx уже созданы — см. раздел «SDK для Go»
res, err := client.Core().Call(ctx, "catalog.priceType.add", b24.Params{
"fields": b24.Params{
"name": "Wholesale price",
"base": "N",
"sort": 10,
"xmlId": "wholesale",
},
})
if err != nil {
return fmt.Errorf("catalog.priceType.add: %w", err)
}
// Метод заворачивает ответ в объект с ключом "priceType".
raw, ok := b24.Unwrap(res.Result, "priceType")
if !ok {
return fmt.Errorf("в ответе нет ключа priceType")
}
var item struct {
Base string `json:"base"`
CreatedBy int `json:"createdBy"`
DateCreate string `json:"dateCreate"`
ID b24.ID `json:"id"`
ModifiedBy int `json:"modifiedBy"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &item); err != nil {
return fmt.Errorf("разбор ответа: %w", err)
}
fmt.Println(item.Base, item.CreatedBy)
Ответ
HTTP-статус: 200
{
"result": {
"priceType": {
"base": "N",
"createdBy": 1,
"dateCreate": "2024-10-02T17:49:44+02:00",
"id": 2,
"modifiedBy": 1,
"name": "Wholesale price",
"sort": 10,
"timestampX": "2024-10-02T17:49:44+02:00",
"xmlId": "wholesale"
}
},
"time": {
"start": 1716552521.40908,
"finish": 1716552521.69852,
"duration": 0.289434909820557,
"processing": 0.011207103729248,
"date_start": "2024-10-02T17:49:44+02:00",
"date_finish": "2024-10-02T17:49:44+02:00",
"operating": 0
}
}
Возвращаемые данные
result
object
Корневой элемент ответа
priceType
catalog_price_type
Объект с информацией о созданном типе цены
time
time
Информация о времени выполнения запроса
Обработка ошибок
HTTP-статус: 400
{
"error": 200040300020,
"error_description": "Access Denied"
}
| Код | Описание | Значение |
|---|---|---|
200040300020 |
Недостаточно прав для редактирования | |
100 |
Не передан обязательный параметр fields |
|
0 |
Не установлены обязательные поля | |
0 |
Другие ошибки (например, фатальные ошибки) |

