Code snippet to validate UK VAT IDs with Barns2uks EDD EU VAT plugin. Requires https://vatsense.com API KEY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//License is public domain, use to your hearts content. I take no ownership or responsibility | |
use Barn2\Plugin\EDD_VAT\VAT_Check_Result; | |
add_filter( 'edd_vat_number_check', function ($result, $vat_number, $country_code ) { | |
if($result->error === VAT_Check_Result::INVALID_INPUT && $country_code==='GB') { | |
if(strlen($vat_number)!==9 || !filter_var($vat_number, FILTER_VALIDATE_INT)) { | |
return $result; | |
} | |
/** @noinspection PhpUndefinedConstantInspection */ | |
$basicauth = 'Basic ' . base64_encode( 'user:'.VATSENSE_API_SECRET ); | |
$headers = array( | |
'Authorization' => $basicauth, | |
'Content-type' => 'application/json', | |
); | |
$request_data = ['headers' => $headers]; | |
$response = wp_remote_get('https://api.vatsense.com/1.0/validate?vat_number='.$country_code.$vat_number, $request_data); | |
$body = wp_remote_retrieve_body($response); | |
$code = wp_remote_retrieve_response_code($response); | |
if(200 === $code) { | |
try { | |
$data = json_decode($body, true); | |
$result->valid = filter_var( $data['data']['valid'], FILTER_VALIDATE_BOOLEAN ); | |
if($result->valid) { | |
$result->name = $data['data']['company']['company_name']; | |
$address = explode( "\n", $data['data']['company']['company_address'] ); | |
$result->valid = filter_var( $data['data']['valid'], FILTER_VALIDATE_BOOLEAN ); | |
$result->address = implode( apply_filters( 'edd_vat_check_result_address_separator', ', ' ), array_filter( $address ) ); | |
$result->error=null; | |
} else { | |
$result->error = VAT_Check_Result::INVALID_VAT_NUMBER; | |
} | |
} catch (Exception $e) { | |
$result->error = VAT_Check_Result::API_ERROR; | |
} | |
} elseif(400 === $code){ | |
$result->error = VAT_Check_Result::INVALID_INPUT; | |
}else { | |
$result->error = VAT_Check_Result::API_ERROR; | |
} | |
} | |
return $result; | |
},0,3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment