Last active
November 7, 2023 08:18
-
-
Save SirDarcanos/cd28c394259456c9c18213ca43f2ab6e to your computer and use it in GitHub Desktop.
Streamline Your WooCommerce Store with Automatic EU VAT Validation
This file contains hidden or 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 | |
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