Skip to content

Instantly share code, notes, and snippets.

@btxtiger
Last active December 21, 2023 10:19
Show Gist options
  • Save btxtiger/b6f78e1574e0772fd9b83c3ff5946400 to your computer and use it in GitHub Desktop.
Save btxtiger/b6f78e1574e0772fd9b83c3ff5946400 to your computer and use it in GitHub Desktop.
EU VAT-ID validation in PHP
<?php
namespace App\Services;
use Http;
use Log;
class EUVatService {
/**
* Check vat in EU interface
*/
public static function isVatIdValid(string $vatId): ?bool {
$countryCode = substr($vatId, 0, 2);
// Regex pattern for EU VAT ID validation: 2 uppercase letters followed by any characters
$pattern = '/^[A-Z]{2,}.*$/';
$body = '';
if (preg_match($pattern, $vatId) === 1) {
$resp = Http::get("https://ec.europa.eu/taxation_customs/vies/rest-api/ms/$countryCode/vat/$vatId");
$body = $resp->json();
error_log(json_encode($body, JSON_PRETTY_PRINT));
if ($body['isValid'] ?? false) {
return true;
}
if ($body['userError'] === 'MS_MAX_CONCURRENT_REQ') {
return null;
}
if ($body['userError'] === 'MS_UNAVAILABLE') {
return null;
}
if ($body['userError'] === 'INVALID') {
return false;
}
if ($body['userError'] === 'INVALID_INPUT') {
return false;
}
} else {
$body = "Provided vatId didn't match the base requirement pattern. Value: " . $vatId;
}
Log::debug('VatId check failed. Response: ', (array) $body);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment