Business-Tax-VAT-Validation

 view release on metacpan or  search on metacpan

lib/Business/Tax/VAT/Validation.pm  view on Meta::CPAN

package Business::Tax::VAT::Validation;
=pod

=encoding UTF-8

=cut

 ############################################################################
# Original author:                                                           #
# IT Development software                                                    #
# European VAT number validator                                              #
# Created 06/08/2003                                                         #
#                                                                            #
# Maintainership kindly handed over to David Precious (BIGPRESH) in 2015     #
 ############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 2003 Bernard Nauwelaerts  All Rights Reserved.                   #
# Copyright 2015 David Precious       All Rights Reserved.                   #
#                                                                            #
# THIS SOFTWARE IS RELEASED UNDER THE GNU Public Licence version 3           #
# Please see COPYING for details                                             #
#                                                                            #
# DISCLAIMER                                                                 #
#  As usual with GNU software, this one is provided as is,                   #
#  WITHOUT ANY WARRANTY, without even the implied warranty of                #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                      #
#                                                                            #
############################################################################
use strict;
use warnings;

our $VERSION = '1.24';

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use JSON qw/ decode_json /;

=head1 NAME

Business::Tax::VAT::Validation - Validate EU VAT numbers against VIES/HMRC

=head1 SYNOPSIS

  use Business::Tax::VAT::Validation;

  my $hvatn=Business::Tax::VAT::Validation->new();

  # Check number
  if ($hvatn->check($VAT, [$member_state])){
        print "OK\n";
  } else {
        print $hvatn->get_last_error;
  }

=head1 DESCRIPTION

This class provides an easy API to check European VAT numbers' syntax,
and check if they have been registered by the competent authorities.

It asks the EU database (VIES) for this, using its SOAP API.  Basic checks that
the supplied VAT number fit the expected format for the specified EU member
state are performed first, to avoid unnecessarily sending queries to VIES for
input that could never be valid.

It also supports looking up VAT codes from the United Kingdom by using the
REST API provided by their HMRC.

=head1 CONSTRUCTOR

=over 4

=item B<new> Class constructor.

    $hvatn=Business::Tax::VAT::Validation->new();


    # If your system is located behind a proxy :

    $hvatn=Business::Tax::VAT::Validation->new(-proxy => ['http', 'http://example.com:8001/']);

    # Note : See LWP::UserAgent for proxy options.

=cut

sub new {
    my ( $class, %arg ) = @_;
    my $self = {
        baseurl      => $arg{baseurl} || 'https://ec.europa.eu/taxation_customs/vies/services/checkVatService',
        hmrc_baseurl => $arg{hmrc_baseurl} || 'https://api.service.hmrc.gov.uk/organisations/vat/check-vat-number/lookup/',
        error        => '',
        error_code   => 0,
        response     => '',
        re           => {
            ### t/01_localcheck.t tests if these regexps accepts all regular VAT numbers, according to VIES FAQ

lib/Business/Tax/VAT/Validation.pm  view on Meta::CPAN


=item *
 18  Member Sevice Unavailable: The EU database is unable to reach the requested member's database.

=item *
 19  The EU database is too busy.

=item *
 20  Connexion to the VIES database failed.

=item *
 21  The VIES interface failed to parse a stream. This error occurs unpredictabely, so you should retry your validation request.

=item *
257  Invalid response, please contact the author of this module. : This normally only happens if this software doesn't recognize any valid pattern into the response document: this generally means that the database interface has been modified, and you...

=item *
500  The VIES server encountered an internal server error.
Error 500 : soap:Server TIMEOUT
Error 500 : soap:Server MS_UNAVAILABLE

=back

If error_code > 16,  you should temporarily accept the provided number, and periodically perform new checks until response is OK or error < 17
If error_code > 256, you should temporarily accept the provided number, contact the author, and perform a new check when the software is updated.

=cut

sub get_last_error {
    $_[0]->{error};
}

sub get_last_error_code {
    $_[0]->{error_code};
}

=item B<get_last_response> - Returns the full last response

=cut

sub get_last_response {
    $_[0]->{response};
}

### PRIVATE FUNCTIONS ==========================================================
sub _get_ua {
    my ($self) = @_;
    my $ua = LWP::UserAgent->new;
    if ( ref $self->{proxy} eq 'ARRAY' ) {
        $ua->proxy( @{ $self->{proxy} } );
    } else {
        $ua->env_proxy;
    }
    $ua->agent( 'Business::Tax::VAT::Validation/'. $Business::Tax::VAT::Validation::VERSION );
    return $ua;
}

sub _check_vies {
  my ($self, $vatNumber, $countryCode) = @_;
  my $ua = $self->_get_ua();
  my $request = HTTP::Request->new(POST => $self->{baseurl});
  $request->content(_in_soap_envelope($vatNumber, $countryCode));
  $request->content_type("text/xml; charset=utf-8");

  my $response = $ua->request($request);

  return $countryCode . '-' . $vatNumber if $self->_is_res_ok( $response->code, $response->decoded_content );
}

sub _check_hmrc {
    my ($self, $vatNumber, $countryCode) = @_;
    my $ua = $self->_get_ua();

    my $request = HTTP::Request->new(GET => $self->{hmrc_baseurl}.$vatNumber);
    $request->header(Accept => 'application/vnd.hmrc.1.0+json');
    my $response = $ua->request($request);

    $self->{res} = $response->decoded_content;
    if ($response->code == 200) {
        my $data = decode_json($self->{res});
        $self->{information}->{name} = $data->{target}->{name};
        my $line = 1;
        my $address = "";
        while (defined $data->{target}->{address}->{"line$line"}) {
            $address .= $data->{target}->{address}->{"line$line"}."\n";
            $line++;
        }
        $address .= $data->{target}->{address}->{postcode};
        $address .= "\n".$data->{target}->{address}->{countryCode};
        $self->{information}->{address} = $address;
        $self->_set_error( -1, 'Valid VAT Number');
    }
    elsif ($response->code == 404) {
        return $self->_set_error( 2, 'Invalid VAT Number ('.$vatNumber.')');
    }
    elsif ($response->code == 400) {
        return $self->_set_error( 3, 'VAT number badly formed ('.$vatNumber.')');
    }
    else {
        return $self->_set_error( 500, 'Could not contact HMRC: '.$response->status_line);
    }

    return $countryCode . '-' . $vatNumber;
}

sub _format_vatn {
    my ( $self, $vatn, $mscc ) = @_;
    my $null = '';
    $vatn =~ s/\-/ /g;
    $vatn =~ s/\./ /g;
    $vatn =~ s/\s+/ /g;
    if ( !$mscc && $vatn =~ s/^($self->{members}) ?/$null/e ) {
        $mscc = $1;
    }
    return $self->_set_error( 0, "Unknown MS code" )
      if $mscc !~ m/^($self->{members})$/;
    my $re = $self->{re}{$mscc};
    return $self->_set_error( 1, "Invalid VAT number format" )
      if $vatn !~ m/^$re$/;
    ( $vatn, $mscc );
}

sub _in_soap_envelope {
    my ($vatNumber, $countryCode)=@_;
    return <<EWWSOAP;
<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
     <s11:Body>
     <tns1:checkVat xmlns:tns1='urn:ec.europa.eu:taxud:vies:services:checkVat:types'>
     <tns1:countryCode>$countryCode</tns1:countryCode>
     <tns1:vatNumber>$vatNumber</tns1:vatNumber>
     </tns1:checkVat>
     </s11:Body>
     </s11:Envelope>
EWWSOAP



( run in 1.304 second using v1.01-cache-2.11-cpan-3c2a17b8caa )