/** * verifica * Verifica o status da SEFAZ com o webservice e retorna tags html com o resultado * @param string $config json do arquivo de configuração * @return string */ public static function verifica($config = '') { $aRetorno = array(); if (empty($config)) { return ''; } self::$config = $config; if (is_file(APP_ROOT . '/base/status.json')) { $aRetorno = (array) json_decode(FilesFolders::readFile(APP_ROOT . '/base/status.json')); } $tstmp = DateTime::convertSefazTimeToTimestamp($aRetorno['dhRecbto']); $tsnow = time(); $dif = $tsnow - $tstmp; //caso tenha passado mais de uma hora desde a ultima verificação if ($dif > 3600) { self::$nfe = new ToolsNFe($config); self::$certTS = self::$nfe->certExpireTimestamp; self::$nfe->sefazStatus('', '', $aRetorno); $retJson = json_encode($aRetorno); FilesFolders::saveFile(APP_ROOT . '/base', 'status.json', $retJson); } $tstmp = DateTime::convertSefazTimeToTimestamp($aRetorno['dhRecbto']); $dhora = date('d/m/Y H:i:s', $tstmp); $htmlStatus = "<p class=\"smallred\">OFF-LINE</p>\n<p class=\"smallred\">{$dhora}</p>"; if ($aRetorno['cStat'] == '107') { $htmlStatus = "<p class=\"smallgreen\">SEFAZ On-Line</p>\n<p class=\"smallgreen\">{$dhora}</p>"; } return $htmlStatus; }
/** * zMontaMessagem * * @param string $pathFile */ protected function zMontaMessagem($pathFile) { $dom = new Dom(); $dom->loadXMLFile($pathFile); $infNFe = $dom->getNode('infNFe', 0); $ide = $infNFe->getElementsByTagName('ide')->item(0); $dest = $infNFe->getElementsByTagName('dest')->item(0); $emit = $infNFe->getElementsByTagName('emit')->item(0); $icmsTot = $infNFe->getElementsByTagName('ICMSTot')->item(0); $razao = $emit->getElementsByTagName('xNome')->item(0)->nodeValue; $nNF = $ide->getElementsByTagName('nNF')->item(0)->nodeValue; $serie = $ide->getElementsByTagName('serie')->item(0)->nodeValue; $xNome = $dest->getElementsByTagName('xNome')->item(0)->nodeValue; $dhEmi = !empty($ide->getElementsByTagName('dhEmi')->item(0)->nodeValue) ? $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue : $ide->getElementsByTagName('dEmi')->item(0)->nodeValue; $data = date('d/m/Y', DateTime::convertSefazTimeToTimestamp($dhEmi)); $vNF = $icmsTot->getElementsByTagName('vNF')->item(0)->nodeValue; $this->aMail[] = !empty($dest->getElementsByTagName('email')->item(0)->nodeValue) ? $dest->getElementsByTagName('email')->item(0)->nodeValue : ''; //pega os emails que existirem em obsCont $infAdic = $infNFe->getElementsByTagName('infAdic')->item(0); if (!empty($infAdic)) { $obsConts = $infAdic->getElementsByTagName('obsCont'); foreach ($obsConts as $obsCont) { if (strtoupper($obsCont->getAttribute('xCampo')) === 'EMAIL') { $this->aMail[] = $obsCont->getElementsByTagName('xTexto')->item(0)->nodeValue; } } } $this->msgHtml = $this->zRenderTemplate($xNome, $data, $nNF, $serie, $vNF, $razao); $this->msgTxt = utf8_encode(Html2Text::convert(utf8_decode($this->msgHtml))); return "NFe n. {$nNF} - {$razao}"; }
/** * zMontaMessagem * @param string $pathFile */ protected function zMontaMessagem($pathFile) { $dom = new Dom(); $dom->loadXMLFile($pathFile); $infMDFe = $dom->getNode('infMDFe', 0); $ide = $infMDFe->getElementsByTagName('ide')->item(0); $emit = $infMDFe->getElementsByTagName('emit')->item(0); $tot = $infMDFe->getElementsByTagName('tot')->item(0); $razao = $emit->getElementsByTagName('xNome')->item(0)->nodeValue; $nMDF = $ide->getElementsByTagName('nMDF')->item(0)->nodeValue; $serie = $ide->getElementsByTagName('serie')->item(0)->nodeValue; $dhEmi = !empty($ide->getElementsByTagName('dhEmi')->item(0)->nodeValue) ? $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue : $ide->getElementsByTagName('dEmi')->item(0)->nodeValue; $data = date('d/m/Y', DateTime::convertSefazTimeToTimestamp($dhEmi)); $vCarga = $tot->getElementsByTagName('vCarga')->item(0)->nodeValue; $xNome = ''; $this->msgHtml = $this->zRenderTemplate($xNome, $data, $nMDF, $serie, $vCarga, $razao); $this->msgTxt = utf8_encode(Html2Text::convert(utf8_decode($this->msgHtml))); return "MDFe n. {$nMDF} - {$razao}"; }
/** * zMontaMessagem * * @param string $pathFile */ protected function zMontaMessagem($pathFile) { $dom = new Dom(); $dom->loadXMLFile($pathFile); $infCTe = $dom->getNode('infCte', 0); $ide = $infCTe->getElementsByTagName('ide')->item(0); $dest = $infCTe->getElementsByTagName('dest')->item(0); $emit = $infCTe->getElementsByTagName('emit')->item(0); $vPrest = $infCTe->getElementsByTagName('vPrest')->item(0); $razao = $emit->getElementsByTagName('xNome')->item(0)->nodeValue; $nCT = $ide->getElementsByTagName('nCT')->item(0)->nodeValue; $serie = $ide->getElementsByTagName('serie')->item(0)->nodeValue; $xNome = $dest->getElementsByTagName('xNome')->item(0)->nodeValue; $dhEmi = !empty($ide->getElementsByTagName('dhEmi')->item(0)->nodeValue) ? $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue : $ide->getElementsByTagName('dEmi')->item(0)->nodeValue; $data = date('d/m/Y', DateTime::convertSefazTimeToTimestamp($dhEmi)); $vCT = $vPrest->getElementsByTagName('vTPrest')->item(0)->nodeValue; $this->aMail[] = !empty($dest->getElementsByTagName('email')->item(0)->nodeValue) ? $dest->getElementsByTagName('email')->item(0)->nodeValue : ''; $this->msgHtml = $this->zRenderTemplate($xNome, $data, $nCT, $serie, $vCT, $razao); $cHTT = new Html2Text($this->msgHtml); $this->msgTxt = $cHTT->getText(); return "CTe n. {$nCT} - {$razao}"; }
/** * zPutQRTag * Monta a URI para o QRCode e coloca a tag * no xml já assinado * @param Dom $dom * @return string * NOTA: O Campo QRCode está habilitado para uso a partir de * 01/10/2015 homologação * 03/11/2015 Produção */ protected function zPutQRTag(Dom $dom, $saveFile) { //pega os dados necessários para a montagem da URI a partir do xml $nfe = $dom->getNode('NFe'); $ide = $dom->getNode('ide'); $dest = $dom->getNode('dest'); $icmsTot = $dom->getNode('ICMSTot'); $signedInfo = $dom->getNode('SignedInfo'); $chNFe = $dom->getChave('infNFe'); $cUF = $dom->getValue($ide, 'cUF'); $tpAmb = $dom->getValue($ide, 'tpAmb'); $dhEmi = $dom->getValue($ide, 'dhEmi'); $cDest = ''; if (!empty($dest)) { //pode ser CNPJ , CPF ou idEstrageiro $cDest = $dom->getValue($dest, 'CNPJ'); if ($cDest == '') { $cDest = $dom->getValue($dest, 'CPF'); if ($cDest == '') { $cDest = $dom->getValue($dest, 'idEstrangeiro'); } } } $vNF = $dom->getValue($icmsTot, 'vNF'); $vICMS = $dom->getValue($icmsTot, 'vICMS'); $digVal = $dom->getValue($signedInfo, 'DigestValue'); $token = $this->aConfig['tokenNFCe']; $idToken = $this->aConfig['tokenNFCeId']; $versao = '100'; //pega a URL para consulta do QRCode do estado emissor //essa url está em nfe_ws3_mode65.xml //carrega serviço $servico = 'NfeConsultaQR'; $siglaUF = $this->zGetSigla($cUF); $this->zLoadServico('nfe', $servico, $siglaUF, $tpAmb); if ($this->urlService == '') { $this->errors[] = "A consulta por QRCode não está disponível na SEFAZ {$siglaUF}!!!"; return $dom->saveXML(); } $url = $this->urlService; //usa a função zMakeQRCode para gerar a string da URI $qrcode = $this->zMakeQRCode($chNFe, $url, $tpAmb, $dhEmi, $vNF, $vICMS, $digVal, $token, $cDest, $idToken, $versao); if ($qrcode == '') { return $dom->saveXML(); } //inclui a TAG NFe/infNFeSupl com o qrcode $infNFeSupl = $dom->createElement("infNFeSupl"); $nodeqr = $infNFeSupl->appendChild($dom->createElement('qrCode')); $nodeqr->appendChild($dom->createCDATASection($qrcode)); $signature = $dom->getElementsByTagName('Signature')->item(0); $nfe->insertBefore($infNFeSupl, $signature); $dom->formatOutput = false; $xmlSigned = $dom->saveXML(); //salva novamente o xml assinado e agora com o QRCode if ($saveFile) { $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($dhEmi)); $filename = "{$chNFe}-nfe.xml"; $this->zGravaFile('nfe', $tpAmb, $filename, $xmlSigned, 'assinadas', $anomes); } //retorna a string com o xml assinado e com o QRCode return $xmlSigned; }
/** * assinaDoc * @param string $xml * @param string $tipo nfe, cte, ou mdfe * @param string $tag Nome da tag a ser assinada * @param boolean $saveFile APENAS para salvar NFe, CTe ou MDFe * @return string * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ public function assinaDoc($xml = '', $tipo = '', $tag = '', $saveFile = false) { if ($tag == '') { $msg = 'Deve ser indicada uma tag a ser assinada'; throw new Exception\InvalidArgumentException($msg); } if (is_file($xml)) { $xml = Files\FilesFolders::readFile($xml); } $sxml = $this->oCertificate->signXML($xml, $tag); $dom = new Dom(); $dom->loadXMLString($sxml); //$versao = $dom->getElementsByTagName($tag)->item(0)->getAttribute('versao'); //if (! $this->zValidMessage($sxml, $tipo, $versao)) { //$msg = "Falha na validação do $tipo. ".$this->error; // throw new Exception\RuntimeException($msg); //} if ($saveFile && $tipo != '') { $dom = new Dom(); $dom->loadXMLString($sxml); $tpAmb = $dom->getElementsByTagName('tpAmb')->item(0)->nodeValue; $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($dom->getElementsByTagName('dhEmi')->item(0)->nodeValue)); $chave = $dom->getChave($tag); $filename = "{$chave}-{$tipo}.xml"; $this->zGravaFile($tipo, $tpAmb, $filename, $sxml, 'assinadas', $anomes); } return $sxml; }
/** * addCancelamento * Adiciona a tga de cancelamento a uma MDFe já autorizada * NOTA: não é requisito da SEFAZ, mas auxilia na identificação das MDFe que foram canceladas * @param string $pathMDFefile * @param string $pathCancfile * @param bool $saveFile * @return string * @throws Exception\RuntimeException */ public function addCancelamento($pathMDFefile = '', $pathCancfile = '', $saveFile = false) { $procXML = ''; //carrega a NFe $docmdfe = new Dom(); $docmdfe->loadXMLFile($pathMDFefile); $nodemdfe = $docmdfe->getNode('MDFe', 0); if ($nodemdfe == '') { $msg = "O arquivo indicado como MDFe não é um xml de MDFe!"; throw new Exception\RuntimeException($msg); } $proMDFe = $docmdfe->getNode('protMDFe'); if ($proMDFe == '') { $msg = "O MDFe não está protocolado ainda!!"; throw new Exception\RuntimeException($msg); } $chaveMDFe = $proMDFe->getElementsByTagName('chMDFe')->item(0)->nodeValue; //$nProtNFe = $proNFe->getElementsByTagName('nProt')->item(0)->nodeValue; $tpAmb = $docmdfe->getNodeValue('tpAmb'); $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($docmdfe->getNodeValue('dhEmi'))); //carrega o cancelamento //pode ser um evento ou resultado de uma consulta com multiplos eventos $doccanc = new Dom(); $doccanc->loadXMLFile($pathCancfile); $eventos = $doccanc->getElementsByTagName('infEvento'); foreach ($eventos as $evento) { //evento $cStat = $evento->getElementsByTagName('cStat')->item(0)->nodeValue; $tpAmb = $evento->getElementsByTagName('tpAmb')->item(0)->nodeValue; $chaveEvento = $evento->getElementsByTagName('chNFe')->item(0)->nodeValue; $tpEvento = $evento->getElementsByTagName('tpEvento')->item(0)->nodeValue; //$nProtEvento = $evento->getElementsByTagName('nProt')->item(0)->nodeValue; //verifica se conferem os dados //cStat = 135 ==> evento homologado //tpEvento = 110111 ==> Cancelamento //chave do evento == chave da NFe //protocolo do evneto == protocolo da NFe if ($cStat == '135' && $tpEvento == '110111' && $chaveEvento == $chaveMDFe) { $proMDFe->getElementsByTagName('cStat')->item(0)->nodeValue = '101'; $proMDFe->getElementsByTagName('xMotivo')->item(0)->nodeValue = 'Cancelamento de NF-e homologado'; $procXML = $docmdfe->saveXML(); //remove as informações indesejadas $procXML = Strings::clearProt($procXML); if ($saveFile) { $filename = "{$chaveMDFe}-protMDFe.xml"; $this->zGravaFile('mdfe', $tpAmb, $filename, $procXML, 'enviadas' . DIRECTORY_SEPARATOR . 'aprovadas', $anomes); } break; } } return (string) $procXML; }
public static function extrai($aList, $cnpj = '') { $aResp = array(); $totFat = 0; $totPeso = 0; $totIcms = 0; foreach ($aList as $file) { $dom = null; $ide = null; $emit = null; $dest = null; try { $dom = new Dom(); $dom->loadXMLFile($file); $ide = $dom->getNode('ide'); $emit = $dom->getNode('emit'); $dest = $dom->getNode('dest'); $icmsTot = $dom->getNode('ICMSTot'); $vol = $dom->getNode('vol'); $cStat = $dom->getNodeValue('cStat'); if ($cStat != '100') { self::$nCanc++; } $dhEmi = $dom->getValue($ide, 'dhEmi'); if (empty($dhEmi)) { $dhEmi = $dom->getValue($ide, 'dEmi'); } //echo $file.'___'.$dhEmi.'<br>'; $tsEmi = DateTime::convertSefazTimeToTimestamp($dhEmi); $data = ''; if (is_numeric($tsEmi)) { $data = date('d/m/Y', $tsEmi); } $emitCNPJ = $dom->getValue($emit, 'CNPJ'); $emitRazao = $dom->getValue($emit, 'xNome'); $destRazao = $dom->getValue($dest, 'xNome'); $vNF = $dom->getValue($icmsTot, 'vNF'); $vNFtext = $vNF; if (is_numeric($vNF)) { $vNFtext = 'R$ ' . number_format($vNF, '2', ',', '.'); } $serie = $dom->getNodeValue('serie'); $nProt = $dom->getNodeValue('nProt'); $nome = $emitRazao; if ($emitCNPJ == $cnpj) { $nome = $destRazao; } $email = $dom->getValue($dest, 'email'); $aObscont = $dom->getElementsByTagName('obsCont'); if (count($aObscont) > 0) { foreach ($aObscont as $obsCont) { $xCampo = $obsCont->getAttribute('xCampo'); if ($xCampo == 'email') { $email .= ";" . $dom->getValue($obsCont, 'xTexto'); } } } if (substr($email, 0, 1) == ';') { $email = substr($email, 1, strlen($email) - 1); } $vICMS = $dom->getValue($icmsTot, 'vICMS'); $totIcms += $vICMS; $valorFat = 0; if ($vICMS != 0 && $cStat == '100') { $valorFat = $vNF; } $totFat += $valorFat; $pesoL = $dom->getValue($vol, 'pesoL'); if ($pesoL != '') { $totPeso += $pesoL; } $aResp[] = array('nNF' => $dom->getValue($ide, 'nNF'), 'serie' => $serie, 'data' => $data, 'nome' => $nome, 'natureza' => $dom->getValue($ide, 'natOp'), 'cStat' => $cStat, 'vNF' => $vNFtext, 'nProt' => $nProt, 'email' => $email); } catch (RuntimeException $e) { $aResp[] = array('nNF' => '000000', 'serie' => '000', 'data' => '000', 'nome' => 'FALHA', 'natureza' => "{$file}", 'cStat' => '', 'vNF' => 0, 'nProt' => '', 'email' => ''); } } return array('totFat' => $totFat, 'totPeso' => $totPeso, 'totIcms' => $totIcms, 'aNF' => $aResp); }
public function testConvertSefazTimeToTimestampEmBranco() { $this->assertEmpty(DateTime::convertSefazTimeToTimestamp()); }
public function testConvertSefazTimeToTimestamp() { DateTime::tzdBR('CE'); $tsp = DateTime::convertSefazTimeToTimestamp($this->sefTime); $this->assertEquals($tsp, $this->tstp); }
/** * zTrataProcEvent * @param array $resp */ private static function zTrataProcEvent($resp = array()) { $aResp = array(); $content = $resp['doc']; $dom = new Dom(); $dom->loadXMLString($content); $xmldata = $dom->saveXML(); $xmldata = str_replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="utf-8"?>', $xmldata); $data = $dom->getNodeValue('dhEvento'); $tsdhevento = DateTime::convertSefazTimeToTimestamp($data); $anomes = date('Ym', $tsdhevento); $tpEvento = $dom->getNodeValue('tpEvento'); $chave = $dom->getNodeValue('chNFe'); if ($tpEvento == '110111') { //confirmado cancelamento, localizar o xml da NFe recebida //na pasta anomes $path = $this->pathNFe . DIRECTORY_SEPARATOR . $this->ambiente . DIRECTORY_SEPARATOR . "recebidas" . DIRECTORY_SEPARATOR . $anomes; $pathFile = $path . DIRECTORY_SEPARATOR . $chave . '-nfe.xml'; self::zCancela($pathFile); $aResp[] = array('tipo' => '-cancNFe.xml', 'chave' => $chave, 'anomes' => $anomes, 'xml' => $xmldata); } elseif ($tpEvento == '110110') { //evento Carta de Correção $aResp[] = array('tipo' => '-cce.xml', 'chave' => $chave, 'anomes' => $anomes, 'xml' => $xmldata); } return $aResp; }
/** * addCancelamento * Adiciona a tga de cancelamento a uma CTe já autorizada * NOTA: não é requisito da SEFAZ, mas auxilia na identificação das CTe que foram canceladas * @param string $pathCTefile * @param string $pathCancfile * @param bool $saveFile * @return string * @throws Exception\RuntimeException */ public function addCancelamento($pathCTefile = '', $pathCancfile = '', $saveFile = false) { $procXML = ''; //carrega a CTe $docCTe = new Dom(); if (file_exists($pathCTefile)) { //carrega o XML pelo caminho do arquivo informado $docCTe->loadXMLFile($pathCTefile); } else { //carrega o XML pelo conteúdo $docCTe->loadXMLString($pathCTefile); } $nodeCTe = $docCTe->getNode('CTe', 0); if ($nodeCTe == '') { $msg = "O arquivo indicado como CTe não é um xml de CTe!"; throw new Exception\RuntimeException($msg); } $proCTe = $docCTe->getNode('protCTe'); if ($proCTe == '') { $msg = "A CTe não está protocolada ainda!!"; throw new Exception\RuntimeException($msg); } $chaveCTe = $proCTe->getElementsByTagName('chCTe')->item(0)->nodeValue; //$nProtCTe = $proCTe->getElementsByTagName('nProt')->item(0)->nodeValue; $tpAmb = $docCTe->getNodeValue('tpAmb'); $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($docCTe->getNodeValue('dhEmi'))); //carrega o cancelamento //pode ser um evento ou resultado de uma consulta com multiplos eventos $doccanc = new Dom(); if (file_exists($pathCancfile)) { //carrega o XML pelo caminho do arquivo informado $doccanc->loadXMLFile($pathCancfile); } else { //carrega o XML pelo conteúdo $doccanc->loadXMLString($pathCancfile); } $retEvento = $doccanc->getElementsByTagName('retEventoCTe')->item(0); $eventos = $retEvento->getElementsByTagName('infEvento'); foreach ($eventos as $evento) { //evento $cStat = $evento->getElementsByTagName('cStat')->item(0)->nodeValue; $tpAmb = $evento->getElementsByTagName('tpAmb')->item(0)->nodeValue; $chaveEvento = $evento->getElementsByTagName('chCTe')->item(0)->nodeValue; $tpEvento = $evento->getElementsByTagName('tpEvento')->item(0)->nodeValue; //$nProtEvento = $evento->getElementsByTagName('nProt')->item(0)->nodeValue; //verifica se conferem os dados //cStat = 135 ==> evento homologado //cStat = 136 ==> vinculação do evento à respectiva NF-e prejudicada //cStat = 155 ==> Cancelamento homologado fora de prazo //tpEvento = 110111 ==> Cancelamento //chave do evento == chave da CTe //protocolo do evneto == protocolo da CTe if (($cStat == '135' || $cStat == '136' || $cStat == '155') && $tpEvento == '110111' && $chaveEvento == $chaveCTe) { $proCTe->getElementsByTagName('cStat')->item(0)->nodeValue = '101'; $proCTe->getElementsByTagName('xMotivo')->item(0)->nodeValue = 'Cancelamento de CT-e homologado'; $procXML = $docCTe->saveXML(); //remove as informações indesejadas $procXML = Strings::clearProt($procXML); if ($saveFile) { $filename = "{$chaveCTe}-protCTe.xml"; $this->zGravaFile('cte', $tpAmb, $filename, $procXML, 'canceladas', $anomes); } break; } } return (string) $procXML; }
/** * Busca a data e hora do processamento * * @param DOMElement $node * @return strinf */ protected static function retDataHora($node) { $data = ''; $dtHora = self::retValue($node, 'dataHoraProcessamento'); if (empty($dtHora)) { $dtHora = self::retValue($node, 'dhProcessamento'); } if (!empty($dtHora)) { $data = date('d/m/Y H:i:s', DateTime::convertSefazTimeToTimestamp($dtHora)); } return $data; }