Управление брендами и сертификацией
API для работы с брендами и требованиями к сертификации — получение информации о том, какие бренды требуют сертификаты для продажи на OZON.
getCertificationList
Список брендов, требующих сертификацию
Метод | Endpoint | Назначение |
---|---|---|
getCertificationList |
/v1/brand/company-certification/list |
Список брендов, требующих сертификацию |
import { OzonSellerAPI } from 'daytona-ozon-seller-api';
const client = new OzonSellerAPI({
clientId: 'your-client-id',
apiKey: 'your-api-key'
});
try {
// Получить первую страницу брендов
const brands = await client.brand.getCertificationList({
page: 1,
page_size: 100
});
console.log(`📊 Всего брендов: ${brands.result?.total}`);
// Фильтрация брендов, требующих сертификацию
const brandsRequiringCerts = brands.result?.brand_certification.filter(
brand => brand.has_certificate
) || [];
const brandsNotRequiringCerts = brands.result?.brand_certification.filter(
brand => !brand.has_certificate
) || [];
console.log(`🔐 Брендов, требующих сертификацию: ${brandsRequiringCerts.length}`);
console.log(`✅ Брендов без требований: ${brandsNotRequiringCerts.length}`);
// Вывести бренды, требующие сертификаты
console.log('\n🔐 Бренды, требующие сертификацию:');
brandsRequiringCerts.slice(0, 10).forEach((brand, index) => {
console.log(`${index + 1}. ${brand.brand_name}`);
});
} catch (error) {
console.error('❌ Ошибка получения списка брендов:', error);
}
getCertificationList()
- Список сертифицируемых брендовinterface BrandCertificationListRequest {
/** Номер страницы (>=1) */
page: number;
/** Количество элементов на странице (>=1) */
page_size: number;
}
interface BrandCertificationInfo {
/** Название бренда */
brand_name: string;
/**
* Требуется ли сертификат:
* - true — требуется сертификат
* - false — сертификат не нужен
*/
has_certificate: boolean;
}
interface BrandCertificationListResponse {
result?: {
/** Информация о брендах */
brand_certification: BrandCertificationInfo[];
/** Общее количество брендов */
total: number;
};
}
const getAllBrands = async () => {
const allBrands: BrandCertificationInfo[] = [];
let page = 1;
const pageSize = 100;
let hasMorePages = true;
while (hasMorePages) {
try {
console.log(`📥 Загружается страница ${page}...`);
const response = await client.brand.getCertificationList({
page,
page_size: pageSize
});
if (response.result?.brand_certification) {
allBrands.push(...response.result.brand_certification);
}
const total = response.result?.total || 0;
const loadedCount = page * pageSize;
hasMorePages = loadedCount < total;
page++;
// Пауза между запросами
if (hasMorePages) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
} catch (error) {
console.error(`❌ Ошибка загрузки страницы ${page}:`, error);
break;
}
}
console.log(`✅ Всего загружено брендов: ${allBrands.length}`);
return allBrands;
};
const analyzeCertificationRequirements = async () => {
try {
const allBrands = await getAllBrands();
const analysis = {
total: allBrands.length,
requiresCertification: 0,
noCertificationRequired: 0,
brandsByRequirement: {
required: [] as string[],
notRequired: [] as string[]
}
};
allBrands.forEach(brand => {
if (brand.has_certificate) {
analysis.requiresCertification++;
analysis.brandsByRequirement.required.push(brand.brand_name);
} else {
analysis.noCertificationRequired++;
analysis.brandsByRequirement.notRequired.push(brand.brand_name);
}
});
// Сортировка по алфавиту
analysis.brandsByRequirement.required.sort((a, b) => a.localeCompare(b, 'ru'));
analysis.brandsByRequirement.notRequired.sort((a, b) => a.localeCompare(b, 'ru'));
return analysis;
} catch (error) {
console.error('❌ Ошибка анализа сертификации:', error);
}
};
const checkBrandCertification = async (brandNameToCheck: string) => {
try {
let found = false;
let page = 1;
const pageSize = 100;
while (!found) {
const response = await client.brand.getCertificationList({
page,
page_size: pageSize
});
if (!response.result?.brand_certification) {
break;
}
// Поиск бренда (нечувствительный к регистру)
const brandInfo = response.result.brand_certification.find(
brand => brand.brand_name.toLowerCase().includes(brandNameToCheck.toLowerCase())
);
if (brandInfo) {
console.log(`🔍 Найден бренд: "${brandInfo.brand_name}"`);
if (brandInfo.has_certificate) {
console.log('🔐 Статус: Требуется сертификат');
} else {
console.log('✅ Статус: Сертификат не требуется');
}
return {
found: true,
brand: brandInfo,
requiresCertification: brandInfo.has_certificate
};
}
// Проверка на последнюю страницу
const total = response.result.total || 0;
if (page * pageSize >= total) {
break;
}
page++;
}
return { found: false, brand: null, requiresCertification: false };
} catch (error) {
console.error('❌ Ошибка поиска бренда:', error);
return { found: false, brand: null, requiresCertification: false, error: error.message };
}
};
// Использование
const checkResult = await checkBrandCertification('Apple');
Статус: Найден
Полное название: Apple Inc.
Сертификация: 🔐 Требуется сертификат
Действие: Необходимо предоставить сертификат для продажи товаров этого бренда
const monitorBrandChanges = async (intervalMinutes = 60) => {
let previousBrands: BrandCertificationInfo[] = [];
const checkForChanges = async () => {
try {
console.log(`🔄 Проверка изменений в требованиях к брендам...`);
const currentBrands = await getAllBrands();
if (previousBrands.length === 0) {
previousBrands = currentBrands;
console.log(`✅ Базовый снимок создан: ${currentBrands.length} брендов`);
return;
}
// Поиск изменений
const changes = {
newRequirements: [] as string[],
removedRequirements: [] as string[],
newBrands: [] as string[],
removedBrands: [] as string[]
};
// Сравнение требований
currentBrands.forEach(currentBrand => {
const previousBrand = previousBrands.find(p => p.brand_name === currentBrand.brand_name);
if (!previousBrand) {
changes.newBrands.push(currentBrand.brand_name);
} else if (currentBrand.has_certificate !== previousBrand.has_certificate) {
if (currentBrand.has_certificate) {
changes.newRequirements.push(currentBrand.brand_name);
} else {
changes.removedRequirements.push(currentBrand.brand_name);
}
}
});
return changes;
} catch (error) {
console.error('❌ Ошибка мониторинга изменений:', error);
}
};
// Первоначальная проверка
await checkForChanges();
// Запуск периодической проверки
const intervalId = setInterval(checkForChanges, intervalMinutes * 60 * 1000);
console.log(`⏰ Мониторинг запущен с интервалом ${intervalMinutes} минут`);
// Возврат функции для остановки мониторинга
return () => {
clearInterval(intervalId);
console.log('⏹️ Мониторинг остановлен');
};
};
page
и page_size
должны быть >= 1total
для определения общего количества страницBrand API поможет избежать проблем с продажей товаров брендов, требующих сертификацию. Регулярно проверяйте список и подготавливайте необходимые документы заранее для бесперебойной работы вашего магазина.