using System.Globalization; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; namespace Khaemhat.Infrastructure.Http; /// The outcome of a VIES check. public enum ViesStatus { /// The number is registered for intra-EU operations. Valid = 0, /// The number is not registered (or not active for intra-EU operations). Invalid = 1, /// The service or the member state could not answer; try again later. Unavailable = 2, /// The request was refused as malformed (unknown country, wrong characters). InvalidInput = 3, } /// The answer of VIES, as saved on the party (SPEC ยง11.2). /// The outcome. /// The member state code asked (Greece is EL). /// The number asked, without prefix. /// When VIES answered (or when the call failed), UTC. /// The registered name, when the member state shares it. /// The registered address, when shared. /// The VIES error code for and . public sealed record ViesResult( ViesStatus Status, string CountryCode, string VatNumber, DateTimeOffset CheckedAt, string? Name, string? Address, string? Error); /// /// Checks EU VAT numbers with the VIES REST service of the European Commission /// (GET /taxation_customs/vies/rest-api/ms/{country}/vat/{number}). Network errors and timeouts become /// : a check that could not be made is never reported as invalid. /// public sealed class ViesClient { /// The public service address. public static readonly Uri DefaultBaseAddress = new("https://ec.europa.eu/taxation_customs/vies/rest-api/"); private static readonly HashSet MemberStates = new(StringComparer.Ordinal) { "AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HR", "HU", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "PT", "RO", "SE", "SI", "SK", "XI", }; private readonly HttpClient _http; private readonly TimeProvider _time; /// Creates the client. /// The HTTP client; its base address defaults to . /// The clock. public ViesClient(HttpClient http, TimeProvider time) { ArgumentNullException.ThrowIfNull(http); ArgumentNullException.ThrowIfNull(time); _http = http; _http.BaseAddress ??= DefaultBaseAddress; _time = time; } /// The VIES member state code for an ISO country code (Greece: GR becomes EL). /// ISO 3166-1 alpha-2 code. /// The VIES code, or outside the EU. public static string? MemberStateCode(string? isoCountryCode) { var code = isoCountryCode?.Trim().ToUpperInvariant(); code = code == "GR" ? "EL" : code; return code is not null && MemberStates.Contains(code) ? code : null; } /// Checks a VAT number. /// ISO or VIES country code. /// The number, with or without the country prefix. /// Cancels the call. /// The outcome. public async Task CheckAsync(string countryCode, string vatNumber, CancellationToken cancellationToken) { var state = MemberStateCode(countryCode); var number = string.Concat((vatNumber ?? string.Empty).Where(char.IsAsciiLetterOrDigit)).ToUpperInvariant(); if (state is not null && number.StartsWith(state, StringComparison.Ordinal)) { number = number[state.Length..]; } if (state is null || number.Length == 0) { return new ViesResult(ViesStatus.InvalidInput, countryCode ?? string.Empty, number, _time.GetUtcNow(), null, null, "INVALID_INPUT"); } try { using var response = await _http.GetAsync(new Uri($"ms/{state}/vat/{Uri.EscapeDataString(number)}", UriKind.Relative), cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { var status = (int)response.StatusCode; return Failed(state, number, status is >= 400 and < 500 && status != 429 ? ViesStatus.InvalidInput : ViesStatus.Unavailable, "HTTP_" + status.ToString(CultureInfo.InvariantCulture)); } var answer = await response.Content.ReadFromJsonAsync(cancellationToken).ConfigureAwait(false); if (answer is null) { return Failed(state, number, ViesStatus.Unavailable, "EMPTY_RESPONSE"); } var error = answer.UserError; if (answer.IsValid) { return new ViesResult(ViesStatus.Valid, state, number, answer.RequestDate ?? _time.GetUtcNow(), Clean(answer.Name), Clean(answer.Address), null); } return error is null or "VALID" or "INVALID" ? new ViesResult(ViesStatus.Invalid, state, number, answer.RequestDate ?? _time.GetUtcNow(), null, null, null) : Failed(state, number, error == "INVALID_INPUT" ? ViesStatus.InvalidInput : ViesStatus.Unavailable, error); } catch (HttpRequestException ex) { return Failed(state, number, ViesStatus.Unavailable, ex.HttpRequestError.ToString()); } catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) { return Failed(state, number, ViesStatus.Unavailable, "TIMEOUT"); } catch (JsonException) { return Failed(state, number, ViesStatus.Unavailable, "BAD_RESPONSE"); } } private ViesResult Failed(string state, string number, ViesStatus status, string error) => new(status, state, number, _time.GetUtcNow(), null, null, error); // Member states that do not share the data answer with "---". private static string? Clean(string? value) { var text = value?.Trim(); return string.IsNullOrEmpty(text) || text == "---" ? null : text; } private sealed class ViesAnswer { [JsonPropertyName("isValid")] public bool IsValid { get; set; } [JsonPropertyName("requestDate")] public DateTimeOffset? RequestDate { get; set; } [JsonPropertyName("userError")] public string? UserError { get; set; } [JsonPropertyName("name")] public string? Name { get; set; } [JsonPropertyName("address")] public string? Address { get; set; } } }