Інтеграція служби доставки Boxberry на сайт
Boxberry — мережа доставки з упором на пункти видачі: більше 15 000 точок по Росії. API досить прямолінійне: токен у заголовку або параметрі, JSON у відповіді, без OAuth. Це спрощує інтеграцію, але вимагає уваги до обробки помилок — Boxberry іноді повертає помилки в тілі 200-відповіді замість HTTP-статусів.
Базова структура клієнта
class BoxberryClient
{
private string $baseUrl = 'https://api.boxberry.ru/json.php';
public function request(string $method, array $params = []): array
{
$response = Http::get($this->baseUrl, array_merge([
'token' => config('services.boxberry.token'),
'method' => $method,
], $params));
$data = $response->json();
if (isset($data['err'])) {
throw new BoxberryApiException("Boxberry API error [{$method}]: {$data['err']}");
}
return $data;
}
}
Розрахунок вартості доставки
Метод DeliveryCosts рахує вартість за кодом міста або індексом ПВЗ:
public function calculateDelivery(
string $targetCity,
float $weightKg,
array $dimensions,
float $declaredValue = 0,
bool $toPickupPoint = true
): array {
$method = $toPickupPoint ? 'DeliveryCosts' : 'DeliveryCostsD2D';
$response = Http::get($this->baseUrl, [
'token' => config('services.boxberry.token'),
'method' => $method,
'weight' => (int)($weightKg * 1000),
'target' => $targetCity,
'OrderSum' => (int)$declaredValue,
'height' => $dimensions['height'],
'width' => $dimensions['width'],
'depth' => $dimensions['length'],
])->json();
if (isset($response['err'])) {
throw new BoxberryApiException($response['err']);
}
return [
'price' => (float)$response['price'],
'min_days' => (int)$response['delivery_period'],
];
}
Boxberry розділяє доставку до ПВЗ і кур'єрську до двері. Другий метод доступний не скрізь.
Міста й пункти видачі
public function getCitiesWithPoints(): array
{
return Cache::remember('boxberry_cities', now()->addDay(), function () {
return $this->request('ListCitiesShort');
});
}
public function getPickupPoints(?string $cityCode = null): array
{
$points = $this->request('ListPoints', ['CityCode' => $cityCode]);
return collect($points)->map(fn($p) => [
'code' => $p['Code'],
'name' => $p['Name'],
'address' => $p['Address'],
'lat' => (float)$p['GPS']['Latitude'],
'lng' => (float)$p['GPS']['Longitude'],
'work_time' => $p['WorkShedule'],
'cash_allowed' => (bool)($p['HaveCash'] ?? false),
])->toArray();
}
Створення посилки
public function createParcel(Order $order): string
{
$payload = [
'order_id' => (string)$order->id,
'targetstart' => $order->pickup_point_code,
'price' => $order->delivery_cost,
'payment_sum' => $order->is_prepaid ? 0 : $order->total,
'delivery_sum' => $order->delivery_cost,
'vid' => 1, // 1=ПВЗ, 2=кур'єр
'kurdost' => ['idx' => $order->zip, 'citi' => $order->city],
'customer' => [
'fio' => $order->recipient_name,
'phone' => $order->recipient_phone,
'email' => $order->recipient_email,
],
'weights' => [
'weight' => (int)($order->total_weight_kg * 1000),
],
];
$response = Http::post('https://api.boxberry.ru/json.php?token=' . config('services.boxberry.token') . '&method=ParselCreate',
$payload
)->json();
if (isset($response['err'])) {
throw new BoxberryApiException($response['err']);
}
return $response['track'];
}
Відстеження
public function trackParcel(string $trackNumber): array
{
$response = $this->request('ListStatuses', ['ImId' => $trackNumber]);
return collect($response)->map(fn($s) => [
'date' => $s['Date'],
'name' => $s['Name'],
])->toArray();
}
Обмеження
Boxberry працює тільки з російськими адресами. Максимальна вага 31 кг, максимальна сторона 150 см. Наложенний платіж доступний не скрізь.
Для тестування використовується тестовий токен (видається менеджером).
Терміни
Розрахунок вартості + список ПВЗ + створення замовлень — 4–6 робочих днів.







