Skip to content

Instantly share code, notes, and snippets.

@mylk
Created August 14, 2016 17:21
Show Gist options
  • Save mylk/a77e41813a06ec23c6ba0c40f935c9da to your computer and use it in GitHub Desktop.
Save mylk/a77e41813a06ec23c6ba0c40f935c9da to your computer and use it in GitHub Desktop.
VIES VAT checker service (uses europe.eu)
<?php
/*
* Installation (Symfony):
* =======================
* # services.yml
* services:
* # ...
* acme.vat_checker:
* class: Acme\AcmeBundle\Service\VatCheckerService
* calls: [ [setupDependencies, [@logger]] ]
*
* Usage (Symfony):
* ================
* $vatChecker = $this->get("acme.vat_checker");
* $vatCheckerResponse = $vatChecker->check($vatId);
* $countryCode = $vatCheckerResponse->countryCode;
*/
namespace Acme\AcmeBundle\Service;
use Psr\Log\LoggerInterface;
class VatCheckerService
{
private $logger;
public function setupDependencies(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function check($vatId)
{
$response = new \stdClass();
$response->countryCode = null;
if ($vatId) {
$vatId = \str_replace(array(" ", ".", "-", ",", ", "), "", \trim($vatId));
$countryCode = \substr($vatId, 0, 2);
$vatNumber = \substr($vatId, 2);
$client = new \SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
if ($client) {
try {
$response = $client->checkVat(array("countryCode" => $countryCode, "vatNumber" => $vatNumber));
if (false === $response->valid) {
return null;
}
} catch (\SoapFault $ex) {
// most probably vat country not in EU
$error = $ex->faultstring;
$this->logger->error($error);
if (!\ctype_alpha($countryCode)) {
$response->countryCode = null;
} else {
$response->countryCode = $countryCode;
}
}
} else {
$this->logger->error("VATChecker error: Could not connect to host (europe.eu down?)");
return null;
}
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment