Работа с сущностью "Товар"

Изменено Чт, 5 Сен, 2024 на 3:13 PM


СОДЕРЖАНИЕ


Получить информацию о товаре


Route: https://cdek.orderadmin.ru/api/products/offer/<shop_id>/<product_id>Method: GETHeaders: Accept: application/jsonAuthorization: basic
Generic



Описание параметров:

ПараметрОписание
shop_idid корневого магазина
offer_idid товара



Пример запроса (PHP):

<?php

$url = 'https://cdek.orderadmin.ru/api/products/offer/185486/5376916';
$headers = [
    'Accept: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($data);
PHP



Пример запроса (curl):

curl -X GET \
-u "<user>:<password>" \
-H "Accept: application/json" \
"https://cdek.orderadmin.ru/api/products/offer/185486/5376916"
Generic



Пример запроса (Python):

import requests

api_url = 'https://cdek.orderadmin.ru/api/products/offer/185486/5376916'
result = requests.get(api_url, auth=(
    '<user>', 
    '<password>'
))
print(result.json())
Python



Пример ответа сервера: 

{
    "id": "5376916",
    "extId": "1128337624",
    "type": "simple",
    "state": "normal",
    "name": "Товар 1",
    "article": "45334245545",
    "sku": "45334245545",
    "barcodes": [],
    "image": null,
    "weight": 200,
    "dimensions": {
        "x": "220",
        "y": "86",
        "z": "51"
    },
    "price": 200,
    "purchasingPrice": null,
    "items":  {
        "count": 15,
        "state": "normal",
        "warehouse": 7542
    }
}
JavaScript



Описание полей ответа:


ПолеОписание
idУникальный идентификатор
nameНазвание
extIdУникальная строка для нужд разработчиков интеграций
typeТип товара. Используйте - simple
stateсостояние товара:
normal - обычный товар
inactive -виден в ЛК, недоступен для заказа
articleАртикул
skuЕдиница складского учета
barcodesМассив штрихкодов
imageСсылка на изображение в сети интернет
weightВес товара, граммы
dimensions.xГабариты, ширина, мм
dimensions.yГабариты, длина, мм
dimensions.zГабариты, глубина, мм
priceЦена товара
purchasingPriceЗакупочная цена
itemsИнформация о наличии товара на складах пользователя





Получить список товаров


Route: https://cdek.orderadmin.ru/api/products/offer
Method: GET
Headers: Accept: application/json
Authorization: basic
Generic



Пример запроса (PHP):

<?php

$url = 'https://cdek.orderadmin.ru/api/products/offer';
$headers = [
    'Accept: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($data);
PHP



Пример запроса (curl):

curl -X GET \
-u "<user>:<password>" \
-H "Accept: application/json" \
"https://cdek.orderadmin.ru/api/products/offer"
Generic



Пример запроса (Python):

import requests

api_url = 'https://cdek.orderadmin.ru/api/products/offer'
result = requests.get(api_url, auth=(
    '<user>', 
    '<password>'
))
print(result.json())
Python



Пример ответа сервера:

{
    "_links": {
        "self": {
            "href": "https://cdek.orderadmin.ru/api/products/offer?page=1"
        },
        "first": {
            "href": "https://cdek.orderadmin.ru/api/products/offer"
        },
        "last": {
            "href": "https://cdek.orderadmin.ru/api/products/offer?page=23"
        },
        "next": {
            "href": "https://cdek.orderadmin.ru/api/products/offer?page=2"
        }
    },
    "_embedded": {
        "product_offer": [
            /* Массив объектов offer */
        ]
    },
    "page_count": 23,
    "page_size": 25,
    "total_items": 562,
    "page": 1
}
JavaScript





Добавить товар


Route: https://cdek.orderadmin.ru/api/products/offer  
Method: POST
Headers: Accept: application/json
Authorization: basic
Generic



Пример json для создания товара:

{
   "state": "normal",
   "type": "simple",
   "shop": 189387,
   "name": "TEST298",
   "article": "0016523429",
   "extId":"2-391244876",
   "barcodes": [
       "S/I/PO3697403*",
       "583161110265"
   ],
   "sku": "2554165235235",
   "image": null,
   "price": 100,
   "purchasingPrice": 100,
   "weight": 200,
   "dimensions": {
       "x": 0,
       "y": 0,
       "z": 0
   }
}
JavaScript



В примерах предполагается, что данные json находятся в файле new_product.json


Пример запроса (PHP):

<?php

$url = 'https://cdek.orderadmin.ru/api/products/offer';
$headers = [
    'Content-Type: application/json'
];
$data = file_get_contents('new_product.json');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($data);
PHP



Пример запроса (curl):

curl -X POST \
"https://cdek.orderadmin.ru/api/products/offer" \
-u "<user>:<password>" \
-H "Content-Type: application/json" \
-d @new_product.json
Generic



Пример запроса (Python):

import requests
import json

with open('new_product.json ', 'rt') as ft:
    data = json.load(ft)

api_url = 'https://cdek.orderadmin.ru/api/products/offer'
result = requests.post(api_url,
    auth=(
        '<user>', 
        '<password>'
    ),
    json=data
)
print(result.json())
Python



Добавить набор

Создание набора отличается от создания обычного товара (см. предыдущий раздел) дополнительным полем в json запроса - блоком eav, в котором перечислены товары, а также значением поля type.


Пример json:

{
  "state": "normal",
  "type": "bundle",
  "shop": 101354,
  "name": "Новый набор 1",
  "article": "5453553458",
  "price": 100,
  "purchasingPrice": 100,
  "weight": 200,
  "dimensions": {
    "x": 0,
    "y": 0,
    "z": 0
  },
  "eav": {
    "products-offer-bundle": [
      {
        "productOffer": 31131447,
        "count": 2,
        "shop": 101354
      },
      {
        "productOffer": 5864389,
        "count": 1,
        "shop": 101354
      }
    ]
  }
}
JavaScript

Здесь в массиве products-offer-bundle находятся товары, которые должны входить в этот набор. Его поля:

  • productOffer - id ранее созданной карточки товара;
  • shop - магазин, должен быть равен магазину, указанному в поле shop выше;
  • count - количество единиц товара в наборе.




Изменить товар


Route: https://cdek.orderadmin.ru/api/products/offer/<shop_id>/<product_id>
Method: PATCH
Headers: Accept: application/json
Authorization: basic
Generic



Пример json для изменения товара: 

{
    "name": "Измененный товар 1"
}
JavaScript



В примере предполагается, что данные json находятся в файле edit_product.json


Пример запроса (PHP):

<?php

$url = 'https://cdek.orderadmin.ru/api/products/offer/185486/5855514';
$headers = [
    'Content-Type: application/json'
];
$data = file_get_contents('edit_product.json');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($data);
PHP



Пример запроса (curl):

curl -X PATCH \
"https://cdek.orderadmin.ru/api/products/offer/185486/5855514" \
-u "<user>:<password>" \
-H "Content-Type: application/json" \
-d @edit_product.json
Generic



Пример запроса (Python):

import requests
import json

with open('edit_product.json', 'rt') as ft:
    data = json.load(ft)

api_url = 'https://cdek.orderadmin.ru/api/products/offer/185486/5855514'
result = requests.patch(api_url,
    auth=(
        '<user>', 
        '<password>'
    ),
    json=data
)
print(result.json())
Python





Поиск по товарам


Поиск товара по артикулу:

https://cdek.orderadmin.ru/api/products/offer?filter[0][type]=eq&filter[0][field]=article&filter[0][value]=<артикул>
Method: GET
Headers: Accept: application/json
Authorization: basic
Generic



Поиск товара по extId 

https://cdek.orderadmin.ru/api/products/offer?filter[0][type]=eq&filter[0][field]=extId&filter[0][value]=<extId>
Method: GET
Headers: Accept: application/json
Authorization: basic
Generic



Поиск по части названия товара:

https://cdek.orderadmin.ru/api/products/offer?filter[0][type]=like&filter[0][field]=name&filter[0][value]=%товар%
Method: GET
Headers: Accept: application/json
Authorization: basic
Generic


Поиск товара по штрихкоду:

https://cdek.orderadmin.ru/api/products/offer?filter[0][type]=like&filter[0][field]=barcodes::text&filter[0][value]=%20000001234%
Method: GET
Headers: Accept: application/json
Authorization: basic
Generic


Статья помогла?

Отлично!

Спасибо за ваш отзыв

Извините, что не удалось помочь!

Спасибо за ваш отзыв

Расскажите, как мы можем улучшить эту статью!

Выберите хотя бы одну причину
Требуется проверка CAPTCHA.

Комментарий отправлен

Мы ценим вашу помощь и постараемся исправить статью