sendcard/lib/external.php
2026-04-14 09:47:00 +08:00

48 lines
1.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
function sendcard_fetch_credentials(string $url, int $timeoutSeconds = 15): array
{
// 使用 cURL 取外部接口(外部接口返回 JSON
$ch = curl_init();
if ($ch === false) {
throw new RuntimeException('curl_init failed');
}
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => min(10, $timeoutSeconds),
CURLOPT_TIMEOUT => $timeoutSeconds,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'User-Agent: sendcard-php/1.0',
],
// 外部是 http通常不需要证书校验若换成 https可再调整。
]);
$body = curl_exec($ch);
if ($body === false) {
$err = curl_error($ch);
curl_close($ch);
throw new RuntimeException('External request failed: ' . $err);
}
$statusCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode($body, true);
if (!is_array($json)) {
throw new RuntimeException('External response is not valid JSON');
}
// 返回:包含 HTTP 状态码与解析后的 JSON
return [
'http_status' => $statusCode,
'json' => $json,
];
}