Інтеграція 1С-Бітрікс зі службою доставки Європошта (Білорусь)
Європошта — білоруська кур'єрська служба, що працює через мережу пунктів видачі. Добре покриває великі та середні міста Білорусі, є популярною альтернативою Білпошті для e-commerce з акцентом на швидкість доставки до ПВЗ. API надає JSON-інтерфейс з авторизацією через пару ключів.
Підключення до API Європошти
Документація та ключі доступу надаються після укладання договору. Базовий URL: https://api.evropochta.by/api/. Авторизація: токен у заголовку token (не Authorization: Bearer, а саме кастомний заголовок token).
private function apiCall(string $method, string $endpoint, array $data = []): array
{
$url = 'https://api.evropochta.by/api/' . ltrim($endpoint, '/');
$ch = curl_init($method === 'GET' ? $url . '?' . http_build_query($data) : $url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'token: ' . $this->getOption('API_TOKEN'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
]);
$result = json_decode(curl_exec($ch), true);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code !== 200 || ($result['error'] ?? false)) {
throw new \RuntimeException($result['error']['message'] ?? 'Помилка API Європошти');
}
return $result['data'] ?? $result;
}
Отримання списку ПВЗ
public function getPickupPoints(?string $cityId = null): array
{
$params = $cityId ? ['cityId' => $cityId] : [];
$cacheKey = 'evropochta_pvz_' . ($cityId ?? 'all');
$cached = \Bitrix\Main\Data\Cache::createInstance();
if ($cached->startDataCache(3600 * 12, $cacheKey, '/evropochta')) {
$points = $this->apiCall('GET', '/pickup-points', $params);
$cached->endDataCache(['points' => $points]);
}
return $cached->getVars()['points'];
}
Список ПВЗ кешується на 12 годин — не змінюється щогодини. На сайті відображається на карті (Яндекс Карти або OpenStreetMap) або у вигляді випадаючого списку з фільтром за містом.
Розрахунок вартості
public function calcPrice(
string $pvzCode,
int $weightGram,
float $declaredValue
): float {
$response = $this->apiCall('POST', '/tariff', [
'pvzCode' => $pvzCode,
'weight' => $weightGram,
'declaredValue' => $declaredValue,
]);
return (float)($response['price'] ?? 0);
}
Вартість у білоруських рублях. При інтеграції з 1С-Бітрікс перевіряйте валюту сайту — якщо магазин працює в кількох валютах, потрібна конвертація через курс НБ РБ.
Створення заявки на доставку
public function createOrder(\Bitrix\Sale\Shipment $shipment): string
{
$order = $shipment->getOrder();
$props = $order->getPropertyCollection();
$payload = [
'externalId' => (string)$order->getId(),
'pvzCode' => $props->getItemByOrderPropertyCode('EVROPOCHTA_PVZ')?->getValue(),
'recipientName' => $props->getItemByOrderPropertyCode('FIO')?->getValue(),
'recipientPhone' => $props->getItemByOrderPropertyCode('PHONE')?->getValue(),
'recipientEmail' => $props->getItemByOrderPropertyCode('EMAIL')?->getValue(),
'weight' => $this->getWeight($shipment),
'declaredValue' => $order->getPrice(),
'codAmount' => 0, // накладений платіж
'items' => $this->buildItems($order),
];
$response = $this->apiCall('POST', '/orders', $payload);
$trackNumber = $response['trackNumber'] ?? '';
$props->getItemByOrderPropertyCode('EVROPOCHTA_TRACK')?->setValue($trackNumber);
$order->save();
return $trackNumber;
}
Трекінг
public function getStatus(string $trackNumber): array
{
$response = $this->apiCall('GET', '/tracking/' . $trackNumber);
return [
'status' => $response['statusName'] ?? '',
'date' => $response['updatedAt'] ?? '',
'pvzName' => $response['pvzName'] ?? '',
];
}
Polling агентом раз на 2–3 години для активних відправлень. Вебхуки не передбачені.
Маппінг статусів
| Статус Європошти | Статус замовлення 1С-Бітрікс |
|---|---|
| created | Створено |
| in_transit | В дорозі |
| arrived | Прибуло до ПВЗ |
| delivered | Видано отримувачу |
| returned | Повернення |
| cancelled | Скасовано |
Терміни
| Склад | Термін |
|---|---|
| Список ПВЗ + карта + розрахунок | 3–4 дні |
| + Створення замовлень + трекінг | +2 дні |







