-
Notifications
You must be signed in to change notification settings - Fork 59
/
Vies.php
540 lines (479 loc) · 18 KB
/
Vies.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
<?php
declare (strict_types=1);
/**
* Vies
*
* Component using the European Commission (EC) VAT Information Exchange System (VIES) to verify and validate VAT
* registration numbers in the EU, using PHP and Composer.
*
* @author Michelangelo van Dam <dragonbe+github@gmail.com>
* @license MIT
*
*/
namespace DragonBe\Vies;
/**
* Thrown under certain circumstances by SoapClient, when exchanging data with European Commission (EC) VAT
* Information Exchange System (VIES).
*
* Common SoapFaults include:
*
* MS_UNAVAILABLE : The Member State service is unavailable. Try again later or with another Member State.
* SERVER_BUSY : The service can not process your request. Try again later.
* SERVICE_UNAVAILABLE : The SOAP service is unavailable, try again later.
* TIMEOUT : The Member State service could not be reach in time, try again later or with another
* Member State
*
* GLOBAL_MAX_CONCURRENT_REQ : The number of concurrent requests is more than the VIES service allows.
* MS_MAX_CONCURRENT_REQ : Same as MS_MAX_CONCURRENT_REQ.
*/
use DragonBe\Vies\Validator;
use SoapClient;
use SoapFault;
/**
* Class Vies
*
* This class provides a soap client for usage of the VIES web service
* provided by the European Commission to validate VAT numbers of companies
* registered within the European Union
*
* @category DragonBe
* @package \DragonBe\Vies
* @link http://ec.europa.eu/taxation_customs/vies/faqvies.do#item16
*/
class Vies
{
const VIES_PROTO = 'https';
const VIES_DOMAIN = 'ec.europa.eu';
const VIES_PORT = 443;
const VIES_WSDL = '/taxation_customs/vies/checkVatService.wsdl';
const VIES_TEST_WSDL = '/taxation_customs/vies/checkVatTestService.wsdl';
const VIES_EU_COUNTRY_TOTAL = 28;
const VIES_TEST_VAT_NRS = [100, 200, 201, 202, 300, 301, 302, 400, 401, 500, 501, 600, 601];
protected const VIES_EU_COUNTRY_LIST = [
'AT' => ['name' => 'Austria', 'validator' => Validator\ValidatorAT::class],
'BE' => ['name' => 'Belgium', 'validator' => Validator\ValidatorBE::class],
'BG' => ['name' => 'Bulgaria', 'validator' => Validator\ValidatorBG::class],
'CY' => ['name' => 'Cyprus', 'validator' => Validator\ValidatorCY::class],
'CZ' => ['name' => 'Czech Republic', 'validator' => Validator\ValidatorCZ::class],
'DE' => ['name' => 'Germany', 'validator' => Validator\ValidatorDE::class],
'DK' => ['name' => 'Denmark', 'validator' => Validator\ValidatorDK::class],
'EE' => ['name' => 'Estonia', 'validator' => Validator\ValidatorEE::class],
'EL' => ['name' => 'Greece', 'validator' => Validator\ValidatorEL::class],
'ES' => ['name' => 'Spain', 'validator' => Validator\ValidatorES::class],
'FI' => ['name' => 'Finland', 'validator' => Validator\ValidatorFI::class],
'FR' => ['name' => 'France', 'validator' => Validator\ValidatorFR::class],
'HR' => ['name' => 'Croatia', 'validator' => Validator\ValidatorHR::class],
'HU' => ['name' => 'Hungary', 'validator' => Validator\ValidatorHU::class],
'IE' => ['name' => 'Ireland', 'validator' => Validator\ValidatorIE::class],
'IT' => ['name' => 'Italy', 'validator' => Validator\ValidatorIT::class],
'LU' => ['name' => 'Luxembourg', 'validator' => Validator\ValidatorLU::class],
'LV' => ['name' => 'Latvia', 'validator' => Validator\ValidatorLV::class],
'LT' => ['name' => 'Lithuania', 'validator' => Validator\ValidatorLT::class],
'MT' => ['name' => 'Malta', 'validator' => Validator\ValidatorMT::class],
'NL' => ['name' => 'Netherlands', 'validator' => Validator\ValidatorNL::class],
'PL' => ['name' => 'Poland', 'validator' => Validator\ValidatorPL::class],
'PT' => ['name' => 'Portugal', 'validator' => Validator\ValidatorPT::class],
'RO' => ['name' => 'Romania', 'validator' => Validator\ValidatorRO::class],
'SE' => ['name' => 'Sweden', 'validator' => Validator\ValidatorSE::class],
'SI' => ['name' => 'Slovenia', 'validator' => Validator\ValidatorSI::class],
'SK' => ['name' => 'Slovakia', 'validator' => Validator\ValidatorSK::class],
'GB' => ['name' => 'United Kingdom', 'validator' => Validator\ValidatorGB::class],
'XI' => ['name' => 'United Kingdom (Northern Ireland)', 'validator' => Validator\ValidatorXI::class],
'EU' => ['name' => 'MOSS Number', 'validator' => Validator\ValidatorEU::class],
];
protected const VIES_EXCLUDED_COUNTRY_CODES = [
'GB' => ['name' => 'United Kingdom', 'excluded' => '2021-01-01', 'reason' => 'Brexit'],
];
/**
* @var bool Require explicit checking against self::VIES_TEST_VAT_NRS
*/
protected $allowTestCodes = true;
/**
* @var SoapClient
*/
protected $soapClient;
/**
* @var string The WSDL for VIES service
*/
protected $wsdl;
/**
* @var array Options for the SOAP client
*/
protected $options;
/**
* @var HeartBeat A heartbeat checker to verify if the VIES service is available
*/
protected $heartBeat;
/**
* Allow VAT number to be compared to the know VIES test codes (self::VIES_TEST_VAT_NRS)
*
* @return self
*/
public function allowTestCodes(): self
{
$this->allowTestCodes = true;
return $this;
}
/**
* Disallow VAT number to be compared to the know VIES test codes (self::VIES_TEST_VAT_NRS)
*
* @return self
*/
public function disallowTestCodes(): self
{
$this->allowTestCodes = false;
return $this;
}
/**
* Check if test error codes are allowed
*
* @return bool
*/
public function areTestCodesAllowed(): bool
{
return $this->allowTestCodes;
}
/**
* Retrieves the SOAP client that will be used to communicate with the VIES
* SOAP service.
*
* @return SoapClient
*/
public function getSoapClient(): SoapClient
{
$this->soapClient = $this->soapClient ?? new SoapClient($this->getWsdl(), $this->getOptions());
return $this->soapClient;
}
/**
* Sets the PHP SOAP Client and allows you to override the use of the native
* PHP SoapClient for testing purposes or for better integration in your own
* application.
*
* @param SoapClient $soapClient
* @return self
*/
public function setSoapClient(SoapClient $soapClient): self
{
$this->soapClient = $soapClient;
return $this;
}
/**
* Retrieves the location of the WSDL for the VIES SOAP service
*
* @return string
*/
public function getWsdl(): string
{
$this->wsdl = $this->wsdl ?? sprintf('%s://%s%s', self::VIES_PROTO, self::VIES_DOMAIN, self::VIES_WSDL);
return $this->wsdl;
}
/**
* Sets the location of the WSDL for the VIES SOAP Service
*
* @param string $wsdl
*
* @return self
*
* @example http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
*/
public function setWsdl(string $wsdl): self
{
$this->wsdl = $wsdl;
return $this;
}
/**
* Retrieves the options for the PHP SOAP service
*
* @return array
*/
public function getOptions(): array
{
$this->options = $this->options ?? [];
return $this->options;
}
/**
* Set options for the native PHP Soap Client
*
* @param array $options
* @return self
* @link http://php.net/manual/en/soapclient.soapclient.php
*/
public function setOptions(array $options): self
{
$this->options = $options;
return $this;
}
/**
* Retrieves the heartbeat class that offers the option to check if the VIES
* service is up-and-running.
*
* @return HeartBeat
*/
public function getHeartBeat(): HeartBeat
{
$this->heartBeat = $this->heartBeat ?? new HeartBeat(self::VIES_DOMAIN, self::VIES_PORT);
return $this->heartBeat;
}
/**
* Sets the heartbeat functionality to verify if the VIES service is alive or not,
* especially since this service tends to have a bad reputation of its availability.
*
* @param HeartBeat $heartBeat
* @return self
*/
public function setHeartBeat(HeartBeat $heartBeat): self
{
$this->heartBeat = $heartBeat;
return $this;
}
/**
* Validates a given country code and VAT number and returns a
* \DragonBe\Vies\CheckVatResponse object
*
* @param string $countryCode The two-character country code of a European
* member country
* @param string $vatNumber The VAT number (without the country
* identification) of a registered company
* @param string $requesterCountryCode The two-character country code of a European
* member country
* @param string $requesterVatNumber The VAT number (without the country
* identification) of a registered company
* @param string $traderName The name of the company you want to validate
* @param string $traderCompanyType The type of company you want to validate
* @param string $traderStreet The street of the company you want to validate
* @param string $traderPostcode The postal code of the company you want to validate
* @param string $traderCity The city of the company you want to validate
* @return CheckVatResponse
* @throws ViesException
* @throws ViesServiceException
*/
public function validateVat(
string $countryCode,
string $vatNumber,
string $requesterCountryCode = '',
string $requesterVatNumber = '',
string $traderName = '',
string $traderCompanyType = '',
string $traderStreet = '',
string $traderPostcode = '',
string $traderCity = ''
): CheckVatResponse {
if ($this->validateCountryCode($countryCode, true) === false) {
throw new ViesException(sprintf('Invalid country code "%s" provided', $countryCode));
}
if ($this->areTestCodesAllowed() && in_array((int) $vatNumber, self::VIES_TEST_VAT_NRS, true)) {
return $this->validateTestVat($countryCode, $vatNumber);
}
$vatNumber = self::filterVat($vatNumber);
if (! $this->validateVatSum($countryCode, $vatNumber)) {
$params = (object) [
'countryCode' => $countryCode,
'vatNumber' => $vatNumber,
'requestDate' => date_create(),
'valid' => false,
];
return new CheckVatResponse($params);
}
if (array_key_exists($countryCode, self::VIES_EXCLUDED_COUNTRY_CODES)) {
throw new ViesServiceException(sprintf(
'Country %s is no longer supported by VIES services provided by EC since %s because of %s',
self::VIES_EXCLUDED_COUNTRY_CODES[$countryCode]['name'],
self::VIES_EXCLUDED_COUNTRY_CODES[$countryCode]['excluded'],
self::VIES_EXCLUDED_COUNTRY_CODES[$countryCode]['reason'],
));
}
$requestParams = [
'countryCode' => $countryCode,
'vatNumber' => $vatNumber,
];
$this->addOptionalArguments($requestParams, 'traderName', $traderName);
$this->addOptionalArguments($requestParams, 'traderCompanyType', $traderCompanyType);
$this->addOptionalArguments($requestParams, 'traderStreet', $traderStreet);
$this->addOptionalArguments($requestParams, 'traderPostcode', $traderPostcode);
$this->addOptionalArguments($requestParams, 'traderCity', $traderCity);
if ($requesterCountryCode && $requesterVatNumber) {
if ($this->validateCountryCode($requesterCountryCode) === false) {
throw new ViesException(sprintf('Invalid requestor country code "%s" provided', $requesterCountryCode));
}
$requesterVatNumber = self::filterVat($requesterVatNumber);
$requestParams['requesterCountryCode'] = $requesterCountryCode;
$requestParams['requesterVatNumber'] = $requesterVatNumber;
}
try {
return new CheckVatResponse(
$this->getSoapClient()->__soapCall(
'checkVatApprox',
[$requestParams]
)
);
} catch (SoapFault $e) {
$message = sprintf(
'Back-end VIES service cannot validate the VAT number "%s%s" at this moment. '
. 'The service responded with the critical error "%s". This is probably a temporary '
. 'problem. Please try again later.',
$countryCode,
$vatNumber,
$e->getMessage()
);
throw new ViesServiceException($message, 0, $e);
}
}
/**
* Validate a VAT number control sum
*
* @param string $countryCode The two-character country code of a European
* member country
* @param string $vatNumber The VAT number (without the country
* identification) of a registered company
* @return bool
* @throws ViesException
*/
public function validateVatSum(string $countryCode, string $vatNumber): bool
{
if ($this->validateCountryCode($countryCode, true) === false) {
throw new ViesException(sprintf('Invalid country code "%s" provided', $countryCode));
}
$className = self::VIES_EU_COUNTRY_LIST[$countryCode]['validator'];
return (new $className())->validate(self::filterVat($vatNumber));
}
/**
* Filters a VAT number and normalizes it to an alfanumeric string
*
* @param string $vatNumber
* @return string
* @static
*/
public static function filterVat(string $vatNumber): string
{
return str_replace([' ', '.', '-'], '', $vatNumber);
}
/**
* Splits a VAT ID on country code and VAT number
*
* @param string $vatId
* @return array
*/
public function splitVatId(string $vatId): array
{
return [
'country' => substr($vatId, 0, 2),
'id' => substr($vatId, 2),
];
}
/**
* A list of European Union countries as of January 2015
*
* @return array
*/
public static function listEuropeanCountries(): array
{
static $list;
if (! $list) {
$list = array_combine(
array_keys(self::VIES_EU_COUNTRY_LIST),
array_column(self::VIES_EU_COUNTRY_LIST, 'name')
);
unset($list['EU']);
foreach (array_keys(self::VIES_EXCLUDED_COUNTRY_CODES) as $excludedCountryCode) {
unset($list[$excludedCountryCode]);
}
}
return $list;
}
/**
* Here you can safely add optional arguments for verification
*
* @param array $requestParams
* @param string $argumentKey
* @param string $argumentValue
* @return bool
*/
private function addOptionalArguments(array &$requestParams, string $argumentKey, string $argumentValue): bool
{
if ('' !== $argumentValue) {
$argumentValue = $this->filterArgument($argumentValue);
if (! $this->validateArgument($argumentValue)) {
throw new \InvalidArgumentException('The provided argument is not valid');
}
$requestParams[$argumentKey] = $argumentValue;
return true;
}
return false;
}
/**
* Filter the data so it's clean to be validated before sending
* to the VIES service
*
* @param string $argumentValue
* @return string
*/
private function filterArgument(string $argumentValue): string
{
$argumentValue = str_replace(['"', '\''], '', $argumentValue);
return filter_var($argumentValue, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
}
/**
* Validate the data to prevent XSS and other nasty things
* from happening at the VIES service
*
* @param string $argumentValue
* @return bool
*/
private function validateArgument(string $argumentValue): bool
{
$regexp = '/^[a-zA-Z0-9\s\.\-,&\+\(\)\/º\pL]+$/u';
if (false === filter_var($argumentValue, FILTER_VALIDATE_REGEXP, [
'options' => ['regexp' => $regexp]
])) {
return false;
}
return true;
}
/**
* @param string $countryCode
* @param string $testVatNumber
*
* @return CheckVatResponse
* @throws ViesServiceException
*/
private function validateTestVat(string $countryCode, string $testVatNumber): CheckVatResponse
{
$wsdlUri = sprintf('%s://%s%s', self::VIES_PROTO, self::VIES_DOMAIN, self::VIES_TEST_WSDL);
$this->setWsdl($wsdlUri);
$requestParams = [
'countryCode' => $countryCode,
'vatNumber' => $testVatNumber,
];
try {
return new CheckVatResponse(
$this->getSoapClient()->__soapCall('checkVat', [$requestParams])
);
} catch (SoapFault $e) {
$message = sprintf(
'Back-end VIES service cannot validate the VAT number "%s%s" at this moment. '
. 'The service responded with the critical error "%s". This is probably a temporary '
. 'problem. Please try again later.',
$countryCode,
$testVatNumber,
$e->getMessage()
);
throw new ViesServiceException($message, 0, $e);
}
}
/**
* @param string $countryCode
* @param bool $useExcludedCountries
*
* @return bool
*/
private function validateCountryCode(string $countryCode, bool $useExcludedCountries = false): bool
{
if (! isset(self::VIES_EU_COUNTRY_LIST[$countryCode])) {
return false;
}
if ($useExcludedCountries === false && isset(self::VIES_EXCLUDED_COUNTRY_CODES[$countryCode])) {
return false;
}
return true;
}
}