Verifactu in Magento: how to connect Magento 2 with the Verifactu API

Verifacti has no official Magento extension: Magento 2 connects to the Verifactu API with your own module whose observer, when an invoice is paid, sends it as JSON and gets the QR back. No XML to generate, no hash to compute and no digital certificate: Verifacti sends the invoicing record to the AEAT as a colaborador social. In Álava, Bizkaia and Gipuzkoa, the same pattern works with the TicketBAI API.

Test environment and test NIF included
Read the documentation

Which APIs you need for Magento

Your connector uses two pieces: the submission API that matches the NIF (Verifactu API in common territory; TicketBAI API in Álava, Bizkaia and Gipuzkoa) and the NIF management API, integrated once to register the NIF, manage the representation form and receive webhooks. Each NIF uses one API or the other depending on where it is taxed.

Test environment and test NIF included

How to connect Magento with the API

Flow: paid invoice in Magento 2 (sales_order_invoice_save_commit_after event) → your module → Verifactu API or TicketBAI API → AEAT or foral treasury.

  1. Register the NIF with the NIF management API and sign the representation form. Each NIF has its own API key.
  2. Create a module with an observer for sales_order_invoice_save_commit_after in etc/events.xml: it fires once the invoice is saved and has its number.
  3. Build the invoice from the Invoice and call POST /verifactu/create.
  4. Store uuid, qr and huella and add the QR to the invoice PDF.

Do you build software and want to offer Verifactu to your customers? See invoicing software.

Example: from the paid invoice to the record

The observer only acts on paid invoices, uses the Magento invoice number (increment_id) and groups the lines and shipping (with its discount) by VAT rate. The shipping rate is snapped to the nearest valid rate, because Magento only stores the rounded tax amount.

Observer/InvoicePaid.php · Magento 2.4.4+
<?php
// app/code/Verifacti/Verifactu/Observer/InvoicePaid.php · Magento 2.4.4+ (PHP 8).
// Registrado en etc/events.xml para el evento sales_order_invoice_save_commit_after, que llega cuando
// la factura ya está guardada y tiene número (sales_order_invoice_pay llega antes de que lo tenga):
//   <event name="sales_order_invoice_save_commit_after"><observer name="verifacti_invoice_paid" instance="Verifacti\Verifactu\Observer\InvoicePaid"/></event>
// La API key va en app/etc/env.php como 'verifacti' => ['api_key' => 'vf_test_...'].

namespace Verifacti\Verifactu\Observer;

use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Sales\Model\Order\Invoice;
use Psr\Log\LoggerInterface;

class InvoicePaid implements ObserverInterface
{
    private const TIPOS = [0, 4, 10, 21];

    public function __construct(
        private Curl $curl,
        private DeploymentConfig $config,
        private LoggerInterface $logger
    ) {
    }

    public function execute(Observer $observer): void
    {
        /** @var Invoice $invoice */
        $invoice = $observer->getEvent()->getInvoice();
        if ($invoice->getState() != Invoice::STATE_PAID) {
            return;
        }

        $cuerpo = json_encode($this->factura($invoice));
        $this->curl->setHeaders([
            'Authorization' => 'Bearer ' . $this->config->get('verifacti/api_key'),
            'Content-Type' => 'application/json',
            'Idempotency-Key' => 'magento-' . $invoice->getIncrementId() . '-' . substr(hash('sha256', $cuerpo), 0, 12),
        ]);
        $this->curl->setTimeout(30);
        $this->curl->post('https://api.verifacti.com/verifactu/create', $cuerpo);

        $registro = json_decode($this->curl->getBody(), true);
        if ($this->curl->getStatus() !== 200) {
            $this->logger->error('Verifactu ' . $invoice->getIncrementId(), $registro ?? []);
            return;
        }
        $this->logger->info('Verifactu ' . $invoice->getIncrementId() . ': registro ' . $registro['uuid']);
        // Guarda $registro['uuid'], $registro['qr'] y $registro['huella'] en tu tabla para el PDF de la factura
        // (no vuelvas a guardar la factura aquí: dispararía este mismo evento)
    }

    private function factura(Invoice $invoice): array
    {
        $porTipo = [];
        foreach ($invoice->getAllItems() as $item) {
            if ($item->getOrderItem()->getParentItem()) {
                continue;
            }
            // Si aplicas el descuento sobre precios con IVA, resta también getDiscountTaxCompensationAmount()
            $tipo = (string) (float) $item->getOrderItem()->getTaxPercent();
            $porTipo[$tipo]['base'] = ($porTipo[$tipo]['base'] ?? 0) + $item->getRowTotal() - $item->getDiscountAmount();
            $porTipo[$tipo]['cuota'] = ($porTipo[$tipo]['cuota'] ?? 0) + $item->getTaxAmount();
        }
        $envio = $invoice->getShippingAmount() - (float) $invoice->getOrder()->getShippingDiscountAmount();
        if ($envio > 0) {
            $tipo = (string) $this->tipoValido($invoice->getShippingTaxAmount() / $envio * 100);
            $porTipo[$tipo]['base'] = ($porTipo[$tipo]['base'] ?? 0) + $envio;
            $porTipo[$tipo]['cuota'] = ($porTipo[$tipo]['cuota'] ?? 0) + $invoice->getShippingTaxAmount();
        }

        $direccion = $invoice->getBillingAddress();
        $nif = $direccion->getVatId();
        $factura = [
            'serie' => 'MAG-',
            'numero' => $invoice->getIncrementId(),
            'fecha_expedicion' => date('d-m-Y'),
            'tipo_factura' => $nif ? 'F1' : 'F2',
            'descripcion' => 'Pedido ' . $invoice->getOrder()->getIncrementId(),
            'lineas' => [],
            'importe_total' => number_format((float) $invoice->getGrandTotal(), 2, '.', ''),
        ];
        if ($nif) {
            $factura['nif'] = preg_replace('/^ES/', '', $nif);
            $factura['nombre'] = $direccion->getCompany() ?: $direccion->getName();
        }
        foreach ($porTipo as $tipo => $l) {
            $factura['lineas'][] = [
                'base_imponible' => number_format($l['base'], 2, '.', ''),
                'tipo_impositivo' => $tipo,
                'cuota_repercutida' => number_format($l['cuota'], 2, '.', ''),
            ];
        }
        return $factura;
    }

    // El tipo del envío se deduce de la cuota redondeada (4,95 € → 21,01 %): se ajusta al tipo válido más cercano
    private function tipoValido(float $tipo): float
    {
        $mejor = self::TIPOS[0];
        foreach (self::TIPOS as $t) {
            if (abs($t - $tipo) < abs($mejor - $tipo)) {
                $mejor = $t;
            }
        }
        return $mejor;
    }
}

The code groups the lines by VAT rate and uses F1 if the customer has a NIF and F2 otherwise. It sends the Idempotency-Key header with the invoice identifier plus a digest of the body: an identical retry never duplicates the invoice and, if you fix the data after an error, the key changes. The response carries the uuid, the state (Pendiente: the submission to the AEAT is queued), the verification URL, the QR in Base64 and the hash: store them with the invoice.

More code in the Verifactu tutorial in PHP. For TicketBAI, the call goes to POST /ticketbai/create with the foral NIF's API key: the fields, in the TicketBAI API documentation.

Special cases in Magento

Special cases when invoicing from Magento
CaseWhat to doRead more
NumberingEvery invoice needs a series with sequential numbering. If invoice numbers can have gaps, give the invoice its own numberVerifactu requirements
Customer without a NIFSimplified invoice (F2), without nif or nombre. The API rejects an F2 above €3,000 (vf-verifactu-f2_limite_3000)Simplified invoice
Return or refundCorrective invoice: R5 if the original was simplified; R1–R4 if it was a full invoiceCorrective invoices
Customer asks for a full invoice laterExchange invoice (F3) replacing the simplified oneExchange invoice
Canary Islands, Ceuta and MelillaIGIC or IPSI in the lines (impuesto field), not VATIGIC · IPSI
Products without VATCheck whether they are exempt (operacion_exenta) or not subject (calificacion_operacion): they are not sent at rate 0Exempt invoice
CancellationOnly for invoices that should never have been issued: POST /verifactu/cancelCancellation
Sale to another EU countryIt depends on whether the customer is a business and on the distance-selling thresholdIntra-EU examples
Several companies or shopsOne NIF per company, each with its own API keyNIF management API

Dates

The first row only applies if you build the connector to sell it: then you sell invoicing software. For those who invoice, the Verifactu dates are published in the BOE and the postponement to October 2028 is announced with no rule published. In Álava, Bizkaia and Gipuzkoa, TicketBAI is in force.

Producers and resellers of invoicing softwareSince 29 Jul 2025
RDL 15/2025 did not change this date.
In force
Corporate Income Tax payers1 Jan 2027
Published in the BOE, future date
Everyone else, including the self-employed1 Jul 2027
Published in the BOE, future date
Postponement of the pending obligationsOct 2028
The note does not specify the scope for businesses invoicing over €8M.
Announced, no rule published
TicketBAI in Álava: foral taxpayersSince 1 Dec 2022
Phased from 1 April 2022; all other taxpayers since 1 December 2022.
In force
Batuz in Bizkaia (TicketBAI and LROE): all taxpayersSince 1 Jan 2026
Companies that are not SMEs since 1 January 2024; everyone else in windows on 1 July 2024, 1 January 2025, 1 July 2025 and 1 January 2026.
In force
TicketBAI in Gipuzkoa: foral taxpayersSince 1 Jun 2023
Phased by activity from 1 July 2022.
In force

This is not advice: each taxpayer determines what applies to them with their adviser.

More detail in Verifactu dates and TicketBAI.

Pricing

Public tariff of the Verifactu API and the TicketBAI API: you pay per NIF active in production, VAT excluded. Custom per-NIF pricing is available for volume.

From

€14.99

per month for the first NIF active in production, VAT excluded

See all pricing
  • The price per NIF goes down with every tier.
  • Free test environment and test NIF.
  • Annual plan with a 10% discount, no setup fees.
  • Up to 3,000 invoicing records per month per NIF.
  • Startup plan for companies under 12 months old, with under €100,000 in revenue and under €200,000 in funding.
  • Same price with the Verifactu API and the TicketBAI API: each NIF uses one or the other depending on where it is taxed.
  • Online signing of the representation form: €2.90 + VAT per signature.

Questions about Verifactu and Magento

More questions about Verifactu

Is there an extension from Verifacti for Magento?

No. Verifacti is an API: Magento connects to it with the code on this page, in your own development. There are third-party extensions in the Adobe Commerce Marketplace.

Does Magento comply with Verifactu on its own?

It depends on your version and what you have installed: check with your provider. Whoever invoices needs a system that generates the invoicing records and sends them to the AEAT. Which obligation each business has depends on its case: who Verifactu applies to.

Does it work for TicketBAI too?

Yes. If the NIF is taxed in Álava, Bizkaia or Gipuzkoa, the flow is the same with the TicketBAI API: the endpoint (/ticketbai/create), the invoice fields and the API key change.

Do I need a digital certificate?

No. Verifacti is an AEAT social collaborator and submits with its own certificate once the taxpayer signs the representation form, the same one for the AEAT and the foral treasuries. It can be signed online, without a certificate.

How much does it cost?

From €14.99 per month for the first NIF active in production, VAT excluded, with the Verifactu API or the TicketBAI API. The test environment and test NIF are free. Every plan, in pricing.

Connect Magento in the test environment

Create your free account and try the API with a test NIF before going to production.

Test environment and test NIF includedRead the documentation