SII Model: Send data to the Web Service using vba

10

I try to connect to the Web Service of the AEAT (SII) to send XML files. I have a tremendous amount of research and testing, but I am very close to abandonment, or postpone it until there is more information on the net.

For sending, I am trying to use the SERVERXMLHTTP library This would be the code:

Dim oWS As MSXML2.ServerXMLHTTP
Set oWS = New MSXML2.ServerXMLHTTP 
Dim xmlResponse As MSXML2.DOMDocument

'Abrimos conexión'
oWS.Open "POST", strURL, False
oWS.setRequestHeader "Content-Type", "text/xml"

'Autentificación'       
oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT,

'Envío'
Call oWS.send(strXml)

Note that strURL is a correct and verified path, and strXML is a correct XML

The answer I can see is: (I add a reply to the complete TEXT at the end of the query)

oWS.Status      'Respuesta = 200 (OK)'
oWS.ResponseXML 'Esta respuesta está vacía'
oWS.ResponseText 'Aquí hay un html que vendría a ser un formulario en el que me piden que entre la Cl@ve Pin'.

In summary, what I think is missing is the digital certificate. Maybe I do not know how to call the certificate, but I've tried a thousand ways and I can not find out how I could use it:

Option 1: As I could read, if we do not specify the certificate, the first one is selected (in my case I only have a certificate installed thoroughly, but I can understand that I'm taking something else

oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, ""

Option 2: Many people talked about searching for the registry in the style: MY \ This information is very abstract for me. I got to see that the certificates are in the registry in these routes:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates\
'Y allí dentro hay un directorio con muchos números y letras:'
HKEY_LOCAL_MACHINE\...\Certificates\A1234C5678950E8F4295EA63D9515E3689B8EBC1
'Y dentro de ella hay una clave llamaada <Blob>'

Knowing this, I tried several approaches:

oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, "LOCAL_MACHINE\MY\A1234C5678950E8F4295EA63D9515E3689B8EBC1"
oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, "LOCAL_MACHINE\MY\Certificates\A1234C5678950E8F4295EA63D9515E3689B8EBC1"
oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, "LOCAL_MACHINE\MY\Certificates\A1234C5678950E8F4295EA63D9515E3689B8EBC1\Blob"

Option 3: I could also read that the CN name of the certificate should be specified sxh.setOption (3)="Common Name (CN) part of certificate's Subject name"

'Nombre completo que pude encontrar en CN:'
oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, "PEPITO GRILLO - 39301234P"
'Parte del nombre que pude encontrar en CN:'
oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, "39301234P"
'Nombre completo CN, pero añadiendo la ruta'
oWS.SetOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, "LOCAL_MACHINE\MY\PEPITO GRILLO - 39301234P"

Finally ... a thousand ways to try to locate and use the certificate. But none worked for me. The answer is always the same.

Maybe I'm wrong about something?

The certificate could locate it in several ways

> MMC.exe
 > Archivo > Agregar o quitar complementos...
  > Certificados (Equipo local)

> FIREFOX
 > Opciones > Avanzado... > Certificados > Ver Certificados...
  > Sus Certificados:
   > FNMT-RCM
    > PEPITO GRILLO - 39301234P

In both cases we can locate the certificates. And once located, if we double click on the certificate, all the information appears, such as the CN that I tried to use in option 3, or the sequence of numbers and letters that I found in the registry (the value of the fingerprint SHA1 is what was in the Windows registry)

Leaving a bit of vba, I have a final note:

Because I could not make it work, I tried to use CURL.EXE. I will not go into detail for now on how I sent the data, but if the answer I got was the same (answer that refers to a form where you have to enter the Cl @ ve Pin "

In summary, something I do not do well because it does not capture my certificates, but I do not know how to solve it.

APPENDIX 1: I add TEXT response that returns the attempt to send to the AEAT:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml" xml:lang="es">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-15" />
<title>Autenticaci&oacute;n - Cl@ve PIN</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<link href="/static_files/common/css/xzhtcs04.css" rel="stylesheet" type="text/css"/>
<link href="/static_files/common/internet/dep/aplicaciones/ov/css/p24idecs.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="/static_files/common/internet/dep/aplicaciones/ov/script/aeatrsc0.js"></script>
<script type="text/javascript" src="/static_files/common/internet/dep/aplicaciones/ov/script/p24a01cd.js"></script>
<script src="/static_files/common/internet/script/clave_pin.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
jQuery.noConflict();
var ref = "/wlpl/SII-FACT/ws/fe/SiiFactFEV1SOAP";
var from = '';
var bfprint = '&amp;BFPRINT;';
var storksp = '';
var qaa = '';
var msg = '';
//]]>
</script>
</head>
<body onload="init();" onfocus="focoEnPagina();">
        <!-- p24Aut01.html -->
        <div id="AEAT_header"></div>
        <div id="p24h-pane" class="AEAT_contenedor">
        <div id="p24h-title" class="AEAT_contenedor">
            <h2>Autenticaci&oacute;n</h2>
        </div>
        <div id="qaa-2" style="display:none;text-align: right;font-size: xx-small;">Nivel b&aacute;sico</div>
        <div id="qaa-3" style="display:none;text-align: right;font-size: xx-small;">Nivel sustancial</div>
        <!-- div class="AEAT_bloque_avisos p24h-avisos">
            <h2>Avisos:</h2>
            <p>Para el correcto funcionamiento del servicio Cl@ve PIN es necesario que su navegador permita la utilizaci&oacute;n
                de cookies y la ejecuci&oacute;n de javascript</p>
        </div-->
        <div id="errores" class="AEAT_bloque_errores p24h-errores" style="display: none"></div>
        <div id="avisos" class="AEAT_bloque_avisos p24h-avisos" style="display: none"></div>
        <div id="p24h-form" class="AEAT_contenedor">    
            <form id="iden-form" name="iden-form" action="/es12/l/es02genp24h1" method="post" class="AEAT_form" autocomplete="off">
                    El asterisco <span class="obligatorio"> * </span> indica que es imprescindible completar este dato<br/><br/>

                    <table id="p24h-campos" class="ancho_100">
                        <tr id="campo-nif"><td class="ancho_25" style="text-align: right">
                            <label for="nif">
                                    <span class="obligatorio">* </span><acronym title="Documento Nacional de Identidad">DNI</acronym>/<acronym title="N&uacute;mero de Identificaci&oacute;n de Extranjero">NIE</acronym>
                            </label></td>
                            <td>&nbsp;&nbsp;
                            <input type="text" id="nif" name="NIF" size="9em" maxlength="9" placeholder="DNI/NIE" style="width: 11ex" value="" onblur="chequearNIF();$('msg-nif').hide();" onfocus="activarMsg('msg-nif');"/>
                            <span id="msg-nif" style="display: none">&laquo; Introduzca el <acronym title="Documento Nacional de Identidad">DNI</acronym>/<acronym title="N&uacute;mero de Identificaci&oacute;n de Extranjero">NIE</acronym></span>
                        </td></tr>
                        <tr id="campo-ape" style="display: none"><td class="ancho_25" style="text-align: right">
                            <span class="obligatorio">* </span>&nbsp;<label for="ape">Primer apellido</label>
                        </td><td>&nbsp;&nbsp;
                            <input type="text" id="ape" name="APE" size="20em" maxlength="20" placeholder="Primer Apellido" style="width: 22ex" value="" onfocus="activarMsg('msg-ape');" onblur="$('msg-ape').hide();"/>
                            <span id="msg-ape" style="display: none">&laquo; Introduzca su primer apellido</span>
                        </td></tr>                      
                        <tr id="campo-clv">
                            <td class="ancho_25" style="text-align: right">
                                <label for="clv"><span class="obligatorio">* </span>C&oacute;digo</label>
                            </td>
                            <td>&nbsp;&nbsp;
                                <input type="text" id="clv" name="CLV" size="4em" maxlength="4" value="" placeholder="Clave" style="width: 5ex" onfocus="$('clv').select();activarMsg('msg-clv');" onblur="$('msg-clv').hide();"/>
                                <span id="msg-clv" style="display: none">&laquo; Introduzca el c&oacute;digo elegido en el proceso de obtenci&oacute;n</span>
                            </td>
                        </tr>
                        <tr id="campo-pin">
                            <td class="ancho_25" style="text-align: right">
                                <label for="pin"><span class="obligatorio">* </span><acronym title="N&uacute;mero Personal de Identificaci&oacute;n">PIN</acronym></label>
                            </td>
                            <td>&nbsp;&nbsp;
                                <input type="password" id="pin" name="PIN" size="3em" maxlength="3" value="" placeholder="PIN" style="width: 5ex" onfocus="$('pin').select();activarMsg('msg-pin');" onblur="$('msg-pin').hide();"/>
                                <span id="msg-pin" style="display: none">&laquo;  Introduzca el <acronym title="N&uacute;mero Personal de Identificaci&oacute;n">PIN</acronym> que ha recibido en su tel&eacute;fono m&oacute;vil. Estar&aacute; compuesto por letras (excluida la eñe) y/o d&iacute;gitos (excluidos el cero, uno, ocho y nueve).</span>
                                <!--span id="msg-pin" style="display: none">&laquo; Introduzca el <acronym title="N&uacute;mero Personal de Identificaci&oacute;n">PIN</acronym> que ha recibido en el <acronym title="Servicio de Mensajer&iacute;a Corta">SMS</acronym></span-->
                            </td>
                        </tr>
                    <!-- Opcional. Número de teléfono -->
                        <tr id="campo-tmv" style="display: none"><td class="ancho_25" style="text-align: right">
                            <label for="tmv"><span class="obligatorio">* </span>Tel&eacute;fono m&oacute;vil</label>
                        </td><td>&nbsp;&nbsp;
                            <input id="tmv" name="TMV" size="15em" maxlength="15" placeholder="tel&eacute;fono m&oacute;vil" style="width: 17ex" value="" onfocus="activarMsg('msg-tmv');" onblur="$('msg-tmv').hide()"/>
                            <span id="msg-tmv" style="display: none">&laquo; Introduzca el n&uacute;mero de tel&eacute;fono con el que di&oacute; de alta el servicio <acronym title="Servicio de autenticaci&oacute;n por PIN de 24 horas">PIN</acronym></span>
                        </td></tr>
                    </table>
            <div id="botones" class="AEAT_bloque_botones p24-botones">
                    <input type="button" id="boton-acceder"   class="AEAT_boton" value="Acceder" onclick="acceder('es');"/>
                    <input type="button" id="boton-solicitar" class="AEAT_boton" value="No tengo PIN" onclick="solicitudDePin('es');"/>
                    <input type="button" id="boton-acceso-registro" class="AEAT_boton" value="No estoy registrado" onclick="accederRegistroClave('es');"/>
            </div>
            <!-- ATENCIÓN: El orden es significativo -->
            <input type="hidden" id="ref" name="REF" value="/wlpl/SII-FACT/ws/fe/SiiFactFEV1SOAP"/><!-- referrer que me pasa la infraestructura del CWS -->
            <input type="hidden" id="from" name="FROM" value=""/><!-- origen de la petición actual, para stork -->
            <input type="hidden" id="bfprint" name="BFPRINT" value="&amp;BFPRINT;"/><!-- firgerprint del usuario -->
            <input type="hidden" id="storksp" name="STORKSP" value="&amp;STROKSP;"/><!-- origen de la petición actual, para stork -->
            <input type="hidden" id="qaa" name="QAA" value=""/><!-- qaa solicitado desde el SP (Proveedor de servicios) -->
            <input type="hidden" id="msg" value=""/><!-- mensage que me pasa la infraestructura del CWS --> 
            <input type="hidden" id="idi" value="es"/><!-- idioma en el que se encuentra la página -->
            </form>
        </div>
        </div>
        <div id="p24h-registro-clave" title="Registro en Cl@ve" style="display:none">
            <p>La Administración Estatal ha implantando el sistema <strong class="azul">Cl@ve</strong>, que permite el acceso sencillo a los
            servicios electrónicos de diferentes administraciones públicas.</p>
            <p>Si quiere beneficiarse de esta plataforma, s&oacute;lo ser&aacute; necesario que se d&eacute; de alta en un
            registro &uacute;nico. Una vez registrado en <strong class="azul"> Cl@ve </strong> podr&aacute; utilizar algunos de los sistemas de
            identificaci&oacute;n y autenticaci&oacute;n que forman parte de la plataforma, para acceder a los
            diferentes servicios de administraci&oacute;n electr&oacute;nica que se han integrado en la plataforma,
            y sin necesidad de contar con diferentes altas en cada servicio.</p>
            <p>Los sistemas que permiten la identificaci&oacute;n  al acceder a los servicios electr&oacute;nicos
            son el sistema Cl@ve PIN y el sistema Cl@ve Permanente. Para m&aacute;s informaci&oacute;n sobre las
            caracter&iacute;sticas de estos sistemas, visite <a href="http://clave.gob.es/">
            clave.gob.es</a>.</p>
            <p>Los sistemas que forman parte de <strong class="azul">Cl@ve</strong> permiten cubrir las diferentes necesidades y
            circunstancias de los ciudadanos que necesitan realizar tr&aacute;mites administrativos y de
            los &oacute;rganos u organismos que los ofrecen a trav&eacute;s de sus Sedes Electr&oacute;nicas.</p>
            <p>A partir del 1 de enero de 2016, el sistema PIN24H desaparece para integrarse definitivamente
            en Cl@ve PIN. Como usuario registrado del sistema PIN24H, puede incorporar sus datos
            a la nueva plataforma <strong class="azul">Cl@ve</strong> de forma sencilla. Si usted desea beneficiarse de las ventajas
            que ofrece esta nueva plataforma, por favor haga clic en <em>registrarse en Cl@ve</em> y le guiaremos en el proceso.</p>
        </div>
        <div id="p24h-aviso-tdp" title="Importante:" style="display: none">
            <p>Se ha detectado que el n&uacute;mero de tel&eacute;fono m&oacute;vil que constaba asociado al
            <acronym title="Documento Nacional de Identidad">DNI</acronym>/<acronym title="N&uacute;mero de Identificaci&oacute;n de Extranjero">NIE</acronym>
            indicado se encuentra actualmente asignado a otro usuario del sistema <strong class="azul"> Cl@ve </strong>.</p>
            <p>Por su seguridad, para poder recibir el <acronym title="N&uacute;mero Personal de Identificaci&oacute;n">
            PIN</acronym> v&iacute;a <acronym title="Servicio de Mensajer&iacute;a Corta">SMS</acronym> y continuar con el tr&aacute;mite es
            necesario que actualice su n&uacute;mero de tel&eacute;fono.</p>
            <p>Esta actualizaci&oacute;n se puede realizar presencialmente en una Oficina de Registro de usuarios de la plataforma
            <strong class="Azul"> Cl@ve </strong> o de forma telem&aacute;tica con certificado o <acronym title="Documento Nacional de Identidad">DNI</acronym>
            electr&oacute;nico en la Sede Electr&oacute;nica de la Agencia Estatal de Administraci&oacute;n Tributaria. La relaci&oacute;n de
            Oficinas de Registro se encuentra publicada en el Portal <a href="http://administracion.gob.es">Punto de Acceso General</a>.</p>

        </div>
        <div id="p24h-error-bfp" title="Atenci&oacute;n" style="display:none">
            <p>Se ha detectado una modificaci&oacute;n en las caracter&iacute;sticas del dispositivo desde el que est&aacute; intentando
            acceder al sistema <strong class="azul"> Cl@ve </strong> <acronym title="N&uacute;mero Personal de Identificaci&oacute;n">PIN</acronym>.</p>
            <p>Por su seguridad, para continuar con el tr&aacute;mite es necesario que obtenga un nuevo
            <acronym title="N&uacute;mero Personal de Identificaci&oacute;n">PIN</acronym>.</p>
        </div>
        <div id="p24h-fuera-de-servicio" title="Aplicaci&oacute;n fuera de servicio" style="display:none">
            <p id="msg-fuera-servicio"></p>
        </div>
        <!-- para ponerlos disponibles en la página que llama a registro previos -->
        <div id="p24h-datos" style="display: none">
            <input type="hidden" id="extrainfo" value=""/>
        </div>      
</body>
<script type="text/javascript">
    //<![CDATA[
    /*
    * Si el parámetro entorno es "", activarFueraDeServicio no hace nada.
    */
    //activarFueraDeServicio({entorno: "PRO",dia: "2016-11-16",desde: "14.30.00"});
    /* Prioridad en el tratamiento de los lenguajes
     * 1.- valor de la cookie aeat-language
     * 2.- variable id en la queryString
     * 3.- valor de la cabecera accept-language
     */
    var qs = location.search.toQueryParams();
    if ($('idi').value == 'es') {
        /* solo se realiza la redirección desde la página en español */
        var aeatLanguage = AEAT.getCookie("aeat-language");
        var acceptLanguage = window.navigator.userLanguage || window.navigator.language;
        var idi = qs.idi;

        var qstr = "?ref=" + encodeURIComponent(unescape($('ref').value.stripTags())) + "&msg=" + $('msg').value ;
        var h = $H(qs);
        h.each(function(pair){  
            if (pair.key != 'ref') {
                qstr = qstr + "&" + pair.key + "=" + pair.value;
            }
        });
        var value = "";
        if (aeatLanguage != null && aeatLanguage != undefined) {
            value = aeatLanguage;
        } else if (idi != null && idi != undefined) {
            value = idi;
        } else if (acceptLanguage != null && acceptLanguage != undefined){
            value = acceptLanguage;
        }

        switch (value.substring(0,2)) {
            case "ca":
            case "CA":
            case "ca_ES" : location.href="/es13/h/p24autc1.html"+qstr;break;
            case "gl":
            case "GL":
            case "gl_ES" : location.href="/es13/h/p24autg1.html"+qstr;break;
            case "va":
            case "VA":
            case "va_ES" : location.href="/es13/h/p24autv1.html"+qstr;break;
            default: break;
        }
    }

    /* para el resto de los los idiomas (no español) */
    $('ref').value = (qs.ref != undefined) ? decodeURIComponent(unescape(qs.ref.stripTags())) : "/wlpl/SII-FACT/ws/fe/SiiFactFEV1SOAP";
    $('msg').value = (qs.msg != undefined) ? qs.msg : "";
    $('from').value = (qs.from != undefined) ? qs.from : "";
    $('storksp').value = (qs.storksp != undefined) ? qs.storksp: "";
    $('qaa').value = (qs.qaa != undefined) ? qs.qaa : "";

    var bfp = new Fingerprint().get({screen_resolution: true, ie_activex: true});
    $('bfprint').value = AEAT.rjust(""+bfp,10,'0');
    //]]>
</script>
<noscript>
<!-- código para mostrar mensaje de javascript y/o cookies desactivadas -->
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-avisoCookiesDesactivadas" style="display: block; z-index: 1002; outline: 0px; height: auto; width: 500px; top: 361.5px; left: 37%;">
    <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
        <span class="ui-dialog-title" id="ui-dialog-title-avisoCookiesDesactivadas">Aviso</span>
        <a href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button"><span class="ui-icon ui-icon-closethick">close</span></a>
    </div>
    <div id="avisoCookiesDesactivadas" class="ui-dialog-content ui-widget-content" scrolltop="0" scrollleft="0" style="width: auto; min-height: 30.8px; height: auto;">
        <div class="AEAT_bloque_errores">
            <p>Para el correcto funcionamiento de la Sede Electr&oacute;nica es necesario que su navegador permita la utilizaci&oacute;n de cookies y de javascript.</p>
            <p>Si no sabe como hacerlo puede consultarlo en el siguiente enlace: </p>
            <p>
                <a class="enlace_no_decorado negrita" href="http://www.agenciatributaria.es/AEAT.internet/Ayuda/config_Sede.shtml" target="blank">
                Requisitos t&eacute;cnicos para realizar tr&aacute;mites en la Sede Electr&oacute;nica
                </a>
            </p>
            <p>Para mas informaci&oacute;n sobre las cookies visite la <a class="enlace_no_decorado negrita"
                href="https://www.agenciatributaria.gob.es/AEAT.sede/Inicio/_pie_/_Aviso_Legal_/_Aviso_Legal_.shtml" target="blank">
                pol&iacute;tica de privacidad</a>.
            </p>
            <br/>
        </div>
    </div>
</div>
<div class="ui-widget-overlay" style="height: 955px; z-index: 1001;"></div>
</noscript>
</html>
    
asked by BeniGls 20.07.2017 в 13:09
source

2 answers

1

I found the following code in link

And I made some small changes, specifically define some variables that need to be defined and place a certificate name that I have installed on the machine.

Dim strURLEndpoint
Dim strContentType
Dim strSOAPAction
Dim strCertificaatNaam
Dim objRequestXML

objRequestXML="aqui va el xml"

strURLEndpoint="https://www7.aeat.es/wlpl/SSII-FACT/ws/fe/SiiFactFEV1SOAP"
strSOAPAction="test"

'Msxml2.ServerXMLHTTP setOption variables
Const SXH_OPTION_URL                                   = -1
Const SXH_OPTION_URL_CODEPAGE                        = 0
Const SXH_OPTION_ESCAPE_PERCENT_IN_URL                = 1
Const SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = 2

Const SXH_SERVER_CERT_IGNORE_UNKNOWN_CA         =    256        'Unknown certificate authority
Const SXH_SERVER_CERT_IGNORE_WRONG_USAGE        =    512        'Malformed certificate such as a certificate with no subject name
Const SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID    =    4096    'Mismatch between the visited hostname and the certificate name being used on the server
Const SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID    =    8192    'The date in the certificate is invalid or has expired.\
Const SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS    =    13056    'All certificate errors

Const SXH_OPTION_SELECT_CLIENT_SSL_CERT                = 3

Set objWinHttp = CreateObject("Msxml2.ServerXMLHTTP")
strContentType ="text/XML;charset=UTF-8" 'Web Service Content Type

'Open HTTP connection
objWinHttp.Open "POST", strURLEndpoint, False

'Setting Request Headers
objWinHttp.setRequestHeader "Content-Type", strContentType
objWinHttp.setRequestHeader "SOAPAction", strSOAPAction

'    objWinHttp.setOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS
objWinHttp.setOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID

'Setting the clientcertificate (Optional)
strCertificaatNaam="ALEXANDRU CATALIN TRANDAFIR - X4378072E"
If UCase(strCertificaatNaam) <> "" AND  UCase(strCertificaatNaam) <> "[SKIP]" Then
    objWinHttp.setOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, strCertificaatNaam
End If

'Send SOAP request
objWinHttp.Send objRequestXML

msgbox objWinHttp.ResponseText

They use many parameterization options but the ones that matter I think they are:

Const SXH_OPTION_SELECT_CLIENT_SSL_CERT                = 3

And also:

'Setting the clientcertificate (Optional)
strCertificaatNaam="ALEXANDRU CATALIN TRANDAFIR - X4378072E"
If UCase(strCertificaatNaam) <> "" AND  UCase(strCertificaatNaam) <> "[SKIP]" Then
    objWinHttp.setOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, strCertificaatNaam
End If

In this case you can see that I have indicated ALEXANDRU CATALIN TRANDAFIR - X4378072E as the certificate name, and that in Mozilla Firefox I have installed a certificate with that name.

Screenshot 1:

And screenshot with an answer:

Well, in the answer you can see that the request was successful, that is, you could use the certificate and now you complain that the XML is not valid.

It is not my preferred environment so if you are familiar with PHP and with that language it would be useful for your application, I recommend this implementation technical ebook of the SII where there are examples in php of the entire communication circuit.

UPDATE: Complete communication with the SII, with call and XML response

After having carried out the certificate test, I modified the code in order to properly communicate some test invoices and here I put all the files:

The test.vbs script:

Dim strURLEndpoint
Dim strContentType
Dim strSOAPAction
Dim strCertificaatNaam
Dim objRequestXML

Dim fso

Set fso = CreateObject("Scripting.FileSystemObject")

Set file = fso.OpenTextFile("datos_xml.txt", 1)
objRequestXML = file.ReadAll

msgbox objRequestXML

strURLEndpoint="https://www7.aeat.es/wlpl/SSII-FACT/ws/fe/SiiFactFEV1SOAP"
strSOAPAction="SuministroLRFacturasEmitidas"

'Msxml2.ServerXMLHTTP setOption variables
Const SXH_OPTION_URL                                   = -1
Const SXH_OPTION_URL_CODEPAGE                        = 0
Const SXH_OPTION_ESCAPE_PERCENT_IN_URL                = 1
Const SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = 2

Const SXH_SERVER_CERT_IGNORE_UNKNOWN_CA         =    256        'Unknown certificate authority
Const SXH_SERVER_CERT_IGNORE_WRONG_USAGE        =    512        'Malformed certificate such as a certificate with no subject name
Const SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID    =    4096    'Mismatch between the visited hostname and the certificate name being used on the server
Const SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID    =    8192    'The date in the certificate is invalid or has expired.\
Const SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS    =    13056    'All certificate errors

Const SXH_OPTION_SELECT_CLIENT_SSL_CERT                = 3

Set objWinHttp = CreateObject("Msxml2.ServerXMLHTTP")
strContentType ="text/XML;charset=UTF-8" 'Web Service Content Type

'Open HTTP connection
objWinHttp.Open "POST", strURLEndpoint, False

'Setting Request Headers
objWinHttp.setRequestHeader "Content-Type", strContentType
objWinHttp.setRequestHeader "SOAPAction", strSOAPAction

'    objWinHttp.setOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS
objWinHttp.setOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID

'Setting the clientcertificate (Optional)
strCertificaatNaam="ALEXANDRU CATALIN TRANDAFIR - X4378072E"
If UCase(strCertificaatNaam) <> "" AND  UCase(strCertificaatNaam) <> "[SKIP]" Then
    objWinHttp.setOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, strCertificaatNaam
End If

'Send SOAP request
objWinHttp.Send objRequestXML

msgbox objWinHttp.ResponseText

Set objFile = fso.CreateTextFile("respuesta.txt",True)
objFile.Write objWinHttp.ResponseText & vbCrLf
objFile.Close

The file with the call data, datos_xml.txt :

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/ssii/fact/ws/SuministroInformacion.xsd" xmlns:ns2="https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/ssii/fact/ws/SuministroLR.xsd">
  <SOAP-ENV:Body>
    <ns2:SuministroLRFacturasEmitidas>
      <ns1:Cabecera>
        <ns1:IDVersionSii>1.0</ns1:IDVersionSii>
        <ns1:Titular>
          <ns1:NombreRazon>ALEXANDRU CATALIN TRANDAFIR</ns1:NombreRazon>
          <ns1:NIF>X4378072E</ns1:NIF>
        </ns1:Titular>
        <ns1:TipoComunicacion>A0</ns1:TipoComunicacion>
      </ns1:Cabecera>
      <ns2:RegistroLRFacturasEmitidas>
        <ns1:PeriodoImpositivo>
          <ns1:Ejercicio>2017</ns1:Ejercicio>
          <ns1:Periodo>12</ns1:Periodo>
        </ns1:PeriodoImpositivo>
        <ns2:IDFactura>
          <ns1:IDEmisorFactura>
            <ns1:NIF>X4378072E</ns1:NIF>
          </ns1:IDEmisorFactura>
          <ns1:NumSerieFacturaEmisor>SIIDEMO/1</ns1:NumSerieFacturaEmisor>
          <ns1:FechaExpedicionFacturaEmisor>31-12-2017</ns1:FechaExpedicionFacturaEmisor>
        </ns2:IDFactura>
        <ns2:FacturaExpedida>
          <ns1:TipoFactura>F1</ns1:TipoFactura>
          <ns1:FechaOperacion>31-12-2017</ns1:FechaOperacion>
          <ns1:ClaveRegimenEspecialOTrascendencia>01</ns1:ClaveRegimenEspecialOTrascendencia>
          <ns1:ImporteTotal>1210</ns1:ImporteTotal>
          <ns1:DescripcionOperacion>Compra ordenador portátil</ns1:DescripcionOperacion>
          <ns1:Contraparte>
            <ns1:NombreRazon>HeavyDots SL</ns1:NombreRazon>
            <ns1:NIF>B66544586</ns1:NIF>
          </ns1:Contraparte>
          <ns1:TipoDesglose>
            <ns1:DesgloseFactura>
              <ns1:Sujeta>
                <ns1:NoExenta>
                  <ns1:TipoNoExenta>S1</ns1:TipoNoExenta>
                  <ns1:DesgloseIVA>
                    <ns1:DetalleIVA>
                      <ns1:TipoImpositivo>21</ns1:TipoImpositivo>
                      <ns1:BaseImponible>500</ns1:BaseImponible>
                      <ns1:CuotaRepercutida>105</ns1:CuotaRepercutida>
                    </ns1:DetalleIVA>
                    <ns1:DetalleIVA>
                      <ns1:TipoImpositivo>21</ns1:TipoImpositivo>
                      <ns1:BaseImponible>500</ns1:BaseImponible>
                      <ns1:CuotaRepercutida>105</ns1:CuotaRepercutida>
                    </ns1:DetalleIVA>
                  </ns1:DesgloseIVA>
                </ns1:NoExenta>
              </ns1:Sujeta>
            </ns1:DesgloseFactura>
          </ns1:TipoDesglose>
        </ns2:FacturaExpedida>
      </ns2:RegistroLRFacturasEmitidas>
      <ns2:RegistroLRFacturasEmitidas>
        <ns1:PeriodoImpositivo>
          <ns1:Ejercicio>2017</ns1:Ejercicio>
          <ns1:Periodo>12</ns1:Periodo>
        </ns1:PeriodoImpositivo>
        <ns2:IDFactura>
          <ns1:IDEmisorFactura>
            <ns1:NIF>X4378072E</ns1:NIF>
          </ns1:IDEmisorFactura>
          <ns1:NumSerieFacturaEmisor>SIIDEMO/2</ns1:NumSerieFacturaEmisor>
          <ns1:FechaExpedicionFacturaEmisor>31-12-2017</ns1:FechaExpedicionFacturaEmisor>
        </ns2:IDFactura>
        <ns2:FacturaExpedida>
          <ns1:TipoFactura>F1</ns1:TipoFactura>
          <ns1:FechaOperacion>31-12-2017</ns1:FechaOperacion>
          <ns1:ClaveRegimenEspecialOTrascendencia>01</ns1:ClaveRegimenEspecialOTrascendencia>
          <ns1:ImporteTotal>1210</ns1:ImporteTotal>
          <ns1:DescripcionOperacion>Compra ordenador portátil</ns1:DescripcionOperacion>
          <ns1:Contraparte>
            <ns1:NombreRazon>HeavyDots SL</ns1:NombreRazon>
            <ns1:NIF>B66544586</ns1:NIF>
          </ns1:Contraparte>
          <ns1:TipoDesglose>
            <ns1:DesgloseFactura>
              <ns1:Sujeta>
                <ns1:NoExenta>
                  <ns1:TipoNoExenta>S1</ns1:TipoNoExenta>
                  <ns1:DesgloseIVA>
                    <ns1:DetalleIVA>
                      <ns1:TipoImpositivo>21</ns1:TipoImpositivo>
                      <ns1:BaseImponible>500</ns1:BaseImponible>
                      <ns1:CuotaRepercutida>105</ns1:CuotaRepercutida>
                    </ns1:DetalleIVA>
                    <ns1:DetalleIVA>
                      <ns1:TipoImpositivo>21</ns1:TipoImpositivo>
                      <ns1:BaseImponible>500</ns1:BaseImponible>
                      <ns1:CuotaRepercutida>105</ns1:CuotaRepercutida>
                    </ns1:DetalleIVA>
                  </ns1:DesgloseIVA>
                </ns1:NoExenta>
              </ns1:Sujeta>
            </ns1:DesgloseFactura>
          </ns1:TipoDesglose>
        </ns2:FacturaExpedida>
      </ns2:RegistroLRFacturasEmitidas>
    </ns2:SuministroLRFacturasEmitidas>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The file where the received response was written, respuesta.txt :

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header />
   <env:Body Id="Body">
      <siiR:RespuestaLRFacturasEmitidas xmlns:siiR="https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/ssii/fact/ws/RespuestaSuministro.xsd" xmlns:sii="https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/ssii/fact/ws/SuministroInformacion.xsd">
         <siiR:Cabecera>
            <sii:IDVersionSii>1.0</sii:IDVersionSii>
            <sii:Titular>
               <sii:NombreRazon>ALEXANDRU CATALIN TRANDAFIR</sii:NombreRazon>
               <sii:NIF>X4378072E</sii:NIF>
            </sii:Titular>
            <sii:TipoComunicacion>A0</sii:TipoComunicacion>
         </siiR:Cabecera>
         <siiR:EstadoEnvio>Incorrecto</siiR:EstadoEnvio>
         <siiR:RespuestaLinea>
            <siiR:IDFactura>
               <sii:IDEmisorFactura>
                  <sii:NIF>X4378072E</sii:NIF>
               </sii:IDEmisorFactura>
               <sii:NumSerieFacturaEmisor>SIIDEMO/1</sii:NumSerieFacturaEmisor>
               <sii:FechaExpedicionFacturaEmisor>31-12-2017</sii:FechaExpedicionFacturaEmisor>
            </siiR:IDFactura>
            <siiR:EstadoRegistro>Incorrecto</siiR:EstadoRegistro>
            <siiR:CodigoErrorRegistro>3000</siiR:CodigoErrorRegistro>
            <siiR:DescripcionErrorRegistro>Factura duplicada</siiR:DescripcionErrorRegistro>
            <siiR:CSV>QSAYUMZV8NM3REGD</siiR:CSV>
         </siiR:RespuestaLinea>
         <siiR:RespuestaLinea>
            <siiR:IDFactura>
               <sii:IDEmisorFactura>
                  <sii:NIF>X4378072E</sii:NIF>
               </sii:IDEmisorFactura>
               <sii:NumSerieFacturaEmisor>SIIDEMO/2</sii:NumSerieFacturaEmisor>
               <sii:FechaExpedicionFacturaEmisor>31-12-2017</sii:FechaExpedicionFacturaEmisor>
            </siiR:IDFactura>
            <siiR:EstadoRegistro>Incorrecto</siiR:EstadoRegistro>
            <siiR:CodigoErrorRegistro>3000</siiR:CodigoErrorRegistro>
            <siiR:DescripcionErrorRegistro>Factura duplicada</siiR:DescripcionErrorRegistro>
            <siiR:CSV>QSAYUMZV8NM3REGD</siiR:CSV>
         </siiR:RespuestaLinea>
      </siiR:RespuestaLRFacturasEmitidas>
   </env:Body>
</env:Envelope>
    
answered by 16.01.2018 / 17:25
source
0

I understand that the problem, as they say is in the certificate, in some occasion also gave me problems the MSXML2.ServerXMLHTTP, could you try another one ?. Have you been able to contact someone in AEAT? It is possible that other users have the same consequences. Also recommend using postman or similar application to test the solution without programming from the client computer, to rule out another topic.

have you seen this thread?:

link

Lastly, I recommend you to try asking in Stackoverflow in English, for the little that I have been able to see around here, you are more worried about how you answer than to help the question:)

    
answered by 07.08.2017 в 16:27