Files
2026-09-15 10:35:56 +08:00

77 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\SeventeenTrack\Model\Api;
use Esun\SeventeenTrack\Model\Config;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
class Client
{
private ?int $lastStatus = null;
private ?string $lastBody = null;
public function __construct(
private readonly Config $config,
private readonly Curl $curl,
private readonly Json $json
) {
}
public function register(array $shipments): array
{
return $this->post('register', $shipments);
}
public function getTrackInfo(array $shipments): array
{
return $this->post('gettrackinfo', $shipments);
}
public function getLastStatus(): ?int
{
return $this->lastStatus;
}
public function getLastBody(): ?string
{
return $this->lastBody;
}
private function post(string $endpoint, array $payload): array
{
$this->lastStatus = null;
$this->lastBody = null;
$key = $this->config->getApiKey();
if (!$this->config->isEnabled() || $key === '') {
throw new \RuntimeException('17TRACK is disabled or the API key is missing.');
}
$this->curl->setTimeout(30);
$this->curl->setHeaders(['Content-Type' => 'application/json', '17token' => $key]);
$this->curl->post($this->config->getApiUrl() . '/' . $endpoint, $this->json->serialize($payload));
$status = $this->curl->getStatus();
$body = $this->curl->getBody();
$this->lastStatus = $status;
$this->lastBody = $body;
if ($status !== 200) {
throw new \RuntimeException(sprintf('17TRACK returned HTTP %d.', $status));
}
try {
$response = $this->json->unserialize($body);
} catch (\InvalidArgumentException $exception) {
throw new \RuntimeException('17TRACK returned invalid JSON.', 0, $exception);
}
if (!is_array($response) || (int)($response['code'] ?? -1) !== 0) {
$code = is_array($response) && isset($response['code']) ? (int)$response['code'] : 0;
throw new \RuntimeException(
(string)($response['message'] ?? '17TRACK request failed.'),
$code
);
}
return $response;
}
}