Skip to content

Instantly share code, notes, and snippets.

@SiR-DanieL
Last active November 7, 2023 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SiR-DanieL/cd28c394259456c9c18213ca43f2ab6e to your computer and use it in GitHub Desktop.
Save SiR-DanieL/cd28c394259456c9c18213ca43f2ab6e to your computer and use it in GitHub Desktop.
Streamline Your WooCommerce Store with Automatic EU VAT Validation
<?php
add_action( 'woocommerce_checkout_process', 'automatic_validation_eu_vat' );
function automatic_validation_eu_vat() {
$vat = str_replace( array( ' ', '.', '-', ',', ',' ), '', wc_clean( $_POST['billing_vat'] ) );
if ( ! empty( $vat ) ) {
$response = wp_remote_get( "http://ec.europa.eu/taxation_customs/vies/vatResponse.html?ms=" . substr( $vat, 0, 2 ) . "&iso=" . substr( $vat, 2 ) );
if ( is_wp_error( $response ) ) {
wc_add_notice( 'There was a problem connecting to the VAT validation service. Please try again later.', 'error' );
} else {
// Retrieve the body and parse the JSON response
$body = wp_remote_retrieve_body( $response );
$result = json_decode( $body, true );
// Check if the VAT number is valid
if ( $result['isValid'] !== true ) {
wc_add_notice( 'Please enter a valid VAT number.', 'error' );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment