PHP code example of netresearch / sdk-eu-vat

1. Go to this page and download the library: Download netresearch/sdk-eu-vat library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

netresearch / sdk-eu-vat example snippets




use Netresearch\EuVatSdk\Factory\VatRetrievalClientFactory;
use Netresearch\EuVatSdk\DTO\Request\VatRatesRequest;

// Create client
$client = VatRetrievalClientFactory::create();

// Request VAT rates for Germany
$request = new VatRatesRequest(
    memberStates: ['DE'],
    situationOn: new DateTime('2024-01-01')
);

try {
    $response = $client->retrieveVatRates($request);
    
    foreach ($response->getResults() as $result) {
        echo sprintf(
            "VAT rate for %s: %s%%\n",
            $result->getMemberState(),
            (string) $result->getRate()
        );
    }
} catch (\Netresearch\EuVatSdk\Exception\VatServiceException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

$request = new VatRatesRequest(
    memberStates: ['DE', 'FR', 'IT', 'ES'],
    situationOn: new DateTime('2024-01-01')
);

$response = $client->retrieveVatRates($request);

// Group results by country
foreach ($response->getResults() as $result) {
    $rate = $result->getRate();

    // Some rate types carry no percentage at all — getValue() is null for those,
    // and casting the rate to string yields an empty string. Decide explicitly
    // what to display instead of printing an empty percentage.
    $display = $rate->getValue() === null ? 'n/a' : (string) $rate . '%';

    printf(
        "%s: %s (%s rate)\n",
        $result->getMemberState(),
        $display,
        $rate->getType()
    );
}

use Brick\Math\BigDecimal;

$vatRate = $result->getRate();

// Get precise decimal value
$rate = $vatRate->getValue(); // Returns BigDecimal, or null for rate types without a value

$netAmount = BigDecimal::of('100.00');

if ($rate === null) {
    // No percentage was supplied for this rate type (e.g. exempt / out of scope).
    // Treat it as zero VAT rather than dereferencing the null value.
    echo "Net: €" . $netAmount->__toString() . " (no VAT, rate type: " . $vatRate->getType() . ")\n";
} else {
    // Calculate VAT amount (100 EUR at 19% VAT)
    $vatAmount = $netAmount->multipliedBy($rate)->dividedBy('100', 2);
    $grossAmount = $netAmount->plus($vatAmount);

    // Be explicit when printing
    echo "Net: €" . $netAmount->__toString() . "\n";
    echo "VAT: €" . $vatAmount->__toString() . "\n";
    echo "Gross: €" . $grossAmount->__toString() . "\n";
}

use Netresearch\EuVatSdk\Client\ClientConfiguration;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create custom logger
$logger = new Logger('vat-service');
$logger->pushHandler(new StreamHandler('vat-service.log', Logger::INFO));

// Configure client
$config = ClientConfiguration::production($logger)
    ->withTimeout(30)
    ->withDebug(true);

$client = VatRetrievalClientFactory::create($config);

use Netresearch\EuVatSdk\Exception\{
    InvalidRequestException,
    ServiceUnavailableException,
    ConfigurationException,
    VatServiceException
};

try {
    $response = $client->retrieveVatRates($request);
} catch (InvalidRequestException $e) {
    // Client-side validation errors, or a SOAP fault the service blames on the
    // request (faultcode env:Client / Sender).
    echo "Invalid request: " . $e->getMessage();
    // getErrorCode() returns the TEDB identifier from the faultstring, e.g.
    // "TEDB-ERR-2", or null when the error was raised locally by the SDK.
    echo "Error code: " . ($e->getErrorCode() ?? 'n/a');
} catch (ServiceUnavailableException $e) {
    // Network/transport failure, or a SOAP fault the service blames on itself
    // (faultcode env:Server / Receiver). getErrorCode() is null for transport errors.
    echo "Service unavailable: " . $e->getMessage();
} catch (ConfigurationException $e) {
    // Invalid SDK configuration
    echo "Configuration error: " . $e->getMessage();
} catch (VatServiceException $e) {
    // Any other SDK-related error
    echo "VAT service error: " . $e->getMessage();
}

# config/services.yaml
services:
    # Configure the ClientConfiguration service first, injecting the logger here
    Netresearch\EuVatSdk\Client\ClientConfiguration:
        factory: ['Netresearch\EuVatSdk\Client\ClientConfiguration', 'production']
        arguments:
            - '@?logger' # Pass the logger, if it exists

    # The client service now only needs the pre-configured configuration service
    Netresearch\EuVatSdk\Client\VatRetrievalClientInterface:
        factory: ['Netresearch\EuVatSdk\Factory\VatRetrievalClientFactory', 'create']
        arguments:
            - '@Netresearch\EuVatSdk\Client\ClientConfiguration'

// config/app.php
'providers' => [
    // ...
    App\Providers\VatServiceProvider::class,
];

// app/Providers/VatServiceProvider.php


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Netresearch\EuVatSdk\Client\ClientConfiguration;
use Netresearch\EuVatSdk\Client\VatRetrievalClientInterface;
use Netresearch\EuVatSdk\Factory\VatRetrievalClientFactory;
use Psr\Log\LoggerInterface;

class VatServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(VatRetrievalClientInterface::class, function ($app) {
            $logger = $app->make(LoggerInterface::class);
            
            return VatRetrievalClientFactory::create(
                ClientConfiguration::production($logger)
            );
        });
    }
}

$config = ClientConfiguration::production($logger)
    ->withTimeout(30)                    // 30 second timeout
    ->withSoapOptions([                  // Optimize SOAP client
        'cache_wsdl' => WSDL_CACHE_DISK,
        'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
        'connection_timeout' => 30,
    ]);