Files
karczma-aplikacja-stoliki/api/gus_lookup.php
T

117 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode([
'status' => 'error',
'message' => 'Method not allowed',
], JSON_UNESCAPED_UNICODE);
exit;
}
$nipRaw = '';
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$nipRaw = isset($_GET['nip']) ? (string) $_GET['nip'] : '';
} else {
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody ?: '', true);
if (is_array($data) && isset($data['nip'])) {
$nipRaw = (string) $data['nip'];
} elseif (isset($_POST['nip'])) {
$nipRaw = (string) $_POST['nip'];
}
}
$nip = preg_replace('/[\s\-]/', '', $nipRaw) ?? '';
if ($nip === '' || !preg_match('/^\d{10}$/', $nip)) {
http_response_code(422);
echo json_encode([
'status' => false,
'message' => 'Podaj poprawny 10-cyfrowy NIP.',
], JSON_UNESCAPED_UNICODE);
exit;
}
$config = require __DIR__ . '/../config/gus.php';
$apiKey = trim((string) ($config['api_key'] ?? ''));
$baseUrl = rtrim((string) ($config['base_url'] ?? ''), '/');
$timeout = (int) ($config['timeout_seconds'] ?? 12);
if ($apiKey === '' || $baseUrl === '') {
http_response_code(500);
echo json_encode([
'status' => false,
'message' => 'Brak konfiguracji GUS.',
], JSON_UNESCAPED_UNICODE);
exit;
}
$url = $baseUrl . '/' . rawurlencode($nip) . '?api_key=' . rawurlencode($apiKey);
$responseBody = false;
$httpCode = 0;
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => max(3, $timeout),
CURLOPT_HTTPHEADER => [
'Accept: application/json',
],
]);
$responseBody = curl_exec($ch);
$curlErrno = curl_errno($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($curlErrno !== 0) {
$responseBody = false;
}
} else {
$context = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => max(3, $timeout),
'header' => "Accept: application/json\r\n",
'ignore_errors' => true,
],
]);
$responseBody = @file_get_contents($url, false, $context);
if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
$httpCode = (int) $m[1];
}
}
if ($responseBody === false) {
http_response_code(502);
echo json_encode([
'status' => false,
'message' => 'Błąd połączenia z API GUS.',
], JSON_UNESCAPED_UNICODE);
exit;
}
$decoded = json_decode($responseBody, true);
if (!is_array($decoded)) {
http_response_code(502);
echo json_encode([
'status' => false,
'message' => 'Niepoprawna odpowiedź API GUS.',
], JSON_UNESCAPED_UNICODE);
exit;
}
if ($httpCode < 200 || $httpCode >= 300) {
http_response_code($httpCode >= 400 ? $httpCode : 502);
}
echo json_encode($decoded, JSON_UNESCAPED_UNICODE);