Nueva pregunta

Pregunta:

Fecha: 30-07-2019 01:22:50 (En Español)

Llamar a webservice de AFIP en pagina web [Resuelta]

Alguien probo hacer un sitio web, es decir montar un sistema en un hosting para usar webservice AFIP?

Yo utilizo codigo que saque de esta pagina en los temas de facturacion.
Tengo el siguiente codigo, que me funciona perfectamente en local en mi pc:

<?php



include_once ($_SERVER['DOCUMENT_ROOT'].'/gestionn/includes/afip/wsaa-client.php');

define ("URLS", "https://awshomo.afip.gov.ar/sr-padron/webservices/personaServiceA5?WSDL");
$CUIT=$_POST['CUIT'];
$CUITI=(float)$CUIT;

if (isset($_POST['CUIT'])){
    $wsdl_p5="https://awshomo.afip.gov.ar/sr-padron/webservices/personaServiceA5?WSDL";
    $padron = new SoapClient($wsdl_p5, array(
'soap_version' => SOAP_1_1,
'location' => URLS,
'exceptions' => 0,
'trace' => 1)
);
$TA = simplexml_load_file("C:\\xampp\htdocs\gestionn\includes\afip\TA.xml");

 
$resultado = $padron->getPersona(
array(
'token' => $TA->credentials->token,
'sign' => $TA->credentials->sign,
'cuitRepresentada' => 20357161178, // es el cuit con el que pedi el certificao
'idPersona' =>$CUITI,
)
);

echo json_encode($resultado);
}

?>


Y este es el archivo wsaa-client:
<?php

#==============================================================================
define ("WSDL",  dirname(dirname(__FILE__))."/afip/wsaa.wsdl");     # The WSDL corresponding to WSAA
define("CERT", dirname(dirname(__FILE__))."/afip/certificado.crt");  
   # The X.509 certificate in PEM format
define ("PRIVATEKEY", dirname(dirname(__FILE__))."/afip/privada.key"); # The private key correspoding to CERT (PEM)
define ("PASSPHRASE", "caruso12021991"); # The passphrase (if any) to sign
define ("PROXY_HOST", "10.20.152.112"); # Proxy IP, to reach the Internet
define ("PROXY_PORT", "80");            # Proxy TCP port
define ("URL", "https://wsaahomo.afip.gov.ar/ws/services/LoginCms");
#define ("URL", "https://wsaa.afip.gov.ar/ws/services/LoginCms");
#------------------------------------------------------------------------------
# You shouldn't have to change anything below this line!!!
#==============================================================================
function CreateTRA($SERVICE)
{
  $TRA = new SimpleXMLElement(
    '<?xml version="1.0" encoding="UTF-8"?>' .
    '<loginTicketRequest version="1.0">'.
    '</loginTicketRequest>');
  $TRA->addChild('header');
  $TRA->header->addChild('source','SERIALNUMBER=CUIT 20357161178, CN=ultracompu');
  $TRA->header->addChild('destination','cn=wsaahomo,o=afip,c=ar,serialNumber=CUIT 33693450239');
  $TRA->header->addChild('uniqueId',date('U'));
  $TRA->header->addChild('generationTime',date('c',date('U')-60));
  $TRA->header->addChild('expirationTime',date('c',date('U')+60));
  $TRA->addChild('service',$SERVICE);
  $TRA->asXML('TRA.xml');

}
#==============================================================================
# This functions makes the PKCS#7 signature using TRA as input file, CERT and
# PRIVATEKEY to sign. Generates an intermediate file and finally trims the 
# MIME heading leaving the final CMS required by WSAA.
function SignTRA()
{

 
$certificado="file://".realpath("../gestionn/includes/afip/certificado.crt");
$privatekey="file://".realpath("../gestionn/includes/afip/private.key");
$args = array(
               'extracerts' => $certificado,
               'friendly_name' => 'My signed cert by CA certificate'
              );
$pedido="file://".realpath("../gestionn/includes/afip/pedido.csr");
 // $STA=openssl_pkcs12_export($pedido,$certificado,$privatekey, "caruso12021991", $args);  
  $tra="../gestionn/includes/afip/TRA.xml";

  $STATUS=openssl_pkcs7_sign("C://xampp/htdocs/gestionn/includes/afip/TRA.xml", "C://xampp/htdocs/gestionn/TRA.tmp", "file://".realpath(CERT),
    array("file://".realpath(PRIVATEKEY), PASSPHRASE),
    array(),
    !PKCS7_DETACHED
    );

  if (!$STATUS) {exit("ERROR generating PKCS#7 signature\n");}
  $inf=fopen("C://xampp/htdocs/gestionn/TRA.tmp" , "r");
  $i=0;
  $CMS="";
  while (!feof($inf)) 
    { 
      $buffer=fgets($inf);
      if ( $i++ >= 4 ) {$CMS.=$buffer;}
    }
  fclose($inf);
#  unlink("TRA.xml");
  unlink("C://xampp/htdocs/gestionn/TRA.tmp");
  return $CMS;
}
#==============================================================================
function CallWSAA($CMS)
{
  $client=new SoapClient(WSDL, array(
          
          'soap_version'   => SOAP_1_2,
          'location'       => URL,
          'trace'          => 1,
          'exceptions'     => 0
          )); 
  $results=$client->loginCms(array('in0'=>base64_encode($CMS)));
  file_put_contents("request-loginCms.xml",$client->__getLastRequest());
  file_put_contents("response-loginCms.xml",$client->__getLastResponse());
  if (is_soap_fault($results)) 
    {exit("SOAP Fault: ".$results->faultcode."\n".$results->faultstring."\n");}
  return $results->loginCmsReturn;
}
#==============================================================================
function ShowUsage($MyPath)
{
  printf("Uso  : %s Arg#1 Arg#2\n", $MyPath);
  printf("donde: Arg#1 debe ser el service name del WS de negocio.\n");
  printf("  Ej.: %s wsfe\n", $MyPath);
}
#==============================================================================
ini_set("soap.wsdl_cache_enabled", "0");
if (!file_exists(CERT)) {exit("Failed to open ".CERT."\n");}
if (!file_exists(PRIVATEKEY)) {exit("Failed to open ".PRIVATEKEY."\n");}
if (!file_exists(WSDL)) {exit("Failed to open ".WSDL."\n");}
//if ( $argc < 2 ) {ShowUsage($argv[0]); exit();}
date_default_timezone_set('America/Argentina/Buenos_Aires');
$hoy = date("Y-m-j H:i:s"); 

if (file_exists("C:\\xampp\htdocs\gestionn\includes\afip\TA.xml")){
   $TA=simplexml_load_file("C:\\xampp\htdocs\gestionn\includes\afip\TA.xml");
   $expira=substr($TA->header->expirationTime,0,-10);
   $ec=str_replace('T',' ',$expira);
 
    if ($ec<$hoy){
   
    
    $SERVICE="ws_sr_padron_a5";
    CreateTRA($SERVICE);
    $CMS=SignTRA();
    $TA=CallWSAA(base64_decode($CMS));
    if (!file_put_contents("TA.xml", $TA)) {exit();}
    
   }}

    

?>


De igual manera cambie las rutas y directorios dado que gestionn es la carpeta local, los archivos estan todos en la misma carpeta dentro del server:

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
#==============================================================================
define ("WSDL",  dirname(dirname(__FILE__))."/afip/wsaa.wsdl");     # The WSDL corresponding to WSAA
define("CERT", dirname(dirname(__FILE__))."/afip/certificado.crt");  
   # The X.509 certificate in PEM format
define ("PRIVATEKEY", dirname(dirname(__FILE__))."/afip/privada.key"); # The private key correspoding to CERT (PEM)
define ("PASSPHRASE", "caruso12021991"); # The passphrase (if any) to sign
define ("PROXY_HOST", "10.20.152.112"); # Proxy IP, to reach the Internet
define ("PROXY_PORT", "80");            # Proxy TCP port
define ("URL", "https://wsaahomo.afip.gov.ar/ws/services/LoginCms");
#define ("URL", "https://wsaa.afip.gov.ar/ws/services/LoginCms");
#------------------------------------------------------------------------------
# You shouldn't have to change anything below this line!!!
#==============================================================================
function CreateTRA($SERVICE)
{
  $TRA = new SimpleXMLElement(
    '<?xml version="1.0" encoding="UTF-8"?>' .
    '<loginTicketRequest version="1.0">'.
    '</loginTicketRequest>');
  $TRA->addChild('header');
  $TRA->header->addChild('source','SERIALNUMBER=CUIT 20357161178, CN=ultracompu');
  $TRA->header->addChild('destination','cn=wsaahomo,o=afip,c=ar,serialNumber=CUIT 33693450239');
  $TRA->header->addChild('uniqueId',date('U'));
  $TRA->header->addChild('generationTime',date('c',date('U')-60));
  $TRA->header->addChild('expirationTime',date('c',date('U')+60));
  $TRA->addChild('service',$SERVICE);
  $TRA->asXML('TRA.xml');

}
#==============================================================================
# This functions makes the PKCS#7 signature using TRA as input file, CERT and
# PRIVATEKEY to sign. Generates an intermediate file and finally trims the 
# MIME heading leaving the final CMS required by WSAA.
function SignTRA()
{

 
$certificado="file://".realpath("/includes/afip/certificado.crt");
$privatekey="file://".realpath("/includes/afip/private.key");
$args = array(
               'extracerts' => $certificado,
               'friendly_name' => 'My signed cert by CA certificate'
              );
$pedido="file://".realpath("pedido.csr");
 // $STA=openssl_pkcs12_export($pedido,$certificado,$privatekey, "caruso12021991", $args);  
  $tra="/includes/afip/TRA.xml";

  $STATUS=openssl_pkcs7_sign("TRA.xml", "TRA.tmp", "file://".realpath(CERT),
    array("file://".realpath(PRIVATEKEY), PASSPHRASE),
    array(),
    !PKCS7_DETACHED
    );

  if (!$STATUS) {exit("ERROR generating PKCS#7 signature\n");}
  $inf=fopen("/TRA.tmp" , "r");
  $i=0;
  $CMS="";
  while (!feof($inf)) 
    { 
      $buffer=fgets($inf);
      if ( $i++ >= 4 ) {$CMS.=$buffer;}
    }
  fclose($inf);
#  unlink("TRA.xml");
  unlink("TRA.tmp");
  return $CMS;
}
#==============================================================================
function CallWSAA($CMS)
{
  $client=new SoapClient(WSDL, array(
          
          'soap_version'   => SOAP_1_2,
          'location'       => URL,
          'trace'          => 1,
          'exceptions'     => 0
          )); 
  $results=$client->loginCms(array('in0'=>base64_encode($CMS)));
  file_put_contents("request-loginCms.xml",$client->__getLastRequest());
  file_put_contents("response-loginCms.xml",$client->__getLastResponse());
  if (is_soap_fault($results)) 
    {exit("SOAP Fault: ".$results->faultcode."\n".$results->faultstring."\n");}
  return $results->loginCmsReturn;
}
#==============================================================================
function ShowUsage($MyPath)
{
  printf("Uso  : %s Arg#1 Arg#2\n", $MyPath);
  printf("donde: Arg#1 debe ser el service name del WS de negocio.\n");
  printf("  Ej.: %s wsfe\n", $MyPath);
}
#==============================================================================
ini_set("soap.wsdl_cache_enabled", "0");
if (!file_exists(CERT)) {exit("Failed to open ".CERT."\n");}
if (!file_exists(PRIVATEKEY)) {exit("Failed to open ".PRIVATEKEY."\n");}
if (!file_exists(WSDL)) {exit("Failed to open ".WSDL."\n");}
//if ( $argc < 2 ) {ShowUsage($argv[0]); exit();}
date_default_timezone_set('America/Argentina/Buenos_Aires');
$hoy = date("Y-m-j H:i:s"); 

if (file_exists("TA.xml")){
   $TA=simplexml_load_file("TA.xml");
   $expira=substr($TA->header->expirationTime,0,-10);
   $ec=str_replace('T',' ',$expira);
 
    if ($ec<$hoy){
   
    
    $SERVICE="ws_sr_padron_a5";
    CreateTRA($SERVICE);
    $CMS=SignTRA();
    $TA=CallWSAA(base64_decode($CMS));
    if (!file_put_contents("TA.xml", $TA)) {exit();}
    
   }}

    

?>


Y supongo el error esta en la funcion CallWSAA, por la fecha de modificacion de los ficheros: es decir el archivo TRA por ejempolo tiene la fecha de hoy que lo ejecute, pero los archivos request y response de logincms no.

Y el problema es que la pagina se cuelga en esa parte, aunque en local funciona todo perfecto.
Alguna ayuda?
Etiquetas: Facturación - PHP Votos: 1 - Respuestas: 2 - Vistas: 20 Compartir en: Google Facebook Twitter LinkedIn Link
 

Respuestas:

  • Fecha: 30-07-2019 07:30:07 Bueno tenia un error en esta linea:

     $inf=fopen("/TRA.tmp" , "r");


    La barra esta de mas, ahora anduvo
      Votos: 1 - Link respuesta
     
  • Fecha: 02-08-2019 12:58:40 Eso paso mucho cuando lo pruebas en local (Windows) y lo subes a un hosting compartido (por lo regular linux)
    Muchas veces te das cuenta en ello (y debes tomarlo en cuenta) por ejemplo cuando creas carpetas (ya que en linux debes ponerle permisos).

    Toma en cuenta ello, muchas veces no te regresa el error en la linea que es, y la mayoria de veces son cosas sencillas como esas.

    Saludos terricola.

    Stryfe™
      Votos: 0 - Link respuesta
     
Para participar activamente de la comunidad primero debes autenticarte, ingresa al sistema.Iniciar Sesión
 
frjcbbae garagebible.com