'https://exno.app/api/v1/', 'staging' => 'https://staging.exno.app/api/v1/']; private const METHODS = ['GET', 'POST', 'PATCH', 'DELETE']; private string $key; private string $base; private int $timeout; /** * @param array{environment?: string, base_url?: string, timeout?: int} $options environment: "production" (default) * or "staging"; base_url: only http://127.0.0.1: or http://localhost:, for local development. */ public function __construct(string $apiKey, array $options = []) { if (trim($apiKey) === '') { throw new \InvalidArgumentException('An API key is required'); } $environment = $options['environment'] ?? 'production'; if (!isset(self::HOSTS[$environment])) { throw new \InvalidArgumentException('Unknown EXNO environment'); } $base = self::HOSTS[$environment]; if (isset($options['base_url'])) { if (!preg_match('#^http://(127\.0\.0\.1|localhost):\d{2,5}/?$#', (string) $options['base_url'])) { throw new \InvalidArgumentException('base_url is only for local development (http://127.0.0.1:)'); } $base = rtrim((string) $options['base_url'], '/') . '/api/v1/'; } $this->key = $apiKey; $this->base = $base; $this->timeout = (int) ($options['timeout'] ?? 30); } /** * One API call. $resource is relative to /api/v1, for example "products" or "sales/ORDER_ID". * @param array{query?: array, body?: mixed, idempotency_key?: string} $options * @return array|null the complete API response */ public function request(string $method, string $resource, array $options = []): ?array { if (!in_array($method, self::METHODS, true)) { throw new \InvalidArgumentException('Unsupported HTTP method'); } if (!preg_match('#^[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*$#', $resource)) { throw new \InvalidArgumentException('Use an API resource such as products or sales/ID'); } $hasBody = array_key_exists('body', $options); if ($method === 'GET' && $hasBody) { throw new \InvalidArgumentException('GET does not take a body'); } $query = array_filter($options['query'] ?? [], static fn ($v) => $v !== null); $query = array_map(static fn ($v) => is_bool($v) ? ($v ? 'true' : 'false') : (string) $v, $query); $url = $this->base . $resource . ($query ? '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986) : ''); $headers = ['Authorization: Bearer ' . $this->key, 'Accept: application/json']; $payload = null; if ($hasBody) { $headers[] = 'Content-Type: application/json'; $payload = json_encode($options['body'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } if ($method !== 'GET') { $headers[] = 'Idempotency-Key: ' . ($options['idempotency_key'] ?? self::uuid()); } $responseHeaders = []; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS | CURLPROTO_HTTP, CURLOPT_HEADERFUNCTION => static function ($ch, string $line) use (&$responseHeaders): int { $parts = explode(':', $line, 2); if (count($parts) === 2) { $responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]); } return strlen($line); }, ]); if ($payload !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } elseif ($method !== 'GET') { // no body: an empty one (Content-Length: 0), without curl's default form content type curl_setopt($ch, CURLOPT_POSTFIELDS, ''); curl_setopt($ch, CURLOPT_HTTPHEADER, [...$headers, 'Content-Type:']); } $raw = curl_exec($ch); if ($raw === false) { $error = curl_error($ch); curl_close($ch); throw new \RuntimeException('Could not reach EXNO: ' . $error); } $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); $data = null; if ($raw !== '') { try { $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING); } catch (\JsonException $e) { if ($status >= 200 && $status < 300) { throw new \RuntimeException('Invalid JSON from EXNO'); } } } if ($status < 200 || $status >= 300) { $detail = is_array($data) && is_array($data['error'] ?? null) ? $data['error'] : []; throw new ExnoError($status, (string) ($detail['message'] ?? "EXNO returned HTTP $status"), $detail['code'] ?? null, $detail['param'] ?? null, $responseHeaders['x-request-id'] ?? ($detail['request_id'] ?? null), $responseHeaders['retry-after'] ?? null); } return $data; } /** @return array */ public function me(): array { return $this->request('GET', 'me'); } /** @param array $query @return array */ public function products(array $query = []): array { return $this->request('GET', 'products', ['query' => $query]); } /** @param array $query @return array */ public function sales(array $query = []): array { return $this->request('GET', 'sales', ['query' => $query]); } /** * Every page of a list, following next_cursor. * @param array $query * @return \Generator> */ public function pages(string $resource, array $query = []): \Generator { $seen = isset($query['cursor']) ? [(string) $query['cursor'] => true] : []; while (true) { $page = $this->request('GET', $resource, ['query' => $query]); yield $page; if (empty($page['has_more'])) { return; } $next = $page['next_cursor'] ?? null; if (!is_string($next) || $next === '' || isset($seen[$next])) { throw new \RuntimeException('Invalid EXNO pagination cursor'); } $query['cursor'] = $next; $seen[$next] = true; } } /** * Checks a webhook request from EXNO and returns the event. $payload is the raw request body (file_get_contents('php://input')), * $signature the Exno-Signature header, $secret the endpoint's or app's signing secret (whsec_…). Refuses requests * older than $tolerance seconds (0 = don't check the time). * @return array */ public static function verifyWebhook(string $payload, string $signature, string $secret, int $tolerance = 300): array { $t = null; $v1 = []; foreach (explode(',', $signature) as $part) { $kv = explode('=', trim($part), 2); if (count($kv) !== 2) { continue; } if ($kv[0] === 't') { $t = $kv[1]; } elseif ($kv[0] === 'v1') { $v1[] = $kv[1]; } } if ($t === null || !ctype_digit($t) || !$v1) { throw new WebhookSignatureError('The Exno-Signature header is missing or malformed'); } if ($tolerance > 0 && abs(time() - (int) $t) > $tolerance) { throw new WebhookSignatureError('The signature is too old'); } $expected = hash_hmac('sha256', $t . '.' . $payload, $secret); foreach ($v1 as $candidate) { if (hash_equals($expected, $candidate)) { return json_decode($payload, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING); } } throw new WebhookSignatureError('The signature does not match'); } private static function uuid(): string { $b = random_bytes(16); $b[6] = chr((ord($b[6]) & 0x0f) | 0x40); $b[8] = chr((ord($b[8]) & 0x3f) | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4)); } }