Documentation Index
Fetch the complete documentation index at: https://mintlify.com/eclipxe13/CfdiUtils/llms.txt
Use this file to discover all available pages before exploring further.
CfdiCreator40 is the primary high-level API for generating CFDI version 4.0 XML documents in PHP. It acts as a “glue” object that brings together the CfdiUtils\Elements\Cfdi40\Comprobante element tree, the XML resolver, the XSLT cadena-de-origen builder, the certificate management, and the validation pipeline into a single, easy-to-use class.
Rather than manually constructing XML nodes, you work with typed element helpers (addEmisor, addReceptor, addConcepto, etc.) and let CfdiCreator40 handle serialization, signing, and XSD validation. Under the hood it implements CertificadoPropertyInterface, XmlResolverPropertyInterface, and XsltBuilderPropertyInterface through the shared CfdiCreatorTrait.
CFDI 4.0 is the current SAT standard for electronic invoicing in Mexico. All new development should target CFDI 4.0. See CFDI 3.3 (Legacy) if you need to maintain an older integration.
Constructor
Key/value pairs that are set as attributes on the root
cfdi:Comprobante element. Typical keys include Serie, Folio, Fecha, FormaPago, SubTotal, Total, TipoDeComprobante, etc. Fixed attributes such as Version, xmlns:cfdi, and xsi:schemaLocation are set automatically.An optional
CfdiUtils\Certificado\Certificado instance. When provided, the constructor immediately calls putCertificado() to populate NoCertificado, Certificado, and (by default) the Emisor RFC and name from the certificate. Can be passed later via putCertificado().Controls where XSD/XSLT resources are resolved and cached locally. Defaults to a new
XmlResolver with the standard SAT remote resources. Pass null explicitly only if you later call setXmlResolver(null) — note that this disables cadena-de-origen generation and most validators.The engine used to apply the SAT XSLT stylesheet and produce the cadena de origen string. Defaults to
CfdiUtils\CadenaOrigen\DOMBuilder. Override this if you need a custom XSLT processor.Helper Methods
comprobante(): Comprobante
Returns the root CfdiUtils\Elements\Cfdi40\Comprobante element. Every other operation on the document structure goes through this object. All typed helper methods (addEmisor, addReceptor, addConcepto, etc.) are exposed on this element.
putCertificado(Certificado $certificado, bool $putEmisorRfcNombre = true): void
Sets the NoCertificado and Certificado attributes on the comprobante using the serial number and PEM content of the certificate. When $putEmisorRfcNombre is true (the default), it also writes the Rfc and Nombre attributes on the Emisor node — stripping the capital-regime suffix from the name when the RFC is 12 characters long and the document version is 4.0.
A loaded
CfdiUtils\Certificado\Certificado instance pointing to your CSD .cer file.When
true, the Emisor’s Rfc and Nombre are taken from the certificate automatically. Set to false when you need to supply those values manually.asXml(): string
Serializes the entire comprobante element tree to an XML string and returns it. Uses CfdiUtils\Nodes\XmlNodeUtils::nodeToXmlString() internally. Call this after addSello() to obtain the final signed XML.
saveXml(string $filename): bool
Writes the output of asXml() to a file. Returns true on success, false on failure (mirrors file_put_contents).
Absolute or relative filesystem path where the XML file should be saved.
buildCadenaDeOrigen(): string
Applies the SAT XSLT stylesheet for CFDI 4.0 to the current XML, producing the cadena de origen string that is later hashed and signed. Throws \LogicException if no XSLT builder is configured.
buildSumasConceptos(int $precision = 2): SumasConceptos
Creates and returns a CfdiUtils\SumasConceptos\SumasConceptos object calculated from the Conceptos already added to the comprobante. Useful when you need to inspect the computed totals before writing them to the document.
Number of decimal places used when rounding monetary amounts.
addSumasConceptos(?SumasConceptos $sumasConceptos = null, int $precision = 2): void
Computes the document totals and writes them back to the comprobante. When $sumasConceptos is null, it calls buildSumasConceptos($precision) internally. The values written include SubTotal, Total, Descuento, the Impuestos node at the comprobante level, and the TotaldeRetenciones/TotaldeTraslados fields of the local-tax complement when present.
A pre-built
SumasConceptos object, or null to have the method calculate it automatically.Decimal precision forwarded to
buildSumasConceptos() when $sumasConceptos is null.addSello(string $key, string $passPhrase = ''): void
Signs the document. Internally it calls buildCadenaDeOrigen(), signs the resulting string with SHA-256 using the provided PEM private key, and stores the Base64-encoded result in the Sello attribute of the comprobante. If a certificate was previously set, it verifies that the key belongs to that certificate before signing.
The PEM private key content or a
file:// URI pointing to a PEM-formatted .key file. Example: 'file:///path/to/key.pem'.The passphrase protecting the private key. Leave empty if the key is unencrypted.
validate(): Asserts
Runs the full CFDI 4.0 validation suite (MultiValidatorFactory::newCreated40()), which includes XSD schema validation plus additional CfdiUtils business-rule validators. Returns a CfdiUtils\Validate\Asserts collection. Check $asserts->hasErrors() before proceeding to seal or store the document.
moveSatDefinitionsToComprobante(): void
Moves all xmlns:* namespace declarations and xsi:schemaLocation values that live on child nodes up to the root cfdi:Comprobante element. The SAT technical specification lists this as required, even though standard XML allows namespace declarations anywhere in the tree.
Call
moveSatDefinitionsToComprobante() after adding all complements and before saving or transmitting the XML. Namespace locations do not participate in cadena-de-origen generation, so this step does not invalidate an existing Sello.Creation Recipe
The typical CFDI 4.0 creation workflow follows these steps:Full Working Example
The following self-contained example demonstrates a minimal but complete CFDI 4.0 income invoice:Comprobante Node Methods
Once you have theComprobante element from $creator->comprobante(), the most commonly used helper methods are:
| Method | Description |
|---|---|
addEmisor(array $attributes): Emisor | Creates or updates the single Emisor node. |
addReceptor(array $attributes): Receptor | Creates or updates the single Receptor node. |
addConcepto(array $attributes): Concepto | Appends a new Concepto child inside Conceptos. Returns the Concepto element so you can chain .addTraslado() or .addRetencion() directly. |
addComplemento(NodeInterface $node): Comprobante | Inserts $node inside the Complemento wrapper element. |
addCfdiRelacionados(array $attributes): CfdiRelacionados | Adds a CfdiRelacionados node for related documents. |
addInformacionGlobal(array $attributes): InformacionGlobal | Adds global invoice information (used for simplified invoices). |
Using phpcfdi/credentials
The SAT delivers CSD files as a .cer certificate and a binary .key file. The companion library phpcfdi/credentials provides a convenient way to load both:
XML Resource Resolver
TheXmlResolver manages local caching of SAT XSD and XSLT files. The default resolver downloads resources from the SAT’s public servers and stores them in a local cache directory. You can customise this: