从php到javascript的增值税验证

从php到javascript的增值税验证,javascript,php,function,soap,Javascript,Php,Function,Soap,我在这里有一个有趣的函数 这对于检查欧盟的增值税编号非常有效。但是我不能和我的登记表合并。我想在js函数中转换它,在发送注册数据之前使用它,我正在尝试,但我做不到,同一个可以帮助我吗 代码在这个链接中 function viesCheckVAT($countryCode, $vatNumber, $timeout = 30) { $response = array (); $pattern = '/<(%s).*?>([\s\S]*)<\/\1/'; $

我在这里有一个有趣的函数 这对于检查欧盟的增值税编号非常有效。但是我不能和我的登记表合并。我想在js函数中转换它,在发送注册数据之前使用它,我正在尝试,但我做不到,同一个可以帮助我吗

代码在这个链接中

function viesCheckVAT($countryCode, $vatNumber, $timeout = 30) {
    $response = array ();
    $pattern = '/<(%s).*?>([\s\S]*)<\/\1/';
    $keys = array (
        'countryCode',
        'vatNumber',
        'requestDate',
        'valid',
        'name',
        'address'
       );

    $content = "<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>%s</tns1:countryCode>
         <tns1:vatNumber>%s</tns1:vatNumber>
         </tns1:checkVat>
        </s11:Body>
      </s11:Envelope>";

    $opts = array (
        'http' => array (
        'method' => 'POST',
        'header' => "Content-Type: text/xml; charset=utf-8; SOAPAction: checkVatService",
        'content' => sprintf ( $content, $countryCode, $vatNumber ),
        'timeout' => $timeout
        )
       );

    $ctx = stream_context_create ( $opts );
    $result = file_get_contents ( 'http://ec.europa.eu/taxation_customs/vies/services/checkVatService', false, $ctx );

    if (preg_match ( sprintf ( $pattern, 'checkVatResponse' ), $result, $matches )) {
      foreach ( $keys as $key )
      preg_match ( sprintf ( $pattern, $key ), $matches [2], $value ) && $response [$key] = $value [2];
    }
   return $response;
  }

   $arr = viesCheckVAT($countryCode, $vatNumber);

   if ($arr[valid] == fasle) {
    ...
    } else {
    ...
    }
函数viesCheckVAT($countryCode,$vatNumber,$timeout=30){
$response=array();

$pattern='/([\s\s]*)在提到可能应该将上面的代码保持为PHP,并通过Ajax调用它之后,我很快将下面的内容放在一起,展示如何实现这一点。PHP代码基于上述函数,但修改为使用curl

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['task'] ) && $_POST['task']=='check' ){
        ob_clean();

        $result=null;

        function curl( $url=NULL, $options=NULL, $headers=false ){
            /* Initialise curl request object */
            $curl=curl_init();

            /* Define standard options */
            curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
            curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
            curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
            curl_setopt( $curl, CURLOPT_FAILONERROR, true );
            curl_setopt( $curl, CURLOPT_HEADER, false );
            curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
            curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
            curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
            curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
            curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
            curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
            curl_setopt( $curl, CURLOPT_ENCODING, '' );

            /* Assign runtime parameters as options */
            if( isset( $options ) && is_array( $options ) ){
                foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
            }

            if( $headers && is_array( $headers ) ){
                curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
            }

            /* Execute the request and store responses */
            $res=(object)array(
                'response'  =>  curl_exec( $curl ),
                'info'      =>  (object)curl_getinfo( $curl ),
                'errors'    =>  curl_error( $curl )
            );
            curl_close( $curl );
            return $res;
        }






        function checkvat( $code, $vatnumber, $timeout=30 ){
            $url='http://ec.europa.eu/taxation_customs/vies/services/checkVatService';

            $content = "<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>%s</tns1:countryCode>
                        <tns1:vatNumber>%s</tns1:vatNumber>
                    </tns1:checkVat>
                </s11:Body>
            </s11:Envelope>";

            $headers=array(
                'Content-Type'  =>  'text/xml; charset=utf-8',
                'SOAPAction'    =>  'checkVatService'
            );
            $options=array(
                CURLOPT_POST        =>  true,
                CURLOPT_POSTFIELDS  =>  sprintf ( $content, $code, $vatnumber )
            );
            return curl( $url, $options, $headers );
        }








        $code=$_POST['code'];
        $vatnumber=$_POST['vat'];

        /* check the VAT number etc */
        $obj=checkvat( $code, $vatnumber );

        /* if we received a valid response, process it */
        if( $obj->info->http_code==200 ){

            $dom=new DOMDocument;
            $dom->loadXML( $obj->response );

            $reqdate=$dom->getElementsByTagName('requestDate')->item(0)->nodeValue;
            $valid=$dom->getElementsByTagName('valid')->item(0)->nodeValue;
            $address=$dom->getElementsByTagName('address')->item(0)->nodeValue;

            $result=sprintf( 'VAT Number "%s" in Country-Code "%s" - Date: %s, Valid: %s, Address: %s', $vatnumber, $code, $reqdate, $valid, $address ); 
        }

        exit( $result );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>VAT checker</title>
        <script>

            const ajax=function( url, params, callback ){
                let xhr=new XMLHttpRequest();
                xhr.onload=function(){
                    if( this.status==200 && this.readyState==4 )callback( this.response )
                };
                xhr.open( 'POST', url, true );
                xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                xhr.send( buildparams( params ) );
            };

            const buildparams=function(p){/* construct payload/querystring from object */
                if( p && typeof( p )==='object' ){
                    p=Object.keys( p ).map(function( k ){
                        return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
                    }).join('&');
                }
                return p;
            };




            document.addEventListener('DOMContentLoaded', ()=>{
                let form=document.forms.registration;
                    form.bttn.addEventListener('click', e=>{
                        let url=location.href;
                        let params={
                            'task':'check',
                            'vat':form.vat.value,
                            'code':form.code.value
                        };
                        let callback=function(r){
                            document.querySelector('pre').innerHTML=r
                        }
                        ajax.call( this, url, params, callback );
                    })
            });
        </script>
    </head>
    <body>
        <form method='post' name='registration'>
            <!-- lots of other form elements -->


            <!--
                The details in the form (vat-number) is bogus
                and will not return live data...
            -->
            <label for='vat'><input type='text' name='vat' value='10758820' /></label>
            <label for='code'><input type='text' name='code' value='GB' /></label>
            <input type='button' value='Check VAT' name='bttn' />


        </form>
        <pre></pre>
    </body>
</html>
“text/xml;charset=utf-8”,
“SOAPAction”=>“checkVatService”
);
$options=array(
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>sprintf($content、$code、$vatnumber)
);
返回curl($url、$options、$headers);
}
$code=$_POST['code'];
$vatnumber=$_POST['vat'];
/*检查增值税号码等*/
$obj=支票增值税($code,$VATNAMER);
/*如果我们收到了有效的回复,请进行处理*/
如果($obj->info->http\U代码==200){
$dom=新的DOMDocument;
$dom->loadXML($obj->response);
$reqdate=$dom->getElementsByTagName('requestDate')->项(0)->节点值;
$valid=$dom->getElementsByTagName('valid')->item(0)->nodeValue;
$address=$dom->getElementsByTagName('address')->item(0)->nodeValue;
$result=sprintf(国家代码“%s”中的“增值税编号“%s”-日期:%s,有效日期:%s,地址:%s',$VATNAMER,$Code,$reqdate,$Valid,$Address);
}
退出(结果);
}
?>
增值税检查器
const ajax=函数(url、参数、回调){
设xhr=newXMLHttpRequest();
xhr.onload=函数(){
if(this.status==200&&this.readyState==4)回调(this.response)
};
xhr.open('POST',url,true);
setRequestHeader('Content Type','application/x-www-form-urlencoded');
发送(buildparams(params));
};
const buildparams=函数(p){/*从对象构造有效负载/查询字符串*/
if(p&&typeof(p)=='object'){
p=Object.keys(p).map(函数(k){
返回typeof(p[k])='object'?buildparams(p[k]):[encodeURIComponent(k),encodeURIComponent(p[k])。join('='))
}).加入(“&”);
}
返回p;
};
document.addEventListener('DOMContentLoaded',()=>{
让表单=document.forms.registration;
form.bttn.addEventListener('click',e=>{
让url=location.href;
让params={
“任务”:“检查”,
“vat”:form.vat.value,
“代码”:form.code.value
};
让回调函数=函数(r){
document.querySelector('pre').innerHTML=r
}
call(this、url、params、callback);
})
});

与其将上述内容转换为javascript(这需要大量工作),不如建议您将其作为PHP保存,并在发送表单之前通过ajax/fetch从注册表单中调用它?根据我的经验,这种验证服务通常不起作用。不要让表单提交依赖于它。我总是事后检查。不,这是自主权。你必须使用它,但不要依赖它总是能工作。事实并非如此。我在谷歌上搜索到了一个JS版本:。好吧,好吧,我只是在谷歌上搜索了一下,它看起来不错。我会按照RamRaider说的做:不用麻烦将其转换为JS,如果您真的需要在JS中使用AJAX。对VAT验证PHP脚本执行AJAX调用的最简单方法是使用JQuery。请参阅:。有些人坚持在没有JQuery的情况下使用它,这是绝对可能的:哇。好啊我刚刚试着在一个页面中使用它,而且效果很好!非常感谢。现在我尝试在我的网站上使用,看看我是否可以在注册前检查增值税。但是谢谢你!!没有问题-尽管正如@KikoSoftware所指出的,如果它容易失败(?我不知道),那么依赖增值税检查结果的任何代码都需要仔细考虑。好心的luckI试着用一些来自不同国家的真正的增值税,现在起作用了。我不知道是连接问题还是数据库问题。但我的随机测试呈阳性。你能给我一个提示吗?代替使用单击功能,在填写我可以使用的字段时检查vat。类型改变?好的,我试着很好地使用keyupwork!!我只需使用
keyup
+在
callback=function
中添加更多的js,我就可以做任何事情!非常感谢!!