SPED-NFE

repository·master·Indexed 23 days ago

https://github.com/nfephp-org/sped-nfe

A PHP library for generating, signing, and communicating electronic fiscal documents (NFe and NFCe) with Brazilian SEFAZ authorities. It supports NFe (modelo 55) and NFCe (modelo 65) across all states, including specialized features like Cancellation by Substitution for NFCe and XML protocol merging via the Complements class. Requires PHP 7.4+ and the nfephp-org/sped-common dependency.

Tokens
131.1K
Snippets
218
Records
356
Agent score
80%

What's inside sped-nfe

  1. Overview of supported NFe operations

    master

    The sped-nfe library covers a wide range of fiscal document operations, including:

    • XML Generation: Via Convert::class (from TXT) or Make::class (direct assembly).
    • Contingency: Managing SVC, EPEC, FS-DA, and OFF-LINE modes via Contingency::class.
    • Webservice Interaction: Communicating with SEFAZ servers.
    • Data Handling: Reading and converting XML data into other formats.
    • Document Management: Storage and sending of fiscal documents.
    • DANFE Printing: Supported via external libraries sped-da and posprint.
    • Emailing: Sending documents to recipients via sped-mail.
    • Tax Data: Obtaining tax information via sped-ibpt.
    • GNRE Generation: Generating tax collection guides via sped-gnre.
  2. Understand the SEBRAE NFe v4.00 TXT Layout

    master

    The SEBRAE NFe v4.00 layout is a TXT-based structure used by the SEBRAE issuer. This layout is based on Technical Notes 2016.002 (versions v1.10 through v1.60).

    Important Constraints:

    • Erratic Fields: Some fields do not follow a consistent pattern and may not be covered by the API parser in all conditions.
    • Parser Requirement: While the SEBRAE issuer may omit the pipe separator (|) at the end of some fields, the sped-nfe parser requires ALL fields to end with a pipe (|).
    • Reverse Engineering: This structure was partially obtained via reverse engineering and is subject to errors as there is no official TXT formation manual.
    • Incomplete Conversion: The converter does not yet perform a complete conversion to the SEBRAE standard due to complexity and lack of information.
  3. Understand NFe and NFCe contingency modes

    master

    When the connection to the SEFAZ authorizing authority is unavailable, you can use different contingency modes. Activating any contingency requires the XML to be modified and resigned with the following changes:

    • <tpEmis>: Must indicate the specific contingency mode number.
    • <dhCont>: Date and time of entry into contingency (format with TZD).
    • <xJust>: Justification for entering contingency (between 15 and 256 characters).

    Available Modes:

    ModetpEmisTargetDescriptionUsage
    FS-DA5NFe (mod 55)Uses security forms (DANFE) for printing.No internet or SEFAZ offline. Requires manual sending within 24h.
    SVC-AN6NFe (mod 55)National Virtual Contingency SEFAZ.SEFAZ offline, but issuer has internet. Automatic synchronization.
    SVC-RS7NFe (mod 55)RS Virtual Contingency SEFAZ.SEFAZ offline, but issuer has internet. Automatic synchronization.
    OFF-LINE9NFCe (mod 65)Exclusive to NFCe.No internet or SEFAZ offline. Requires manual sending within 24h.
    EPEC4NFe & NFCeEvento Prévio da Emissão em Contingência.SEFAZ/SVC offline, but issuer has internet. Complex process involving event registration.
  4. EPEC Workflow Reference

    master

    When performing an EPEC operation, follow this logical flow to ensure compliance and data integrity:

    1. Activate Contingency: Use Contingency::activate() to set the state, motive, and type.
    2. Configure Tools: Pass the contingency object to $tools->contingency.
    3. Transmit: Call $tools->sefazEPEC($xml).
    4. Validate Response:
      • The service response cStat must be 128.
      • The event response cStat must be 136.
    5. Persist Data:
      • Use Complements::toAuthorize() to create the protocol XML.
      • Crucial: Save the XML returned/modified by the process, as the chNFe (access key) may have changed.
    6. Finalize: Once SEFAZ is back to normal, transmit the document using the standard (non-contingency) method.
  5. Understand Fundo de Combate à Pobreza (FCP) in NFe 4.0

    master

    The Fundo Estadual de Combate e Erradicação à Pobreza (FECP, FCP, or FECOEP) is a state-level tax in Brazil that acts as an additional percentage applied to the ICMS (Imposto sobre Circulação de Mercadorias e Serviços) rate. It is typically linked to specific products (often identified by NCM) and varies depending on the product type and the destination State (UF).

    In NFe 4.0, specific fields must be used to report the FCP calculation. When dealing with Tax Substitution (ICMS-ST), the FCP rate must be included in the total ICMS-ST rate. For example, if the base ICMS rate is 18% and the FCP is 2%, the rate reported in the pST field should be 20%.

    Important for Interstate Sales:

    • For interstate sales to a final consumer, you must use the vBCFCPUFDest tag to report the FCP calculation base for the destination state.
    • If a GNRE (Guia Nacional de Recolhimento de Tributos Estaduais) is required for ICMS, a separate GNRE must also be generated for the FCP collection.
  6. Federal Mandatory Recipient Manifestation (Manifestação do Destinatário) Rules

    master

    At the federal level, it is mandatory for the recipient to register one of the following events: Confirmação da Operação (Confirmation of Operation), Operação não Realizada (Operation Not Performed), or Desconhecimento da Operação (Unknown Operation) for NF-e transactions that meet these criteria:

    1. Fuel Transactions: Circulation of goods destined for fuel distributors (since 2013) or fuel stations/retailers (since 2013).
    2. Bulk Alcohol: Operations involving alcohol for non-fuel purposes transported in bulk (since 2014).
    3. Wholesale/Distribution of Specific Goods: If the recipient is a distributor or wholesaler, transactions involving cigarettes, alcoholic beverages (including beer/draft beer), soft drinks, and mineral water (since 2015).
  7. Understand CFOP (Fiscal Code of Operations and Services)

    master

    The CFOP (Código Fiscal de Operações e de Prestações) is a mandatory code required for every item in electronic invoices (NFe/NFCe), declarations, guides, and book-keeping.

    It serves three primary purposes:

    1. Taxation: Defines whether the invoice incurs taxes.
    2. Inventory: Dictates how the movement affects stock.
    3. Financial: Influences financial movements.

    When selecting a CFOP, you must consider two main criteria:

    • Type of Operation: Whether it is an entry (entrada) or an exit (saída).
    • Region: The geographic location of the transaction (e.g., within the same state or from another state).

    CFOP is closely related to the product classification and its type within the SPED system.

  8. Convert SEFAZ-standard TXT to XML

    master

    For legacy systems that struggle with XML, you can generate an intermediate TXT file where fields are separated by pipes (|). The library provides the Convert::class to transform these pipe-delimited TXT files into valid NFe XML files. This approach uses a structure derived from reverse-engineering the SEFAZ free issuer to ensure compatibility despite omissions in official manuals.

    For detailed structure information, refer to EstruturaTxt.md. For implementation details, refer to Convert.md.

  9. Understand the Distribution of Fiscal Documents (Distribuição de Documentos Fiscais)

    master

    The ProcEventoNFe functionality handles the return of protocolled events provided by the DFe (Documentos Fiscais Eletrônicos) distribution system. These XML responses represent events manifested by parties involved in a fiscal operation, such as Customers, Suppliers, Carriers, or Tax Authorities (State or Federal).

    Common event types handled in this context include:

    • Cancellation Events (Evento de Cancelamento)
    • Correction Letter Events (Evento de Carta de Correção)
    • Recipient Manifestation Events (Eventos de Manifestação do Destinatário)
    • Suframa Events (Vistoria/Internalização)
    • Deadline Extension Request Events (Eventos de Pedido de Prorrogação de Prazo)
    • Tax Authority Responses to Extension Requests (Eventos do Fisco em Resposta ao Pedido de Prorrogação)
  10. Understand deadlines for Recipient Manifestation (Manifestação do Destinatário)

    master

    The Recipient Manifestation (Manifestação do Destinatário) events have a general deadline for registration, but specific rules apply depending on federal or state legislation.

    • General Rule: Events can generally be registered up to 90 days after the NF-e authorization date.
    • Rectifications: Once an event has been registered for an NF-e, any rectifications can only be performed within 30 days of the first manifestation.

    Note that specific deadlines and mandatory requirements vary by federal segment, state (UF), document value, or the type of operation (e.g., refusal or cancellation).

  11. Understand the XML structure of Recipient Manifestation Events

    master

    When querying or receiving Recipient Manifestation Events (Eventos de Manifestação do Destinatário), the system returns a procEventoNFe XML structure. This structure contains two main parts:

    1. evento: Contains the details of the event itself, including the unique ID (infEvento Id), the event type (tpEvento), the description (descEvento), and the digital signature (Signature).
    2. retEvento: Contains the response information from the tax authority, including the status code (cStat), the reason/message (xMotivo), and the protocol number (nProt).

    Common fields in the response include:

    • chNFe: The NFe access key.
    • tpEvento: The event type code (e.g., 210200 for Operation Confirmation).
    • cStat: The status code of the operation.
    • nProt: The protocol number assigned to the event.
    <?xml version="1.0"?>
    <procEventoNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.00">
      <evento xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.00">
        <infEvento Id="ID...">
          <cOrgao>91</cOrgao>
          <tpAmb>1</tpAmb>
          <CNPJ>89850341000160</CNPJ>
          <chNFe>35161258716523000119550000000439901870176068</chNFe>
          <dhEvento>2016-12-30T19:19:41-02:00</dhEvento>
          <tpEvento>210200</tpEvento>
          <nSeqEvento>1</nSeqEvento>
          <verEvento>1.00</verEvento>
          <detEvento versao="1.00">
            <descEvento>Confirmacao da Operacao</descEvento>
          </detEvento>
        </infEvento>
        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
          <!-- Signature details -->
        </Signature>
      </evento>
      <retEvento xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.00">
        <infEvento Id="ID...">
          <tpAmb>1</tpAmb>
          <verAplic>AN_1.0.0</verAplic>
          <cOrgao>91</cOrgao>
          <cStat>135</cStat>
          <xMotivo>Evento registrado e vinculado a NF-e</xMotivo>
          <chNFe>35161258716523000119550000000439901870176068</chNFe>
          <tpEvento>210200</tpEvento>
          <xEvento>Confirmacao da Operacao</xEvento>
          <nSeqEvento>1</nSeqEvento>
          <CNPJDest>89850341000160</CNPJDest>
          <dhRegEvento>2016-12-30T19:20:00-02:00</dhRegEvento>
          <nProt>891161800271770</nProt>
        </infEvento>
      </retEvento>
    </procEventoNFe>
  12. Structure the PAG tag and its details (detPag)

    master

    In Layout 4.00, the payment information is structured using a single <pag> tag which can contain up to 100 <detPag> (payment detail) tags. This allows for splitting a single transaction across multiple payment methods (e.g., part cash, part credit card).

    Key components:

    • <pag>: The parent container for all payment information. It can include an optional <vTroco> (change amount) field.
    • <detPag>: Individual payment details. Each detail includes the payment type (tPag), value (vPag), and indicator if it is a cash payment (indPag).
    • <card>: For certain payment types (like credit cards), a <card> sub-element is required within <detPag> to provide integration type (tpIntegra), CNPJ, card brand (tBand), and authorization code (cAut).
    <pag>
        <detPag>
            <indPag>0</indPag>
            <tPag>01</tPag>
            <vPag>100.00</vPag>
        </detPag>
        <detPag>
            <indPag>0</indPag>
            <tPag>03</tPag>
            <vPag>100.00</vPag>
            <card>
                <tpIntegra>1</tpIntegra>
                <CNPJ>05577343000137</CNPJ>
                <tBand>02</tBand>
                <cAut>20010afsct</cAut>
            </card>
        </detPag>
        <vTroco>1.00</vTroco>
    </pag>