73 lines
2.2 KiB
PHP
73 lines
2.2 KiB
PHP
<?php
|
|
/**
|
|
* Postcode Service - Handles postcode lookup via postcode.tech API
|
|
*/
|
|
|
|
class PostcodeService
|
|
{
|
|
/**
|
|
* Lookup address by postcode and house number
|
|
*
|
|
* @param string $postcode
|
|
* @param string $number
|
|
* @return array
|
|
*/
|
|
public static function lookup(string $postcode, string $number): array
|
|
{
|
|
$postcode = str_replace(' ', '', $postcode);
|
|
|
|
if (empty($postcode) || empty($number)) {
|
|
return [
|
|
'success' => false,
|
|
'error' => 'Postcode en huisnummer zijn verplicht',
|
|
'http_code' => 400
|
|
];
|
|
}
|
|
|
|
$url = "https://postcode.tech/api/v1/postcode?postcode={$postcode}&number={$number}";
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
"Authorization: Bearer " . $_ENV['POSTCODE_TECH_KEY']
|
|
]);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
|
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$curlError = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($curlError || $httpCode >= 500) {
|
|
return [
|
|
'success' => false,
|
|
'error' => 'Postcode service niet bereikbaar, vul straat en woonplaats zelf in',
|
|
'details' => $curlError,
|
|
'http_code' => 503
|
|
];
|
|
}
|
|
|
|
if ($httpCode >= 400) {
|
|
$decoded = json_decode($response, true);
|
|
$errorMessage = ($decoded && isset($decoded['error']))
|
|
? $decoded['error']
|
|
: 'Postcode niet gevonden of ongeldige invoer, vul straat en woonplaats zelf in';
|
|
|
|
return [
|
|
'success' => false,
|
|
'error' => $errorMessage,
|
|
'http_code' => $httpCode
|
|
];
|
|
}
|
|
|
|
$data = json_decode($response, true);
|
|
|
|
return [
|
|
'success' => true,
|
|
'data' => $data,
|
|
'http_code' => 200
|
|
];
|
|
}
|
|
}
|