<?php
// PHP 8.1+；需要 cURL 扩展，不依赖第三方包。
function required_env(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException('请设置环境变量 ' . $name);
    }
    return $value;
}

$baseURL = rtrim(required_env('OPEN_API_BASE_URL'), '/');
$apiKey = required_env('OPEN_API_KEY');
$secret = required_env('OPEN_API_SECRET');
$path = '/api/v1/open/watch-data/viewers/query';
$rawBody = '{"ticketCode":"demo-live","playbackMode":"REPLAY","uids":[10000],"minWatchSeconds":0,"sort":"WATCH_SECONDS_DESC","pageSize":100}';
$timestamp = (string) time();
$nonce = bin2hex(random_bytes(16));
$bodyHash = hash('sha256', $rawBody);
$canonical = implode("\n", [$apiKey, 'POST', $path, $timestamp, $nonce, $bodyHash]);
$signature = hash_hmac('sha256', $canonical, $secret);

$curl = curl_init($baseURL . $path);
if ($curl === false) {
    throw new RuntimeException('无法初始化 cURL');
}
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $rawBody,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'X-API-Key: ' . $apiKey,
        'X-Timestamp: ' . $timestamp,
        'X-Nonce: ' . $nonce,
        'X-Signature: ' . $signature,
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_CONNECTTIMEOUT => 15,
    CURLOPT_TIMEOUT => 15,
]);
$responseBody = curl_exec($curl);
if ($responseBody === false) {
    $message = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException('请求失败：' . $message);
}
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
$result = json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
// result['data'] 交给业务处理；不要记录完整响应和票据。
printf("status=%d requestId=%s errorCode=%s\n", $status, $result['requestId'] ?? '', $result['error']['code'] ?? '');
