Быстрый старт
- В админке откройте Growth → Webhooks & API и создайте ключ. Скопируйте секрет ugc_. Он показывается один раз.
- Вызовите API этим ключом.
curl https://api.tescommerce.com/api/v1/products \ -H "Authorization: Bearer ugc_…"
- В ответе ваши товары, по одной странице. nextCursor равен null, когда список кончился.
Авторизация
Ключ создаётся в админке: Growth → Webhooks & API. Он показывается один раз и начинается с ugc_.
Тот же ключ принимается в заголовке X-Api-Key.
Что может ключ
Ключ бывает full, read, products или orders. full стоит по умолчанию и может всё. read — только GET. products читает и меняет каталог, включая остаток. orders читает заказы и отмечает отправку или возврат. Покупатели, скидки и метаполя требуют read или full. Ключ без права отвечает 403.
Тестовый ключ
При создании отметьте тестовый режим. Секрет начинается с ugc_test_. GET по-прежнему отдаёт живой магазин. POST и PATCH отвечают test: true и не сохраняют товар, не меняют остаток, не отмечают отправку и не вызывают Stripe. Это прогон на вашем магазине, а не второй магазин.
Деньги в минорных единицах. 1999 — это 19.99 в валюте магазина. У скидки в процентах поле value хранит процент, а не центы.
curl https://api.tescommerce.com/api/v1/products \ -H "Authorization: Bearer ugc_…" curl https://api.tescommerce.com/api/v1/products \ -H "X-Api-Key: ugc_…"
const res = await fetch("https://api.tescommerce.com/api/v1/products", {
headers: { Authorization: "Bearer ugc_…" }
});
const body = await res.json();Лимиты
120 запросов в минуту с одного IP, затем 300 в минуту для верного ключа. 30 неверных ключей с одного IP блокируются на 15 минут. Ответ 429 содержит Retry-After в секундах.
HTTP/1.1 429 Too Many Requests
Retry-After: 12
{ "error": "Too many requests. Try again later.", "retryAfterSec": 12 }Страницы
У каждого списка есть limit от 1 до 100 (по умолчанию 25) и cursor. Передавайте прошлый nextCursor, пока он не станет null.
updatedSince и createdSince — метка ISO 8601. В список попадут только строки, изменённые или созданные после неё. Неверная метка даёт 400.
Каждая метка времени в JSON — ISO 8601 в UTC, например 2026-11-15T08:00:00.000Z.
Передавайте Idempotency-Key в POST /products, POST /products/:id/inventory, POST /orders/:id/fulfill и POST /orders/:id/refund. Тот же ключ и то же тело повторяют первый ответ 24 часа, в том числе ответ тестового ключа. Тот же ключ с другим телом даёт 409.
curl "https://api.tescommerce.com/api/v1/products?limit=50&updatedSince=2026-11-01T00:00:00.000Z" \ -H "Authorization: Bearer ugc_…"
{
"products": [{
"id": "clproduct",
"title": "Tee",
"slug": "tee",
"status": "ACTIVE",
"type": "PHYSICAL",
"priceAmount": 1999,
"compareAt": null,
"inventory": 12,
"updatedAt": "2026-11-15T08:00:00.000Z"
}],
"currency": "USD",
"nextCursor": null
}Справочник
OpenAPI: https://api.tescommerce.com/api/v1/openapi.json
GET /products
Активные и черновики. status=ARCHIVED показывает архив. Мягко удалённые товары не попадают в список.
{
"products": [{
"id": "clproduct",
"title": "Tee",
"slug": "tee",
"status": "ACTIVE",
"type": "PHYSICAL",
"priceAmount": 1999,
"compareAt": null,
"inventory": 12,
"updatedAt": "2026-11-15T08:00:00.000Z"
}],
"currency": "USD",
"nextCursor": null
}POST /products
priceAmount обязателен. status по умолчанию DRAFT. Без slug он берётся из названия.
curl https://api.tescommerce.com/api/v1/products \
-H "Authorization: Bearer ugc_…" \
-H "Content-Type: application/json" \
-d '{"title":"Tee","priceAmount":1999,"inventory":12}'
{
"product": {
"id": "clproduct",
"title": "Tee",
"slug": "tee",
"description": null,
"status": "DRAFT",
"type": "PHYSICAL",
"priceAmount": 1999,
"compareAt": null,
"inventory": 12,
"sku": null,
"barcode": null,
"tags": [],
"currency": "USD",
"updatedAt": "2026-11-15T08:00:00.000Z"
}
}GET /products/:id
В ответе фото (storageKey, fileName, alt, sortOrder) и варианты (id, title, sku, priceAmount, inventory).
curl https://api.tescommerce.com/api/v1/products/clproduct \ -H "Authorization: Bearer ugc_…"
PATCH /products/:id
Передавайте только меняющиеся поля. priceAmount — минорные единицы, inventory — количество.
curl https://api.tescommerce.com/api/v1/products/clproduct \
-X PATCH \
-H "Authorization: Bearer ugc_…" \
-H "Content-Type: application/json" \
-d '{"status":"ACTIVE","priceAmount":2499}'POST /products/:id/inventory
Либо inventory, либо adjust. Остаток ниже нуля отклоняется. variantId меняет этот вариант.
curl https://api.tescommerce.com/api/v1/products/clproduct/inventory \
-H "Authorization: Bearer ugc_…" \
-H "Content-Type: application/json" \
-d '{"adjust":-1}'
{ "productId": "clproduct", "variantId": null, "inventory": 11 }GET /orders
Необязательный status: DRAFT, PENDING, PAID, FULFILLED, CANCELLED, REFUNDED.
{
"orders": [{
"id": "clorder",
"orderNumber": "1001",
"status": "PAID",
"totalAmount": 1999,
"currency": "USD",
"guestEmail": "buyer@example.com",
"createdAt": "2026-11-15T08:00:00.000Z",
"customer": { "email": "buyer@example.com", "name": "Aya" }
}],
"nextCursor": null
}GET /orders/:id
В строках есть title, quantity, unitAmount и totalAmount.
{
"order": {
"id": "clorder",
"orderNumber": "1001",
"status": "PAID",
"currency": "USD",
"totalAmount": 1999,
"guestEmail": "buyer@example.com",
"items": [{
"id": "clline",
"title": "Tee",
"quantity": 1,
"unitAmount": 1999,
"totalAmount": 1999
}],
"customer": { "id": "clcustomer", "email": "buyer@example.com", "name": "Aya" }
}
}POST /orders/:id/fulfill
Заказ должен быть PAID. Для защиты покупателя trackingNumber нужен до списания.
curl https://api.tescommerce.com/api/v1/orders/clorder/fulfill \
-H "Authorization: Bearer ugc_…" \
-H "Content-Type: application/json" \
-d '{"trackingNumber":"1Z999","notifyCustomer":true}'POST /orders/:id/refund
Только оплаченные и отправленные. Если оплата прошла через Stripe, возврат идёт туда. amountCents по умолчанию — остаток.
curl https://api.tescommerce.com/api/v1/orders/clorder/refund \
-H "Authorization: Bearer ugc_…" \
-H "Content-Type: application/json" \
-d '{"amountCents":500,"reason":"Short ship"}'
{
"order": { "id": "clorder", "status": "PAID" },
"stripeRefund": true,
"partial": true,
"refundAmountCents": 500
}GET /customers
Хеши паролей и токены сброса не отдаются. Слитые покупатели в список не входят.
{
"customers": [{
"id": "clcustomer",
"email": "buyer@example.com",
"name": "Aya",
"country": "KG",
"marketingOptOut": false,
"loyaltyPoints": 0,
"storeCreditCents": 0,
"createdAt": "2026-11-15T08:00:00.000Z"
}],
"nextCursor": null
}GET /discounts
У PERCENT поле value — процент. У FIXED — минорные единицы. Можно active=true или active=false.
{
"discounts": [{
"id": "cldiscount",
"code": "WELCOME10",
"type": "PERCENT",
"value": 10,
"valueKind": "percent",
"active": true,
"usedCount": 3,
"maxUses": 100
}],
"nextCursor": null
}GET /metafields?ownerType=PRODUCT&ownerId=clproduct
ownerType обязателен: PRODUCT, VARIANT, CUSTOMER, ORDER, SHOP или METAOBJECT. ownerId сужает до одной записи.
{
"metafields": [{
"id": "clmeta",
"ownerType": "PRODUCT",
"ownerId": "clproduct",
"namespace": "custom",
"key": "material",
"type": "single_line_text",
"value": "Cotton",
"updatedAt": "2026-11-15T08:00:00.000Z"
}],
"nextCursor": null
}Ошибки
401 { "error": "Missing or invalid API key" }
400 { "error": "priceAmount must be a whole number of minor units (cents)" }
400 { "error": "Invalid cursor" }
400 { "error": "Only a paid order can be marked fulfilled" }
404 { "error": "Not found" }
403 { "error": "This API key cannot do that" }
409 { "error": "Slug already used" }
409 { "error": "Idempotency key was already used with a different request" }
429 { "error": "Too many requests. Try again later.", "retryAfterSec": 12 }Вебхуки
Подписка в Growth → Webhooks & API. Запрос обрывается через 8 секунд. Редиректы не обрабатываются. Неудача повторяется через 1 минуту, 5 минут, 30 минут, 2 часа и 12 часов. Тест из админки добавляет "test": true.
Как ответить
Ответьте 2xx, чтобы принять доставку. Любой другой код, обрыв по времени или редирект — ошибка, и доставка повторится.
В подписи нет времени отправки, поэтому свежесть по подписи не проверить. Повторная попытка присылает то же событие и увеличивает attempt. Сохраните id доставки (поле id и заголовок X-UGCLab-Delivery) и пропускайте дубль.
{
"id": "cldelivery",
"event": "order.paid",
"createdAt": "2026-11-15T08:00:00.000Z",
"attempt": 1,
"data": {
"orderId": "clorder",
"orderNumber": "1001",
"totalAmount": 1999,
"currency": "USD"
}
}X-UGCLab-Event, X-UGCLab-Delivery, X-UGCLab-Signature: sha256=…
Данные событий
- order.createdorderId, orderNumber, totalAmount, currency
- order.paidorderId, orderNumber, totalAmount, currency
- order.fulfilledorderId, orderNumber
- product.createdproductId, title, slug
- product.updatedproductId, title, slug. inventory when stock changes through this API
- customer.createdcustomerId, email
- subscription.updatedsubscriptionId, status
- order.refundedorderId, orderNumber, refundAmountCents, currency, partial
- order.cancelledorderId, orderNumber
- order.tracking_updatedorderId, orderNumber, trackingNumber, status, checkpoint, location, occurredAt, provider
Проверка подписи
Сравните заголовок с HMAC-SHA256 сырого тела и секрета адреса. JSON разбирайте после проверки. Повторная сериализация тела меняет подпись.
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyWebhook(rawBody, header, secret) {
const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(header ?? "");
return a.length === b.length && timingSafeEqual(a, b);
}import hashlib, hmac
def verify_webhook(raw: bytes, header: str, secret: str) -> bool:
expected = "sha256=" + hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header or "")function verify_webhook(string $raw, string $header, string $secret): bool {
$expected = "sha256=" . hash_hmac("sha256", $raw, $secret);
return hash_equals($expected, $header);
}Версия
Публичный контракт — v1. Эта версия читает и обновляет товары, ставит остаток, читает заказы, отмечает отправку, делает возврат и читает покупателей, скидки и метаполя. Списки идут страницами по курсору. Вебхуков девять.
Журнал
v1 — 2026-11. Первый публичный контракт: чтение и запись каталога и заказов, страницы по курсору, покупатели, скидки, метаполя и события вебхуков на этой странице.
Удаление поля, смена его типа или смена проверки ключа — ломающее изменение, для него нужна новая версия. Новое поле или событие ломающим не считается.
Клиент
Официальной библиотеки нет. Вызывайте HTTPS сами или сгенерируйте клиент из документа OpenAPI.
Статус и поддержка
Статус платформы — на странице статуса. Вопрос по магазину — письмом с аккаунта или через страницу контакта. /status · Контакт