Guide · Tax

What to check in a Mexican e-invoice (CFDI) before paying it: what the XML tells you and what it does not

Six checks on the XML of a Mexican e-invoice (CFDI) before paying it, with Python code, and three things the XML cannot tell you.

OrigoID team Published on 6 min read Leer en español
In this guide
  1. What is inside a CFDI
  2. Six checks that come from the XML
  3. The code
  4. What the XML does not tell you
  5. Five common mistakes
  6. In short
  7. Sources

In Mexico an invoice is a CFDI: an XML file carrying the issuer's seal and a stamp certified by SAT, the tax authority. The PDF that comes with it is only a printed representation. If your system pays supplier invoices, the XML is what you need to check.

Before paying you can verify six things from the file alone, without calling anyone. There are three more the file cannot tell you, and it helps to know which ones.

If you only came for the list:

  1. It is a CFDI 4.0 and it is stamped.
  2. It is made out to you.
  3. It was issued by the supplier you expected.
  4. The totals add up.
  5. The invoice type and the payment method are the right ones.
  6. If it is in another currency, it carries an exchange rate.

What the XML does not say: whether the invoice is still valid, whether the issuer is on SAT's 69-B list, and whether the seal is authentic.

What is inside a CFDI

The root node is called Comprobante and lives in the namespace http://www.sat.gob.mx/cfd/4. What matters for paying:

Where Attribute What it is
Comprobante Version Always 4.0
Comprobante SubTotal, Descuento, Total The amounts (Descuento is the discount)
Comprobante Moneda, TipoCambio The currency and, if it is not pesos, its exchange rate
Comprobante TipoDeComprobante I income, E credit note, T transfer, N payroll, P payment
Comprobante MetodoPago PUE paid in full at once, PPD in installments or deferred
Emisor Rfc Who issues the invoice
Receptor Rfc Who it is issued to
Impuestos TotalImpuestosTrasladados, TotalImpuestosRetenidos Taxes charged and taxes withheld
Complemento → TimbreFiscalDigital UUID The fiscal folio: 36 characters

The stamp is not in the same namespace as the rest: it uses http://www.sat.gob.mx/TimbreFiscalDigital. If you look for it under the invoice's namespace, you will not find it.

Six checks that come from the XML

1. It is a CFDI 4.0 and it is stamped. SAT's schema fixes Version at 4.0. And the invoice must carry the TimbreFiscalDigital node with its UUID. An XML without a stamp is a draft: it was never certified and it is not an invoice.

2. It is made out to you. The Rfc of the Receptor must be yours, character by character. In version 4.0 the receiver also carries name, tax-address postal code and tax regime as required fields.

3. It was issued by the supplier you expected. Compare the Rfc of the Emisor with the RFC in your supplier records. Do not compare names: a name can be written many ways, and an RFC cannot.

4. The totals add up. The schema defines Total as the subtotal, minus discounts, plus taxes charged, minus taxes withheld, federal and local. Local taxes, when present, come in their own complement (ImpuestosLocales).

5. The type and the payment method are the right ones. An invoice you are about to pay is type I. If the method is PPD, the story does not end with your payment: rule 2.7.1.32 of Mexico's annual tax rules requires the supplier to issue you a type P CFDI afterwards, with the payment-receipt complement, no later than the fifth calendar day of the following month. Without it your file is incomplete.

6. If it is in another currency, it carries an exchange rate. The schema requires it when the currency is neither MXN nor XXX.

The code

Python standard library only.

Python
"""Offline checks on a CFDI 4.0 before paying it. It never calls SAT."""
import re
import xml.etree.ElementTree as ET
from decimal import Decimal, InvalidOperation

CFDI = "{http://www.sat.gob.mx/cfd/4}"
TFD = "{http://www.sat.gob.mx/TimbreFiscalDigital}"
LOCAL = "{http://www.sat.gob.mx/implocal}"
UUID_RE = re.compile(r"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}")


def _amount(node, name):
    """An amount attribute as Decimal; a missing node or attribute counts as zero."""
    return Decimal(node.get(name, "0")) if node is not None else Decimal(0)


def review_cfdi(xml_bytes, my_rfc, supplier_rfc):
    """Return a list of (level, message). level is "error" or "warning".

    An empty list means these checks found nothing. It does not mean the
    invoice is still valid: only SAT can say whether it was cancelled.
    """
    try:
        root = ET.fromstring(xml_bytes)
    except ET.ParseError:
        return [("error", "not well-formed XML")]
    if root.tag != CFDI + "Comprobante" or root.get("Version") != "4.0":
        return [("error", "not a CFDI 4.0")]

    found = []
    complement = root.find(CFDI + "Complemento")
    stamp = complement.find(TFD + "TimbreFiscalDigital") if complement is not None else None
    if stamp is None:
        found.append(("error", "no fiscal stamp: this XML was never certified"))
    elif not UUID_RE.fullmatch(stamp.get("UUID", "")):
        found.append(("error", "the UUID is not a fiscal folio"))

    issuer, receiver = root.find(CFDI + "Emisor"), root.find(CFDI + "Receptor")
    if issuer is None or issuer.get("Rfc") != supplier_rfc:
        found.append(("error", "the issuer is not the supplier you expected"))
    if receiver is None or receiver.get("Rfc") != my_rfc:
        found.append(("error", "the invoice is not made out to you"))

    if root.get("TipoDeComprobante") != "I":
        found.append(("warning", "not an income invoice (type I)"))

    try:
        taxes = root.find(CFDI + "Impuestos")  # direct child: the invoice totals
        local = complement.find(LOCAL + "ImpuestosLocales") if complement is not None else None
        expected = (
            _amount(root, "SubTotal") - _amount(root, "Descuento")
            + _amount(taxes, "TotalImpuestosTrasladados") - _amount(taxes, "TotalImpuestosRetenidos")
            + _amount(local, "TotaldeTraslados") - _amount(local, "TotaldeRetenciones")
        )
        if expected != _amount(root, "Total"):
            found.append(("error", f"the totals do not add up: {expected} expected, {root.get('Total')} stated"))
    except InvalidOperation:
        found.append(("error", "an amount is not a number"))

    if root.get("Moneda") not in ("MXN", "XXX") and root.get("TipoCambio") is None:
        found.append(("error", "foreign currency without an exchange rate"))
    if root.get("MetodoPago") == "PPD":
        found.append(("warning", "deferred or partial payment: expect a payment receipt (type P) after you pay"))
    return found

With an invoice whose total was edited by hand and which is paid in installments:

Python
>>> review_cfdi(xml_bytes, "CEJ150101XX1", "PEJ200202AB3")
[('error', 'the totals do not add up: 1160.00 expected, 1060.00 stated'),
 ('warning', 'deferred or partial payment: expect a payment receipt (type P) after you pay')]

Three choices in the code:

Why check the sums if whoever stamped it already validated them? Because an XML is text. Anyone can open it, change the Total and send it again. The seal no longer matches, but checking it is a lot more work. The sum catches the crudest edit in five lines.

Tested with 13 cases: clean invoice, edited total, discount with withholding, local taxes, no stamp, malformed UUID, wrong issuer or receiver, type P, method PPD, foreign currency with and without an exchange rate, an amount that is not a number, and files that are not a CFDI 4.0.

What the XML does not tell you

Whether the invoice is still valid. An invoice can be cancelled after it is issued. Article 29-A of the Federal Tax Code allows it up to the month in which the annual return for the year of issue is filed, provided the receiver accepts the cancellation. The file you have stored does not change when that happens. Article 29 says where the authenticity of an invoice is checked: on SAT's website. Check when you receive the invoice and again before paying.

Whether the issuer is on the 69-B list. When a supplier lands on the definitive list of simulated transactions, its invoices lose their tax effect, including the ones you already received. The issuer's RFC comes from the XML; the list does not. We cover it in Mexico's SAT blacklists for developers.

Whether the seal is authentic. The invoice carries the issuer's digital seal (Sello) and the stamp carries SAT's (SelloSAT). Checking them means rebuilding the original string and validating signatures against certificates, which is beyond this article. Even so, a valid seal only proves the file was not altered; it does not prove the invoice is still valid.

Five common mistakes

  1. Keeping the PDF and throwing away the XML. The PDF is not the invoice.
  2. Using float for amounts.
  3. Comparing names instead of RFCs.
  4. Checking only once. Weeks can pass between receiving an invoice and paying it, and it can be cancelled in that time.
  5. Paying a PPD invoice and not asking for the payment receipt.

In short

Sources

Related services

Keep reading

All guides ›
Tax SAT Article 69 vs 69-B: differences, Mexico

How SAT's Article 69 lists and the 69-B list differ in Mexico, what risk each one covers and six common mistakes when integrating them.

7 min
Tax Validate a Mexican RFC: SAT regex and check digit

Offline validation of Mexico's RFC tax ID: the pattern SAT publishes, the date and the check digit, and why a mismatch is not a reason to reject.

9 min
For developers Mexican identity verification with MCP

From zero to a service that validates Mexico's CURP with OrigoID's API using its MCP server in Claude Code, and the design choices that make it fast.

5 min
Start free, no card.

Courtesy credits to try it with your own data. Access is enabled after a brief validation of your company.

Request access