base = rtrim($base, '/'); $this->key = $key; $this->secret = $secret; } /** * One request. The signature covers METHOD, PATH (without /v1), TIMESTAMP and the raw body. * * @return array the decoded envelope */ public function request(string $method, string $path, ?array $body = null, bool $bearer = false): array { $method = strtoupper($method); $raw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_SLASHES); $headers = ['Accept: application/json']; if ($raw !== '') { $headers[] = 'Content-Type: application/json'; } if ($bearer && $this->token !== '') { $headers[] = 'Authorization: Bearer '.$this->token; } else { $ts = (string) time(); $signature = hash_hmac('sha256', $method."\n".'/'.ltrim(parse_url($path, PHP_URL_PATH), '/')."\n".$ts."\n".$raw, $this->secret); $headers[] = 'X-Api-Key: '.$this->key; $headers[] = 'X-Timestamp: '.$ts; $headers[] = 'X-Signature: '.$signature; } $ch = curl_init($this->base.$path); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $raw === '' ? null : $raw, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); $answer = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); $data = json_decode((string) $answer, true); if (!is_array($data)) { throw new RuntimeException('HTTP '.$status.': not a JSON envelope'); } return $data; } /** Exchange the signature for a Bearer token and keep it for later calls. */ public function auth(int $ttl = 3600): array { $answer = $this->request('POST', '/auth', ['ttl' => $ttl]); if (!empty($answer['ok'])) { $this->token = (string) $answer['data']['access_token']; } return $answer; } } if (PHP_SAPI === 'cli' && realpath($argv[0] ?? '') === __FILE__) { $cytron = new CytronApi($argv[1] ?? 'https://api.cytrongift.com/v1', (string) getenv('CYTRON_API_KEY'), (string) getenv('CYTRON_API_SECRET')); $steps = [ 'health' => $cytron->request('GET', '/health'), 'config' => $cytron->request('GET', '/config'), 'stats' => $cytron->request('GET', '/stats'), 'offers' => $cytron->request('GET', '/catalog/offers?limit=5'), 'balance' => $cytron->request('GET', '/account/balance'), 'auth' => $cytron->auth(), 'balance_jwt' => $cytron->request('GET', '/account/balance', null, true), ]; foreach ($steps as $name => $answer) { printf("%-12s %s\n", $name, !empty($answer['ok']) ? 'ok' : 'error '.($answer['error']['id'] ?? '?').' '.($answer['error']['desc'] ?? '')); if (empty($answer['ok'])) { exit(1); } } }