Boa tarde grupo, gostaria de saber se é possível consultar NSUs antigas sem ser bloquado, sei que na teoria o sistema bloqueia acessos as muito antigas, porém somente o resumo já serviria pra mim, segue abaixo o código que estou usando, agradeço desde já a ajuda.
<?php
require 'vendor/autoload.php';
use NFePHP\NFe\Tools;
use NFePHP\Common\Certificate;
// CONFIGURAÇÕES
$configJson = file_get_contents('empresa.json'); // Ajuste o caminho
$pfxContent = file_get_contents('certificado.pfx'); // Ajuste o caminho
$certPassword = '########'; // Substitua pela senha
$tools = new Tools($configJson, Certificate::readPfx($pfxContent, $certPassword));
$tools->model('55');
$tools->setEnvironment(1);
$xmlPath = __DIR__ . '/xmls/';
if (!is_dir($xmlPath))
mkdir($xmlPath);
$ultNSUfile = __DIR__ . '/ultNSU.txt';
// Recupera o último NSU já processado
if (file_exists($ultNSUfile)) {
$ultNSU = trim(file_get_contents($ultNSUfile));
if (!$ultNSU)
$ultNSU = '000000000000000';
} else {
$ultNSU = '000000000000000';
}
$maxNSU = $ultNSU;
$loopLimit = 15; // Menor que 20 para margem de segurança
$iCount = 0;
echo "Iniciando consulta a partir do NSU: $ultNSU\n";
while (bccomp($ultNSU, $maxNSU) <= 0) {
$iCount++;
if ($iCount > $loopLimit) {
echo "Limite de consultas atingido. Aguarde e tente depois!\n";
break;
}
try {
$resp = $tools->sefazDistDFe($ultNSU);
} catch (\Exception $e) {
echo "Erro: " . $e->getMessage() . "\n";
break;
}
$dom = new \DOMDocument();
$dom->loadXML($resp);
$node = $dom->getElementsByTagName('retDistDFeInt')->item(0);
$cStat = $node->getElementsByTagName('cStat')->item(0)->nodeValue;
$xMotivo = $node->getElementsByTagName('xMotivo')->item(0)->nodeValue;
$ultNSU_resp = $node->getElementsByTagName('ultNSU')->item(0)->nodeValue;
$maxNSU = $node->getElementsByTagName('maxNSU')->item(0)->nodeValue;
$lote = $node->getElementsByTagName('loteDistDFeInt')->item(0);
echo "Consulta $iCount | cStat=$cStat | ultNSU=$ultNSU_resp | maxNSU=$maxNSU | $xMotivo\n";
// Grava o último NSU
file_put_contents($ultNSUfile, $ultNSU_resp);
if (in_array($cStat, ['137', '656'])) {
$tempo = 3600; // 1 hora (em segundos)
$msg = $cStat == '137'
? "Nenhum documento localizado. Espere pelo menos 1 hora para nova consulta."
: "Consumo indevido! Bloqueado por 1 hora. Reveja sua rotina!";
echo "$msg\n";
break;
}
if (empty($lote)) {
echo "Nenhum lote retornado.\n";
$ultNSU = bcadd($ultNSU, 1, 0);
sleep(2);
continue;
}
foreach ($lote->getElementsByTagName('docZip') as $doc) {
$nsu = $doc->getAttribute('NSU');
$schema = $doc->getAttribute('schema');
$xmlContent = gzdecode(base64_decode($doc->nodeValue));
$arquivo = "{$xmlPath}{$nsu}_{$schema}.xml";
file_put_contents($arquivo, $xmlContent);
echo "Salvo: $arquivo\n";
}
if ($ultNSU_resp == $maxNSU) {
echo "Chegou ao fim dos NSUs disponíveis! Nova consulta só após 1 hora.\n";
break;
}
// Próximo NSU para consulta
$ultNSU = $ultNSU_resp;
sleep(2);
}
echo "Consulta encerrada.\n";
?>