Ir para conteúdo
Fórum Script Brasil
  • 0

Erro no meu codigo Gera_xml nfe 4.00


Cleimar Lemes

Pergunta

esto com problemas pra gerar um xml já tentei de tudo
make, nfphp-/sped-phpnfe

já fiz de tudo. e nunca gera so erro erro.. 

segue meu codigo do gera..

<?php
// views/gera_xml.php -

// Requisitos / autoload
require __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../vendor/autoload.php';

use NFePHP\NFe\Make;
use NFePHP\Common\Exception\ValidationException;

date_default_timezone_set('America/Sao_Paulo');

// ---------- GET ID
$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
if (!$id) die(" ID da NFe não informado. Use ?id=NUMERO");

// ---------- Carregar NFe
try {
    $stmt = $pdo->prepare("SELECT * FROM nfe WHERE id = ?");
    $stmt->execute([$id]);
    $nfe = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
    die(" Erro ao carregar NFe: " . $e->getMessage());
}
if (!$nfe) die(" NFe não encontrada.");

// ---------- Carregar emitente ATIVO
try {
    $stmt = $pdo->prepare("SELECT * FROM emitentes WHERE ativo = 1 LIMIT 1");
    $stmt->execute();
    $emit = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
    die(" Erro ao carregar emitente: " . $e->getMessage());
}
if (!$emit) die(" Emitente ativo não encontrado. Marque um emitente como ativo.");

// ---------- Carregar destinatário (clientes_nfe preferencial)
$destCliente = null;
if (!empty($nfe['dest_id'])) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM clientes_nfe WHERE id = ?");
        $stmt->execute([$nfe['dest_id']]);
        $destCliente = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (\PDOException $e) { $destCliente = null; }
}

// ---------- Carregar itens (nfe_itens JOIN produtos)
try {
    $sqlItens = $pdo->prepare("
        SELECT i.*,
               p.xProd AS produto_nome,
               COALESCE(p.uCom, p.uTrib) AS produto_unidade,
               p.NCM AS produto_NCM,
               p.CEST AS produto_CEST,
               p.CFOP AS produto_CFOP,
               p.preco_venda AS produto_preco_venda,
               p.csosn AS produto_csosn,
               p.cst_pis AS produto_cst_pis,
               p.cst_cofins AS produto_cst_cofins,
               p.cst_ipi AS produto_cst_ipi
        FROM nfe_itens i
        JOIN produtos p ON p.id = i.produto_id
        WHERE i.nfe_id = ?
        ORDER BY i.id ASC
    ");
    $sqlItens->execute([$id]);
    $itens = $sqlItens->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
    die(" Erro ao carregar itens: " . $e->getMessage());
}
if (!$itens) $itens = [];

// ---------- Inicializa Make
try {
    $make = new Make();
} catch (\Throwable $e) {
    die(" Erro ao inicializar NFePHP Make: " . $e->getMessage());
}

// ---------------- utilitários (DV mod11, montagem manual da chave)
function calculaDVMod11NFe($chave43) {
    $peso = 2; $soma = 0;
    for ($i = strlen($chave43) - 1; $i >= 0; $i--) {
        $soma += intval($chave43[$i]) * $peso;
        $peso++; if ($peso > 9) $peso = 2;
    }
    $resto = $soma % 11;
    $dv = 11 - $resto;
    if ($dv == 10 || $dv == 11) $dv = 0;
    return (string)$dv;
}
function montaChaveManual($cUF, $ano2, $mes2, $cnpj, $mod, $serie, $nNF, $tpEmis, $cNF) {
    $cUF = str_pad(substr($cUF, 0, 2), 2, "0", STR_PAD_LEFT);
    $aamm = str_pad($ano2, 2, "0", STR_PAD_LEFT) . str_pad($mes2, 2, "0", STR_PAD_LEFT);
    $cnpj = str_pad(preg_replace("/\D/","",$cnpj), 14, "0", STR_PAD_LEFT);
    $mod = str_pad($mod, 2, "0", STR_PAD_LEFT);
    $serie = str_pad($serie, 3, "0", STR_PAD_LEFT);
    $nNF = str_pad($nNF, 9, "0", STR_PAD_LEFT);
    $tpEmis = str_pad($tpEmis, 1, "0", STR_PAD_LEFT);
    $cNF = str_pad($cNF, 8, "0", STR_PAD_LEFT);
    $chave43 = $cUF . $aamm . $cnpj . $mod . $serie . $nNF . $tpEmis . $cNF;
    $dv = calculaDVMod11NFe($chave43);
    return $chave43 . $dv;
}

// ---------------- montar campos chave
$cnpj_emit = $emit['CNPJ'] ?? ($emit['cnpj'] ?? '');
$cnpj_emit = preg_replace('/\D/','',$cnpj_emit);
$mod = '55';
$serie = $nfe['serie'] ?? 1;
$numero = $nfe['nNF'] ?? 0;
$tpEmis = $nfe['tpEmis'] ?? 1;
$codigo = $nfe['cNF'] ?? ($nfe['cNF'] ?? '');
$ufEmit = $nfe['cUF'] ?? ($emit['cMun'] ?? ($emit['UF'] ?? ($emit['uf'] ?? '52')));
$dtEmissao = isset($nfe['dhEmi']) ? new DateTime($nfe['dhEmi']) : new DateTime();
$ano2 = $dtEmissao->format('y'); $mes2 = $dtEmissao->format('m');
$cNF = str_pad($codigo, 8, "0", STR_PAD_LEFT);

// ---------------- gerar chave com fallback
$chave = null;
try {
    if (class_exists('NFePHP\NFe\Common\KeyNFe')) {
        try {
            if (method_exists('NFePHP\NFe\Common\KeyNFe', 'build')) {
                $chave = \NFePHP\NFe\Common\KeyNFe::build($ufEmit, $ano2, $mes2, $cnpj_emit, $mod, $serie, $numero, $tpEmis, $codigo);
            } else {
                $k = new \NFePHP\NFe\Common\KeyNFe($ufEmit, $ano2, $mes2, $cnpj_emit, $mod, $serie, $numero, $tpEmis, $cNF);
                if (method_exists($k, 'monta')) $chave = $k->monta();
            }
        } catch (\Throwable $e) { $chave = null; }
    }
    if (empty($chave) && method_exists($make, 'montaChave')) {
        try { $chave = $make->montaChave($ufEmit, $ano2, $mes2, $cnpj_emit, $mod, $serie, $numero, $tpEmis, $cNF); }
        catch (\Throwable $e) { $chave = null; }
    }
    if (empty($chave)) {
        $chave = montaChaveManual($ufEmit, $ano2, $mes2, $cnpj_emit, $mod, $serie, $numero, $tpEmis, $cNF);
    }
} catch (\Throwable $e) {
    die(" Erro ao gerar chave: " . $e->getMessage());
}
if (empty($chave) || strlen($chave) != 44) die(" Chave inválida gerada: " . htmlspecialchars($chave));
$cDV = substr($chave, -1);

// ---------------- taginfNFe
$std = new \stdClass();
$std->Id = 'NFe' . $chave; // assinador pode alterar o Id (pfx...)
$std->versao = '4.00';
$make->taginfNFe($std);

// ---------------- IDE
$ide = new \stdClass();
$ide->cUF = $nfe['cUF'] ?? substr($ufEmit, 0, 2);
$ide->cNF = $cNF;
$ide->natOp = $nfe['natOp'] ?? 'VENDA';
$ide->mod = 55;
$ide->serie = (int)$serie;
$ide->nNF = (int)($nfe['nNF'] ?? 0);
$ide->dhEmi = $dtEmissao->format('Y-m-d\TH:i:sP');
$ide->dhSaiEnt = $dtEmissao->format('Y-m-d\TH:i:sP');
$ide->tpNF = (int)($nfe['tpNF'] ?? 1);
$ide->idDest = (int)($nfe['idDest'] ?? 1);
$ide->cMunFG = $nfe['cMunFG'] ?? ($emit['cMun'] ?? '');
$ide->tpImp = 1;
$ide->tpEmis = (int)$tpEmis;
$ide->cDV = $cDV;
$ide->tpAmb = (int)($nfe['tpAmb'] ?? 2);
$ide->finNFe = (int)($nfe['finNFe'] ?? 1);
$ide->indFinal = (int)($nfe['indFinal'] ?? 1);
$ide->indPres = (int)($nfe['indPres'] ?? 1);
$ide->procEmi = 0;
$ide->verProc = '1.0';
$make->tagide($ide);

// ---------------- EMITENTE
$emitente = new \stdClass();
$emitente->CNPJ = preg_replace('/\D/','',$emit['CNPJ'] ?? '');
$emitente->xNome = $emit['xNome'] ?? '';
$emitente->xFant = $emit['xFant'] ?? '';
$emitente->IE = $emit['IE'] ?? '';
$emitente->CRT = $emit['CRT'] ?? 1;
$make->tagemit($emitente);

// endereco emitente
$enderEmit = new \stdClass();
$enderEmit->xLgr = $emit['xLgr'] ?? '';
$enderEmit->nro = $emit['nro'] ?? '';
$enderEmit->xCpl = $emit['xCpl'] ?? '';
$enderEmit->xBairro = $emit['xBairro'] ?? '';
$enderEmit->cMun = $emit['cMun'] ?? '';
$enderEmit->xMun = $emit['xMun'] ?? '';
$enderEmit->UF = $emit['UF'] ?? '';
$enderEmit->CEP = preg_replace('/\D/','',$emit['CEP'] ?? '');
$enderEmit->cPais = $emit['cPais'] ?? 1058;
$enderEmit->xPais = $emit['xPais'] ?? 'BRASIL';
$enderEmit->fone = preg_replace('/\D/','',$emit['fone'] ?? '');
$make->tagenderEmit($enderEmit);

// ---------------- DESTINATÁRIO
$dest = new \stdClass();
if ($destCliente) {
    $dest->CPF = preg_replace('/\D/','',$destCliente['CPF'] ?? $destCliente['cpf'] ?? '');
    $dest->CNPJ = preg_replace('/\D/','',$destCliente['CNPJ'] ?? $destCliente['cnpj'] ?? '');
    $dest->xNome = $destCliente['xNome'] ?? $destCliente['nome'] ?? '';
    $dest->indIEDest = (strlen($dest->CPF) == 11) ? 9 : 1;
} else {
    $dest->CPF = preg_replace('/\D/','',$nfe['dest_cpf'] ?? '');
    $dest->CNPJ = preg_replace('/\D/','',$nfe['dest_cnpj'] ?? '');
    $dest->xNome = $nfe['dest_nome'] ?? ($nfe['destinatario'] ?? '');
    $dest->indIEDest = (strlen($dest->CPF) == 11) ? 9 : 1;
}
$make->tagdest($dest);

// endereco dest
$enderDest = new \stdClass();
if ($destCliente) {
    $enderDest->xLgr = $destCliente['xLgr'] ?? $destCliente['logradouro'] ?? '';
    $enderDest->nro = $destCliente['nro'] ?? $destCliente['numero'] ?? '';
    $enderDest->xBairro = $destCliente['xBairro'] ?? $destCliente['bairro'] ?? '';
    $enderDest->cMun = $destCliente['cMun'] ?? $destCliente['codigo_municipio'] ?? '';
    $enderDest->xMun = $destCliente['xMun'] ?? $destCliente['municipio'] ?? '';
    $enderDest->UF = $destCliente['UF'] ?? $destCliente['uf'] ?? '';
    $enderDest->CEP = preg_replace('/\D/','',$destCliente['CEP'] ?? $destCliente['cep'] ?? '');
} else {
    $enderDest->xLgr = $nfe['dest_logradouro'] ?? '';
    $enderDest->nro = $nfe['dest_numero'] ?? '';
    $enderDest->xBairro = $nfe['dest_bairro'] ?? '';
    $enderDest->cMun = $nfe['dest_cod_municipio'] ?? '';
    $enderDest->xMun = $nfe['dest_municipio'] ?? '';
    $enderDest->UF = $nfe['dest_uf'] ?? '';
    $enderDest->CEP = preg_replace('/\D/','',$nfe['dest_cep'] ?? '');
}
$enderDest->cPais = 1058;
$enderDest->xPais = 'BRASIL';
$make->tagenderDest($enderDest);

// ---------------- ITENS (det / prod / imposto)
$nItem = 1;
$total_vProd = 0.00;
$emitCRT = intval($emit['CRT'] ?? 1); // 1 = Simples Nacional, else regime normal

foreach ($itens as $item) {
    $produto_id = $item['produto_id'];
    $xProd = $item['produto_nome'] ?? '';
    $NCM = $item['NCM'] ?? $item['produto_NCM'] ?? '';
    $CEST = $item['CEST'] ?? $item['produto_CEST'] ?? '';
    $CFOP = $item['CFOP'] ?? $item['produto_CFOP'] ?? ($nfe['CFOP'] ?? '5102');

    $qCom = floatval($item['qCom'] ?? 0.0000);
    $vUnCom = floatval($item['vUnCom'] ?? ($item['produto_preco_venda'] ?? 0.00));
    $vProd = floatval($item['vProd'] ?? round($qCom * $vUnCom, 2));
    $total_vProd += $vProd;

    // PROD
    $prod = new \stdClass();
    $prod->item = $nItem;
    $prod->cProd = ''; // conforme XML assinado você pode deixar vazio
    $prod->cEAN = '';
    $prod->xProd = $xProd;
    $prod->NCM = $NCM;
    $prod->CFOP = $CFOP;
    $prod->uCom = $item['produto_unidade'] ?? 'UN';
    $prod->qCom = number_format($qCom, 4, '.', '');
    $prod->vUnCom = number_format($vUnCom, 10, '.', ''); // manter precisão alta
    $prod->vProd = number_format($vProd, 2, '.', '');
    $prod->cEANTrib = '';
    $prod->uTrib = $prod->uCom;
    $prod->qTrib = $prod->qCom;
    $prod->vUnTrib = number_format(0, 10, '.', ''); // conforme seu xml assinado: 0.0000000000
    $prod->indTot = 1;

    $make->tagprod($prod);

    // ---------- imposto: tagimposto (stdClass) obrigatório
    $stdImposto = new \stdClass();
    $stdImposto->item = $nItem;
    $stdImposto->vTotTrib = number_format(0.00, 2, '.', '');
    $make->tagimposto($stdImposto);

    // ---------- ICMS
    if ($emitCRT === 1 && method_exists($make, 'tagICMSSN')) {
        // Simples Nacional -> CSOSN
        $icmssn = new \stdClass();
        $icmssn->item = $nItem;
        $icmssn->orig = $item['orig'] ?? 0;
        $icmssn->CSOSN = $item['csosn'] ?? $item['produto_csosn'] ?? '102';
        $icmssn->pCredSN = '0.00';
        $icmssn->vCredICMSSN = '0.00';
        $make->tagICMSSN($icmssn);
    } else {
        // Regime normal -> ICMS00
        if (method_exists($make, 'tagICMS00')) {
            $icms00 = new \stdClass();
            $icms00->item = $nItem;
            $icms00->orig = $item['orig'] ?? 0;
            $icms00->pICMS = floatval($item['pICMS'] ?? 0.00);
            $icms00->vBC = number_format(0, 2, '.', '');
            $icms00->vICMS = number_format(0, 2, '.', '');
            $make->tagICMS00($icms00);
        } elseif (method_exists($make, 'tagICMS')) {
            $icms = new \stdClass();
            $icms->item = $nItem;
            $icms->orig = $item['orig'] ?? 0;
            $icms->CST = $item['cst_icms'] ?? '00';
            $icms->modBC = '3';
            $icms->vBC = '0.00';
            $icms->pICMS = floatval($item['pICMS'] ?? 0);
            $icms->vICMS = number_format(($vProd * ($icms->pICMS/100)), 2, '.', '');
            $make->tagICMS($icms);
        }
    }

    // ---------- IPI (stdClass required by your NFePHP)
    if (method_exists($make, 'tagIPI')) {
        $ipi = new \stdClass();
        $ipi->item = $nItem;
        $ipi->clEnq = '';
        $ipi->CNPJProd = '';
        $ipi->cSelo = '';
        $ipi->qSelo = '';
        $ipi->cEnq = '999';
        $ipi->CST = $item['cst_ipi'] ?? $item['produto_cst_ipi'] ?? '99';
        $ipi->vBC = '0.00';
        $ipi->pIPI = '0.00';
        $ipi->vIPI = '0.00';
        $make->tagIPI($ipi);
    }

    // ---------- PIS (PISNT stdClass preferred)
    if (method_exists($make, 'tagPISNT')) {
        $pisnt = new \stdClass();
        $pisnt->item = $nItem;
        $pisnt->CST = $item['cst_pis'] ?? $item['produto_cst_pis'] ?? '01';
        $make->tagPISNT($pisnt);
    } elseif (method_exists($make, 'tagPIS')) {
        // fallback to parameter version
        $make->tagPIS($nItem, $item['cst_pis'] ?? $item['produto_cst_pis'] ?? '99', '0.00', '0.00', '0.00');
    }

    // ---------- COFINS (COFINSNT stdClass preferred)
    if (method_exists($make, 'tagCOFINSNT')) {
        $cofinsnt = new \stdClass();
        $cofinsnt->item = $nItem;
        $cofinsnt->CST = $item['cst_cofins'] ?? $item['produto_cst_cofins'] ?? '01';
        $make->tagCOFINSNT($cofinsnt);
    } elseif (method_exists($make, 'tagCOFINS')) {
        $make->tagCOFINS($nItem, $item['cst_cofins'] ?? $item['produto_cst_cofins'] ?? '99', '0.00', '0.00', '0.00');
    }

    $nItem++;
}

// ---------------- TOTAL (ICMSTot)
$icmstot = new \stdClass();
$icmstot->vBC = '0.00';
$icmstot->vICMS = number_format($nfe['vICMS'] ?? 0, 2, '.', '');
$icmstot->vICMSDeson = '0.00';
$icmstot->vFCP = '0.00';
$icmstot->vBCST = '0.00';
$icmstot->vST = '0.00';
$icmstot->vFCPST = '0.00';
$icmstot->vFCPSTRet = '0.00';
$icmstot->vProd = number_format($total_vProd, 2, '.', '');
$icmstot->vFrete = '0.00';
$icmstot->vSeg = '0.00';
$icmstot->vDesc = '0.00';
$icmstot->vII = '0.00';
$icmstot->vIPI = '0.00';
$icmstot->vIPIDevol = '0.00';
$icmstot->vPIS = '0.00';
$icmstot->vCOFINS = '0.00';
$icmstot->vOutro = '0.00';
$icmstot->vNF = number_format($total_vProd, 2, '.', '');
$make->tagICMSTot($icmstot);

// ---------------- TRANSPORTE
$transp = new \stdClass();
$transp->modFrete = 9;
$make->tagtransp($transp);

// ---------------- COBRANCA (FAT / DUP)
if (method_exists($make, 'tagfat')) {
    $nFat = $nfe['nNF'] ?? '';
    $vOrig = number_format($total_vProd, 2, '.', '');
    $vLiq = $vOrig;
    $make->tagfat($nFat, $vOrig, $vLiq);
    if (method_exists($make, 'tagdup')) {
        $dVenc = date('Y-m-d', strtotime('+30 days'));
        $make->tagdup('001', $dVenc, $vOrig);
    }
}

// ---------------- infAdic
if (!empty($nfe['observacoes']) && method_exists($make, 'taginfAdic')) {
    $make->taginfAdic('', $nfe['observacoes']);
}

// ---------------- Monta/gera XML
$xml = '';
if (method_exists($make, 'montaNFe')) {
    $xml = $make->montaNFe();
} elseif (method_exists($make, 'getXML')) {
    $xml = $make->getXML();
} else {
    die(" Não foi possível gerar XML: método de geração não encontrado.");
}

// Salvar sem assinatura
$xmlDir = __DIR__ . '/xmls';
if (!is_dir($xmlDir)) mkdir($xmlDir, 0777, true);
$arquivo = $xmlDir . "/{$chave}-sem-assinatura.xml";
if (file_put_contents($arquivo, $xml) === false) {
    die(" Erro ao salvar XML em $arquivo. Verifique permissões.");
}

// Sucesso
header('Content-Type: text/html; charset=utf-8');
echo "✔ XML gerado com sucesso!<br>";
echo "🔑 Chave: <b>{$chave}</b><br>";
echo "📄 Arquivo: <a href='xmls/{$chave}-sem-assinatura.xml'>Baixar XML</a><br>";
echo "<hr><h3>Preview (2KB):</h3><pre>" . htmlspecialchars(substr($xml,0,2048)) . "</pre>";

os erros abaixo.. 


Fatal error: Uncaught TypeError: NFePHP\NFe\Make::tagPIS(): Argument #1 ($std) must be of type stdClass, int given, called in C:\xampp\htdocs\madeireira\views\gera_xml.php on line 338 and defined in C:\xampp\htdocs\madeireira\vendor\nfephp-org\sped-nfe\src\Traits\TraitTagDetPIS.php:27 Stack trace: #0 C:\xampp\htdocs\madeireira\views\gera_xml.php(338): NFePHP\NFe\Make->tagPIS(1, '99', '0.00', '0.00', '0.00') #1 C:\xampp\htdocs\madeireira\index.php(194): require('C:\\xampp\\htdocs...') #2 {main} thrown in C:\xampp\htdocs\madeireira\vendor\nfephp-org\sped-nfe\src\Traits\TraitTagDetPIS.php on line 27

uso o xampp.. 

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,5k
    • Posts
      652,4k
×
×
  • Criar Novo...