Thursday, 27 March 2008

Checking for Active EU Vat Numbers in Rails with SOAP and REST

Rather than implementing checksums and the like for VAT numbers I've decided to go straight to the Internet database and check the number there. It is exposed as a soap service and the ActiveRecord code looks like this:

  #Use the SOAP checker on the Internet to see if the VAT number is live
#The driver is created on first use and cached
def active?
if valid?
@@vat_check_driver ||= create_vat_check_driver
result = @@vat_check_driver.checkVat(
:countryCode => country_code,
:vatNumber => identifier
)
end
result && result.valid == "true"
end

private

require "soap/wsdlDriver"
def create_vat_check_driver
wsdl = "http://ec.europa.eu/taxation_customs/vies/api/checkVatPort?wsdl"
SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
end


'countrycode' and 'identifier' are the names of the ActiveRecord attributes containing respectively the 2 character ISO country code and the Vat number.

For a bit of mild amusement I translated this into a REST based collection sat on http://3accounts.co.uk/active_eu_vat_numbers so that you can get them using ActiveResource.

class ActiveEuVatNumber < ActiveResource::Base
self.site = "http://3accounts.co.uk"
end

ActiveEuVatNumber.find("gb123456789")


You'll get an ActiveResource exception if the record doesn't exist.