verifactu

package module
v0.43.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: AGPL-3.0 Imports: 34 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GOBL to VeriFactu

Go library to convert GOBL invoices into VeriFactu declarations and send them to the AEAT (Agencia Estatal de Administración Tributaria) web services. This library assumes that clients will handle a local database of previous invoices in order to comply with the local requirements of chaining all invoices together.

Released under the Apache 2.0 LICENSE, Copyright 2021-2025 Invopop S.L..

Lint Test Go Go Report Card codecov GoDoc Latest Tag Ask DeepWiki

Addon

This module provides the es-verifactu-v1 GOBL addon, in addon/. It defines the extensions, normalizers, scenarios and validation rules that adapt a GOBL document to VeriFactu, for both the VERIFACTU and NO VERIFACTU modalities.

The addon lived in GOBL core until it moved here, alongside the converter that is its main consumer. It registers itself on import, so a consumer that processes documents declaring es-verifactu-v1 needs a blank import:

import _ "github.com/invopop/gobl.es.verifactu/addon"

This is required, not optional: GOBL refuses to Calculate or Validate a document whose $addons names an addon that is not loaded, so that a document is never processed without the rules its $addons promise.

NO VERI*FACTU events

Event registrations are built from a bill.Status document. Core GOBL status line keys describe the situation of a business document, so a NO VERI*FACTU event uses the other key and carries its event type in the es-verifactu-event-type extension, holding a code from the L2E list:

lines:
  - key: "other"
    ext:
      es-verifactu-event-type: "01" # invoicing system startup

Until this changed, each event type had its own status line key (system-startup, invoice-anomaly, and so on). Those keys are migrated onto the extension automatically during Calculate, so previously issued documents keep working. The one exception is the legacy other key, which meant code 90: it cannot be told apart from the other key every line now carries, so it is reported rather than guessed at, and must set the extension explicitly.

Fault codes

All rules report under a single GOBL-ES-VERIFACTU namespace, with the set component saying which rules rejected the document:

Example Rules
GOBL-ES-VERIFACTU-BILL-INVOICE-02 Invoices
GOBL-ES-VERIFACTU-BILL-STATUS-01 Status events
GOBL-ES-VERIFACTU-INVOICEANOMALY-01 Event complements

Invoice processing is identical under VERIFACTU and NO VERIFACTU, so there is no namespace per modality: it would imply a split the invoice rules do not have. Status documents are the only modality-specific surface, and BILL-STATUS already identifies them.

The status and complement rules previously reported under a bare NOVERIFACTU namespace, from a rule set held outside the addon that only this library invoked. The set and assertion parts are unchanged, so NOVERIFACTU-BILL-STATUS-01 is now GOBL-ES-VERIFACTU-BILL-STATUS-01. Anything matching on the old codes needs updating.

Source

English is used for the principal actions inside this package, however a large amount of code is still in Spanish. We're working on translating, but this project may still be combersome to use if you do not understand Spanish.

The main resources used in this module include:

Usage

Go Package

You must have first created a GOBL Envelope containing an Invoice that you'd like to send to the AEAT. For the document to be converted, the supplier contained in the invoice should have a "Tax ID" with the country set to ES.

The following is an example of how the GOBL VeriFactu package could be used:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/invopop/gobl"
	verifactu "github.com/invopop/gobl.es.verifactu"
	"github.com/invopop/xmldsig"
)

func main() {
	ctx := context.Background()

	// Load sample envelope:
	data, _ := os.ReadFile("./test/data/sample-invoice.json")
	env := new(gobl.Envelope)
	if err := json.Unmarshal(data, env); err != nil {
		panic(err)
	}

	// VeriFactu requires a software definition to be provided. This is an example
	software := &verifactu.Software{
		NombreRazon:              "Company S.L.",    // Company Name
		NIF:                      "B123456789",     // Software company's tax code
		NombreSistemaInformatico: "Software Name",  // Name of application
		IdSistemaInformatico:     "A1",             // Software ID
		Version:                  "1.0",            // Software version
		NumeroInstalacion:        "00001",          // Software installation number
	}

	// Load the certificate
	cert, err := xmldsig.LoadCertificate(
		"./path/to/certificate.p12",
		"password",
	)
	if err != nil {
		panic(err)
	}

	// Create the client with the software and certificate
	opts := []verifactu.Option{
		verifactu.WithCertificate(cert),
		verifactu.InTesting(),          // Use the testing environment
	}
	vc, err := verifactu.New(software, opts...)
	if err != nil {
		panic(err)
	}

	// Prepare previous chain data. Ideally you want to do this from
	// your own database.
	prevData, err := os.ReadFile("./path/to/previous_invoice.json")
	if err != nil {
		panic(err)
	}
	prev := new(verifactu.ChainData)
	if err := json.Unmarshal([]byte(prevData), prev); err != nil {
		panic(err)
	}

	// Generate a registration document and update the envelope.
	reg, err := vc.RegisterInvoice(env)
	if err != nil {
		panic(err)
	}

	inv := env.(*bill.Invoice)
	ir, err := vc.InvoiceRequest(inv.Supplier)
	if err != nil {
		panic(err)
	}
	inv.AddRegistration(reg)

	// Send the document to the tax agency
	out, err = vc.SendInvoiceRequest(ctx, ir)
	if err != nil {
		panic(err)
	}
	line := out.Lines[0]

	// Print the data to be used as previous document chain for the next invoice
	// Persist the data somewhere to be used by the next invoice
	cd, err := json.Marshal(line.ChainData())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Generated document with fingerprint: \n%s\n", string(cd))

}
Checking records

verifactu.ParseRecord(data) reads back a stored invoice registration, cancellation or event record and recomputes its fingerprint, which differs from the one in the record when a field it covers was altered. It does not check the signature.

Command Line

The GOBL VeriFactu package tool also includes a command line helper. You can install manually in your Go environment with:

go install github.com/invopop/gobl.es.verifactu/cmd/gobl.verifactu@latest

We recommend using a .env file to prepare configuration settings, although all parameters can be set using command line flags. Heres an example:

SOFTWARE_COMPANY_NIF=B85905495
SOFTWARE_COMPANY_NAME=Invopop S.L.
SOFTWARE_NAME=gobl.verifactu
SOFTWARE_VERSION=1.0
SOFTWARE_ID_SISTEMA_INFORMATICO=A1
SOFTWARE_NUMERO_INSTALACION=00001
DEBUG=true
CERTIFICATE_PATH=xxxxxxxxx
CERTIFICATE_PASSWORD=xxxxxxxxx

To convert a document to XML, run:

gobl.verifactu convert ./test/data/sample-invoice.json

This function will output the XML to the terminal, or to a file if a second argument is provided. The output file will not include a fingerprint, and therefore will not be able to be submitted to the tax agency.

To submit to the tax agency testing environment:

gobl.verifactu send ./test/data/sample-invoice.json ./test/data/previous-invoice-info.json

Now, the output file will include a fingerprint, linked to the previous document, and will be submitted to the tax agency. An example for a previous file would look like this:

{
  "emisor": "B12345678",
  "serie": "SAMPLE-001",
  "fecha": "2024-11-28",
  "huella": "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"
}

Tax Extensions

The following extensions must be included in the document. Note that the GOBL addon will automatically add these extensions when processing invoices:

  • es-verifactu-doc-type – defines the type of invoice being sent. In most cases this will be set automatically by GOBL, but it must be present. It is taken from list L2 of the VeriFactu Ministerial Order. These are the valid values:

    • F1 - Standard invoice.
    • F2 - Simplified invoice.
    • F3 - Invoice in substitution of simplified invoices.
    • R1 - Rectified invoice based on law and Article 80.1, 80.2 and 80.6 in the Spanish VAT Law.
    • R2 - Rectified invoice based on law and Article 80.3.
    • R3 - Rectified invoice based on law and Article 80.4.
    • R4 - Rectified invoice based on law and other reasons.
    • R5 - Rectified invoice based on simplified invoices.
  • es-verifactu-op-class - Operation classification code used to identify if taxes should be applied to the line. It is taken from list L9 of the VeriFactu Ministerial Order. These are the valid values:

    • S1 - Subject and not exempt - Without reverse charge
    • S2 - Subject and not exempt - With reverse charge. Known as Inversión del Sujeto Pasivo in Spanish VAT Law
    • N1 - Not subject - Articles 7, 14, others
    • N2 - Not subject - Due to location rules
  • es-verifactu-exempt - Exemption code used to identify if the line item is exempt from taxes. It is taken from list L10 of the VeriFactu Ministerial Order. These are the valid values:

    • E1 - Exempt pursuant to Article 20 of the VAT Law
    • E2 - Exempt pursuant to Article 21 of the VAT Law
    • E3 - Exempt pursuant to Article 22 of the VAT Law
    • E4 - Exempt pursuant to Articles 23 and 24 of the VAT Law
    • E5 - Exempt pursuant to Article 25 of the VAT Law
    • E6 - Exempt for other reasons
  • es-verifactu-correction-type - Differentiates between the correction method. Corrective invoices in VeriFactu can be Facturas Rectificativas por Diferencias or Facturas Rectificativas por Sustitución. It is taken from list L3 of the VeriFactu Ministerial Order. These are the valid values:

    • I - Differences. Used for credit and debit notes. In case of credit notes the values of the invoice are inverted to reflect the amount being a credit instead of a debit.
    • S - Substitution. Used for corrective invoices.
  • es-verifactu-regime - Regime code used to identify the type of VAT/IGIC regime to be applied to the invoice. It combines the values of lists L8A and L8B of the VeriFactu Ministerial Order. These are the valid values:

    • 01 - General regime operation
    • 02 - Export
    • 03 - Special regime for used goods, art objects, antiques and collectibles
    • 04 - Special regime for investment gold
    • 05 - Special regime for travel agencies
    • 06 - Special regime for VAT/IGIC groups (Advanced Level)
    • 07 - Special cash accounting regime
    • 08 - Operations subject to a different regime
    • 09 - Billing of travel agency services acting as mediators in name and on behalf of others
    • 10 - Collection of professional fees or rights on behalf of third parties
    • 11 - Business premises rental operations
    • 14 - Invoice with pending VAT/IGIC accrual in work certifications for Public Administration
    • 15 - Invoice with pending VAT/IGIC accrual in successive tract operations
    • 17 - Operation under OSS and IOSS regimes (VAT) / Special regime for retail traders. (IGIC)
    • 18 - Equivalence surcharge (VAT) / Special regime for small traders or retailers (IGIC)
    • 19 - Operations included in the Special Regime for Agriculture, Livestock and Fisheries
    • 20 - Simplified regime (VAT only)

Limitations

  • VeriFactu allows more than one customer per invoice, but GOBL only has one possible customer.
  • Invoices must have a note of type general that will be used as a general description of the invoice. If an invoice is missing this info, it will be rejected with an error.
  • VeriFactu supports sending more than one invoice at a time (up to 1000). However, this module only currently supports 1 invoice at a time.
  • VeriFactu requires a valid certificate to be provided, even when using the testing environment. It is the same certificate needed to access the AEAT's portal.
  • When cancelling invoices, this module assumes the party issuing the cancellation is the same as the party that issued the original invoice. In the context of the app this would always be true, but VeriFactu does allow for a different issuer.

Testing

This library includes a set of tests that can be used to validate the conversion and submission process. To run the tests, use the following command:

go test ./...

Some sample test data is available in the ./test directory. To update the JSON documents and regenerate the XML files for testing, use the following command:

go test --update

Documentation

Overview

Package verifactu provides the VeriFactu client

Index

Constants

View Source
const (
	EnvironmentProduction Environment = "production"
	EnvironmentSandbox    Environment = "sandbox"

	BaseURLProduction         = "https://www1.agenciatributaria.gob.es/wlpl/TIKE-CONT/ws/SistemaFacturacion/VerifactuSOAP"
	BaseURLProductionWithSeal = "https://www10.agenciatributaria.gob.es/wlpl/TIKE-CONT/ws/SistemaFacturacion/VerifactuSOAP"
	BaseURLTesting            = "https://prewww1.aeat.es/wlpl/TIKE-CONT/ws/SistemaFacturacion/VerifactuSOAP"
	BaseURLTestingWithSeal    = "https://prewww10.aeat.es/wlpl/TIKE-CONT/ws/SistemaFacturacion/VerifactuSOAP"
)

Environment to use for connections

View Source
const (
	SUM          = "https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/tike/cont/ws/SuministroLR.xsd"
	SUM1         = "" /* 130-byte string literal not displayed */
	DS           = "http://www.w3.org/2000/09/xmldsig#"
	EnvNamespace = "http://schemas.xmlsoap.org/soap/envelope/"
)

VeriFactu XML namespace constants

View Source
const (
	StatusCorrect            string = "Correcto"
	StatusAcceptedWithErrors string = "AceptadoConErrores"
	StatusCancelled          string = "Anulada"
	StatusIncorrect          string = "Incorrecto"
)

Default response status

View Source
const (
	// CurrentVersion is the current version of the VeriFactu document
	CurrentVersion = "1.0"
)
View Source
const FingerprintType = "01"

FingerprintType is the SHA-256 fingerprint type for Verifactu - L12. Might include support for other encryption types in the future.

View Source
const (
	SF = "https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/tike/cont/ws/EventosSIF.xsd"
)

XML namespaces

View Source
const (
	// StampKeyHash defines the key used to store the Hash in the envelope
	// stamps.
	StampKeyHash cbc.Key = "verifactu-hash"
)

Variables

View Source
var (
	// ErrConnection is used when the gateway could not be reached or gave a
	// response we're unable to understand.
	ErrConnection = newError("connection")
	// ErrValidation implies there is something wrong with the contents of the
	// request that needs to be fixed before sending it again.
	ErrValidation = newError("validation")
	// ErrDuplicate is used when the gateway has already received the request.
	ErrDuplicate = newError("duplicate")
	// ErrWarning means the request was accepted, but the gateway reported
	// issues that should be reviewed.
	ErrWarning = newError("warning")
	// ErrServer indicates the gateway had an internal problem handling the
	// request, which may succeed if attempted again later.
	ErrServer = newError("server")
)

Standard gateway error responses

View Source
var (
	ErrNotSpanish       = ErrValidation.WithMessage("only spanish invoices are supported")
	ErrAlreadyProcessed = ErrValidation.WithMessage("already processed")
	ErrOnlyInvoices     = ErrValidation.WithMessage("only invoices are supported")
	ErrOnlyStatuses     = ErrValidation.WithMessage("only bill status documents are supported")
	ErrOnlyRecords      = ErrValidation.WithMessage("only invoice registration, invoice cancellation and event records are supported")
	ErrIncompleteRecord = ErrValidation.WithMessage("record is missing the details its fingerprint is computed from")
)

Standard error responses.

Functions

func SignDocument

func SignDocument(doc any, cert *xmldsig.Certificate, opts ...xmldsig.Option) (*xmldsig.Signature, error)

SignDocument signs any XML-marshalable struct using the VeriFactu XAdES configuration. It can be used to sign registration, cancellation, and event records (or any other document type) with the provided certificate.

Types

type AggregatedEventType

type AggregatedEventType struct {
	EventType  string `xml:"sf:TipoEvento"`
	EventCount string `xml:"sf:NumeroDeEventos"`
}

AggregatedEventType represents an aggregated event type count (TipoEventoAgrType).

type ChainData

type ChainData struct {
	IDIssuer    string `json:"issuer"`
	NumSeries   string `json:"num_series"`
	IssueDate   string `json:"issue_date"`
	Fingerprint string `json:"fingerprint"`
}

ChainData contains the fields of this invoice that will be required for fingerprinting the _next_ invoice. JSON tags are provided to help with serialization.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides the main interface to the VeriFactu package.

func New

func New(software Software, opts ...Option) (*Client, error)

New creates a new VeriFactu client with shared software and configuration options for creating and sending new documents.

func (*Client) CancelInvoice

func (c *Client) CancelInvoice(env *gobl.Envelope, prev *ChainData, opts ...GenerateOption) (*InvoiceCancellation, error)

CancelInvoice builds a cancellation message from the provided document and previous chain data. Note that the cancellation does not require Hash information of the last, invoice, and instead only requires the previous chain entry.

func (*Client) CurrentTime

func (c *Client) CurrentTime() time.Time

CurrentTime returns the current time to use when generating the VeriFactu document.

func (*Client) NewEnvelopeInvoiceRequest

func (c *Client) NewEnvelopeInvoiceRequest(env *gobl.Envelope, prev *ChainData, opts ...GenerateOption) (*InvoiceRequest, error)

NewEnvelopeInvoiceRequest is a convenience method that prepares a new InvoiceRequest from the GOBL envelope in a single method call.

func (*Client) NewInvoiceRequest

func (c *Client) NewInvoiceRequest(supplier *org.Party) (*InvoiceRequest, error)

NewInvoiceRequest prepares a new invoice request for the provided supplier.

func (*Client) RegisterEvent

func (c *Client) RegisterEvent(env *gobl.Envelope, prev *EventChainData, opts ...GenerateOption) (*EventRegistration, error)

RegisterEvent prepares a new event registration document from the provided bill status inside the GOBL envelope. It will fingerprint and optionally sign the event. The resulting document can be persisted locally.

func (*Client) RegisterInvoice

func (c *Client) RegisterInvoice(env *gobl.Envelope, prev *ChainData, opts ...GenerateOption) (*InvoiceRegistration, error)

RegisterInvoice prepares a new registration document from the provided invoice inside the GOBL envelope. It will fingerprint and update the registration with the chaining hash and QR code. The resulting document can be persisted for sending later.

func (*Client) Sandbox

func (c *Client) Sandbox() bool

Sandbox returns true if the client is using the sandbox environment.

func (*Client) SendInvoiceRequest

func (c *Client) SendInvoiceRequest(ctx context.Context, ir *InvoiceRequest) (*InvoiceResponse, error)

SendInvoiceRequest will prepare the final SOAP envelope with the invoice request data and send it the agency API.

type Desglose

type Desglose struct {
	DetalleDesglose []*DetalleDesglose `xml:"sum1:DetalleDesglose"`
}

Desglose contains the breakdown details

type Destinatario

type Destinatario struct {
	IDDestinatario *Party `xml:"sum1:IDDestinatario"`
}

Destinatario represents a recipient in the document

type DetalleDesglose

type DetalleDesglose struct {
	Impuesto                      string `xml:"sum1:Impuesto,omitempty"`
	ClaveRegimen                  string `xml:"sum1:ClaveRegimen,omitempty"`
	CalificacionOperacion         string `xml:"sum1:CalificacionOperacion,omitempty"`
	OperacionExenta               string `xml:"sum1:OperacionExenta,omitempty"`
	TipoImpositivo                string `xml:"sum1:TipoImpositivo,omitempty"`
	BaseImponibleOImporteNoSujeto string `xml:"sum1:BaseImponibleOimporteNoSujeto"`
	BaseImponibleACoste           string `xml:"sum1:BaseImponibleACoste,omitempty"`
	CuotaRepercutida              string `xml:"sum1:CuotaRepercutida,omitempty"`
	TipoRecargoEquivalencia       string `xml:"sum1:TipoRecargoEquivalencia,omitempty"`
	CuotaRecargoEquivalencia      string `xml:"sum1:CuotaRecargoEquivalencia,omitempty"`
}

DetalleDesglose contains detailed breakdown information

type Encadenamiento

type Encadenamiento struct {
	PrimerRegistro   string            `xml:"sum1:PrimerRegistro,omitempty"`
	RegistroAnterior *RegistroAnterior `xml:"sum1:RegistroAnterior,omitempty"`
}

Encadenamiento contains chaining information between invoice documents

type Envelope

type Envelope struct {
	XMLName xml.Name `xml:"soapenv:Envelope"`
	XMLNs   string   `xml:"xmlns:soapenv,attr"`
	SUM     string   `xml:"xmlns:sum,attr,omitempty"`
	SUM1    string   `xml:"xmlns:sum1,attr,omitempty"`
	DS      string   `xml:"xmlns:ds,attr,omitempty"`
	Body    struct {
		ID             string          `xml:"soapenv:Id,attr,omitempty"`
		InvoiceRequest *InvoiceRequest `xml:"sum:RegFactuSistemaFacturacion,omitempty"`
	} `xml:"soapenv:Body"`
}

Envelope is the SOAP envelope wrapper used for sending messages to the remote service.

func (*Envelope) Bytes

func (d *Envelope) Bytes() ([]byte, error)

Bytes returns the XML document bytes

func (*Envelope) BytesIndent

func (d *Envelope) BytesIndent() ([]byte, error)

BytesIndent returns the indented XML document bytes

type EnvelopeResponse

type EnvelopeResponse struct {
	XMLName xml.Name `xml:"Envelope"`
	Body    struct {
		ID              string           `xml:"Id,attr,omitempty"`
		Fault           *Fault           `xml:"Fault,omitempty"`
		InvoiceResponse *InvoiceResponse `xml:"RespuestaRegFactuSistemaFacturacion,omitempty"`
	} `xml:"Body"`
}

EnvelopeResponse handles a SOAP response object that will correctly handle the namespaces.

type Environment

type Environment string

Environment defines the environment to use for connections

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error allows for structured responses from the gateway to be able to response codes and messages.

func (*Error) Code

func (e *Error) Code() string

Code returns the code provided by the remote service.

func (*Error) Error

func (e *Error) Error() string

Error produces a human readable error message.

func (*Error) Is

func (e *Error) Is(target error) bool

Is checks to see if the target error is the same as the current one or forms part of the chain.

func (*Error) Key

func (e *Error) Key() string

Key returns the key for the error.

func (*Error) Message

func (e *Error) Message() string

Message returns the human message for the error.

func (*Error) WithCode

func (e *Error) WithCode(code string) *Error

WithCode duplicates and adds the code to the error.

func (*Error) WithMessage

func (e *Error) WithMessage(msg string) *Error

WithMessage duplicates and adds the message to the error.

type Event

type Event struct {
	Software                      *EventSoftware     `xml:"sf:SistemaInformatico"`
	Issuer                        *EventIssuer       `xml:"sf:ObligadoEmision"`
	IssuedByThirdPartyOrRecipient string             `xml:"sf:EmitidaPorTerceroODestinatario,omitempty"`
	ThirdPartyOrRecipient         *EventParty        `xml:"sf:TerceroODestinatario,omitempty"`
	GenerationTimestamp           string             `xml:"sf:FechaHoraHusoGenEvento"`
	EventType                     string             `xml:"sf:TipoEvento"`
	EventData                     *EventData         `xml:"sf:DatosPropiosEvento,omitempty"`
	OtherEventData                string             `xml:"sf:OtrosDatosEvento,omitempty"`
	Chaining                      *EventChaining     `xml:"sf:Encadenamiento"`
	FingerprintType               string             `xml:"sf:TipoHuella"`
	Fingerprint                   string             `xml:"sf:HuellaEvento"`
	Signature                     *xmldsig.Signature `xml:"ds:Signature,omitempty"`
}

Event contains the event data (EventoType).

func (*Event) ChainData

func (e *Event) ChainData() *EventChainData

ChainData returns the chaining data from this event for use when fingerprinting the next event in the chain.

type EventAnomalyDetection

type EventAnomalyDetection struct {
	AnomalyType      string       `xml:"sf:TipoAnomalia"`
	OtherAnomalyData string       `xml:"sf:OtrosDatosAnomalia,omitempty"`
	AnomalousEvent   *EventRecord `xml:"sf:RegEventoAnomalo,omitempty"`
}

EventAnomalyDetection contains data for a detected anomaly in event registration records.

type EventAnomalyDetectionLaunch

type EventAnomalyDetectionLaunch struct {
	FingerprintCheck string `xml:"sf:RealizadoProcesoSobreIntegridadHuellasRegEvento"`
	FingerprintCount string `xml:"sf:NumeroDeRegistrosEventoProcesadosSobreIntegridadHuellas,omitempty"`
	SignatureCheck   string `xml:"sf:RealizadoProcesoSobreIntegridadFirmasRegEvento"`
	SignatureCount   string `xml:"sf:NumeroDeRegistrosEventoProcesadosSobreIntegridadFirmas,omitempty"`
	ChainCheck       string `xml:"sf:RealizadoProcesoSobreTrazabilidadCadenaRegEvento"`
	ChainCount       string `xml:"sf:NumeroDeRegistrosEventoProcesadosSobreTrazabilidadCadena,omitempty"`
	DateCheck        string `xml:"sf:RealizadoProcesoSobreTrazabilidadFechasRegEvento"`
	DateCount        string `xml:"sf:NumeroDeRegistrosEventoProcesadosSobreTrazabilidadFechas,omitempty"`
}

EventAnomalyDetectionLaunch contains data for launching the anomaly detection process on event registration records.

type EventChainData

type EventChainData struct {
	EventType           string `json:"event_type"`
	GenerationTimestamp string `json:"generation_timestamp"`
	Fingerprint         string `json:"fingerprint"`
}

EventChainData contains the fields of this event that will be required for fingerprinting the _next_ event. JSON tags are provided to help with serialization.

type EventChaining

type EventChaining struct {
	FirstEvent    string         `xml:"sf:PrimerEvento,omitempty"`
	PreviousEvent *PreviousEvent `xml:"sf:EventoAnterior,omitempty"`
}

EventChaining contains chaining information between event registrations

type EventData

type EventData struct {
	InvoiceAnomalyDetectionLaunch *InvoiceAnomalyDetectionLaunch `xml:"sf:LanzamientoProcesoDeteccionAnomaliasRegFacturacion,omitempty"`
	InvoiceAnomalyDetection       *InvoiceAnomalyDetection       `xml:"sf:DeteccionAnomaliasRegFacturacion,omitempty"`
	EventAnomalyDetectionLaunch   *EventAnomalyDetectionLaunch   `xml:"sf:LanzamientoProcesoDeteccionAnomaliasRegEvento,omitempty"`
	EventAnomalyDetection         *EventAnomalyDetection         `xml:"sf:DeteccionAnomaliasRegEvento,omitempty"`
	InvoiceExportPeriod           *InvoiceExportPeriod           `xml:"sf:ExportacionRegFacturacionPeriodo,omitempty"`
	EventExportPeriod             *EventExportPeriod             `xml:"sf:ExportacionRegEventoPeriodo,omitempty"`
	EventSummary                  *EventSummary                  `xml:"sf:ResumenEventos,omitempty"`
}

EventData contains event-specific data (DatosPropiosEventoType). Only one of the fields should be set at a time (choice).

type EventExportPeriod

type EventExportPeriod struct {
	PeriodStart              string       `xml:"sf:FechaHoraHusoInicioPeriodoExport"`
	PeriodEnd                string       `xml:"sf:FechaHoraHusoFinPeriodoExport"`
	FirstEventRecord         *EventRecord `xml:"sf:RegistroEventoInicialPeriodo"`
	LastEventRecord          *EventRecord `xml:"sf:RegistroEventoFinalPeriodo"`
	EventRecordCount         string       `xml:"sf:NumeroDeRegEventoExportados"`
	ExportedRecordsDiscarded string       `xml:"sf:RegEventoExportadosDejanDeConservarse"`
}

EventExportPeriod contains data about an export of event registration records for a given period.

type EventInvoiceRecord

type EventInvoiceRecord struct {
	IssuerNIF     string `xml:"sf:IDEmisorFactura"`
	InvoiceNumber string `xml:"sf:NumSerieFactura"`
	IssueDate     string `xml:"sf:FechaExpedicionFactura"`
}

EventInvoiceRecord identifies an issued invoice (IDFacturaExpedidaType) in the events namespace.

type EventInvoiceRecordWithFingerprint

type EventInvoiceRecordWithFingerprint struct {
	IssuerNIF     string `xml:"sf:IDEmisorFactura"`
	InvoiceNumber string `xml:"sf:NumSerieFactura"`
	IssueDate     string `xml:"sf:FechaExpedicionFactura"`
	Fingerprint   string `xml:"sf:Huella"`
}

EventInvoiceRecordWithFingerprint identifies an issued invoice with its fingerprint (IDFacturaExpedidaHuellaType) in the events namespace.

type EventIssuer

type EventIssuer struct {
	Name string `xml:"sf:NombreRazon"`
	NIF  string `xml:"sf:NIF"`
}

EventIssuer represents a Spanish person or entity obligated to issue invoices (PersonaFisicaJuridicaESType) in the events namespace.

type EventOtherID

type EventOtherID struct {
	CountryCode string `xml:"sf:CodigoPais,omitempty"`
	IDType      string `xml:"sf:IDType"`
	ID          string `xml:"sf:ID"`
}

EventOtherID contains alternative identification for non-NIF entities (IDOtroType) in the events namespace.

type EventParty

type EventParty struct {
	Name    string        `xml:"sf:NombreRazon"`
	NIF     string        `xml:"sf:NIF,omitempty"`
	IDOther *EventOtherID `xml:"sf:IDOtro,omitempty"`
}

EventParty represents a person or entity that may be Spanish or foreign (PersonaFisicaJuridicaType) in the events namespace.

type EventRecord

type EventRecord struct {
	EventType      string `xml:"sf:TipoEvento"`
	EventTimestamp string `xml:"sf:FechaHoraHusoEvento"`
	Fingerprint    string `xml:"sf:HuellaEvento"`
}

EventRecord identifies an event registration record (RegEventoType).

type EventRegistration

type EventRegistration struct {
	XMLName xml.Name `xml:"sf:RegistroEvento"`
	SF      string   `xml:"xmlns:sf,attr,omitempty"`
	Version string   `xml:"sf:IDVersion"`
	Event   *Event   `xml:"sf:Evento"`
}

EventRegistration represents the root element of a RegistroEvento document.

func (*EventRegistration) Bytes

func (r *EventRegistration) Bytes() ([]byte, error)

Bytes prepares an XML document suitable for persistence. Signed documents use compact XML to preserve the enveloped signature.

func (*EventRegistration) BytesIndent added in v0.43.0

func (r *EventRegistration) BytesIndent() ([]byte, error)

BytesIndent returns the indented XML document bytes, which breaks the signature of a signed document.

func (*EventRegistration) ChainData

func (r *EventRegistration) ChainData() *EventChainData

ChainData returns the chaining data from the inner event.

type EventSoftware

type EventSoftware struct {
	Name               string        `xml:"sf:NombreRazon"`
	NIF                string        `xml:"sf:NIF,omitempty"`
	IDOther            *EventOtherID `xml:"sf:IDOtro,omitempty"`
	SoftwareName       string        `xml:"sf:NombreSistemaInformatico,omitempty"`
	SoftwareID         string        `xml:"sf:IdSistemaInformatico"`
	Version            string        `xml:"sf:Version"`
	InstallationNumber string        `xml:"sf:NumeroInstalacion"`
	OnlyVerifactu      string        `xml:"sf:TipoUsoPosibleSoloVerifactu,omitempty"`
	MultiOT            string        `xml:"sf:TipoUsoPosibleMultiOT,omitempty"`
	MultipleOT         string        `xml:"sf:IndicadorMultiplesOT,omitempty"`
}

EventSoftware contains the details about the software system that generated the event (SistemaInformaticoType).

type EventSummary

type EventSummary struct {
	EventTypes              []*AggregatedEventType             `xml:"sf:TipoEvento"`
	FirstInvoiceRecord      *EventInvoiceRecordWithFingerprint `xml:"sf:RegistroFacturacionInicialPeriodo,omitempty"`
	LastInvoiceRecord       *EventInvoiceRecordWithFingerprint `xml:"sf:RegistroFacturacionFinalPeriodo,omitempty"`
	RegistrationRecordCount string                             `xml:"sf:NumeroDeRegistrosFacturacionAltaGenerados"`
	TotalTaxSum             string                             `xml:"sf:SumaCuotaTotalAlta"`
	TotalAmountSum          string                             `xml:"sf:SumaImporteTotalAlta"`
	CancellationRecordCount string                             `xml:"sf:NumeroDeRegistrosFacturacionAnulacionGenerados"`
}

EventSummary contains a summary of events (ResumenEventosType).

type FacturaRectificada

type FacturaRectificada struct {
	IDEmisorFactura        string `xml:"sum1:IDEmisorFactura"`
	NumSerieFactura        string `xml:"sum1:NumSerieFactura"`
	FechaExpedicionFactura string `xml:"sum1:FechaExpedicionFactura"`
}

FacturaRectificada represents a rectified invoice

type FacturaSustituida

type FacturaSustituida struct {
	IDEmisorFactura        string `xml:"sum1:IDEmisorFactura"`
	NumSerieFactura        string `xml:"sum1:NumSerieFactura"`
	FechaExpedicionFactura string `xml:"sum1:FechaExpedicionFactura"`
}

FacturaSustituida represents a substituted invoice

type FacturasRectificadas

type FacturasRectificadas struct {
	Items []*FacturaRectificada `xml:"sum1:IDFacturaRectificada"`
}

FacturasRectificadas is a wrapper for multiple rectified invoices

type FacturasSustituidas

type FacturasSustituidas struct {
	Items []*FacturaSustituida `xml:"sum1:IDFacturaSustituida"`
}

FacturasSustituidas is a wrapper for multiple substituted invoices

type Fault

type Fault struct {
	Code    string `xml:"faultcode"`
	Message string `xml:"faultstring"`
}

Fault is issued by the SOAP server when something goes wrong.

func (*Fault) Err

func (f *Fault) Err() *Error

Err converts the fault into a structured error that the consumer can use to determine how the issue should be handled.

func (*Fault) ErrorCode

func (f *Fault) ErrorCode() string

ErrorCode provides the VeriFactu error code of the fault, if one could be extracted from the fault string.

func (*Fault) ErrorMessage

func (f *Fault) ErrorMessage() string

ErrorMessage provides the fault string without the error code prefix and with any indentation reduced to single spaces.

type GenerateOption

type GenerateOption func(*generateOptions)

GenerateOption defines what is expected from an option used in generate methods.

func Amended

func Amended() GenerateOption

Amended indicates that the incoming document is an amendment of a previous document, known in Spanish as "Subsanación". If incorrect data was sent, this will allow the new document to replace the old.

func NoPriorRecord

func NoPriorRecord() GenerateOption

NoPriorRecord is used with cancellation documents when no previous attempt was made to issue an invoice via Verifactu, or if the document to cancel was rejected.

func PreviouslyRejected

func PreviouslyRejected() GenerateOption

PreviouslyRejected indicates that an earlier attempt to process the document was rejected and thus never received by the verifactu system. This option automatically implies the Amended option when supported by the document.

func WithInstallationNumber

func WithInstallationNumber(code string) GenerateOption

WithInstallationNumber is used to override the installation number defined in the connection configuration while generating the invoice.

type IDFactura

type IDFactura struct {
	IDEmisorFactura        string `xml:"sum1:IDEmisorFactura"`
	NumSerieFactura        string `xml:"sum1:NumSerieFactura"`
	FechaExpedicionFactura string `xml:"sum1:FechaExpedicionFactura"`
}

IDFactura contains the identifying information for an invoice

type IDFacturaAnulada

type IDFacturaAnulada struct {
	IDEmisorFactura        string `xml:"sum1:IDEmisorFacturaAnulada"`
	NumSerieFactura        string `xml:"sum1:NumSerieFacturaAnulada"`
	FechaExpedicionFactura string `xml:"sum1:FechaExpedicionFacturaAnulada"`
}

IDFacturaAnulada contains the identifying information for an invoice

type IDOtro

type IDOtro struct {
	CodigoPais string `xml:"sum1:CodigoPais"`
	IDType     string `xml:"sum1:IDType"`
	ID         string `xml:"sum1:ID"`
}

IDOtro contains alternative identifying information

type ImporteRectificacion

type ImporteRectificacion struct {
	BaseRectificada         num.Amount `xml:"sum1:BaseRectificada"`
	CuotaRectificada        num.Amount `xml:"sum1:CuotaRectificada"`
	CuotaRecargoRectificado num.Amount `xml:"sum1:CuotaRecargoRectificado,omitempty"`
}

ImporteRectificacion contains rectification amounts

type InvoiceAnomalyDetection

type InvoiceAnomalyDetection struct {
	AnomalyType      string              `xml:"sf:TipoAnomalia"`
	OtherAnomalyData string              `xml:"sf:OtrosDatosAnomalia,omitempty"`
	AnomalousInvoice *EventInvoiceRecord `xml:"sf:RegistroFacturacionAnomalo,omitempty"`
}

InvoiceAnomalyDetection contains data for a detected anomaly in invoice registration records.

type InvoiceAnomalyDetectionLaunch

type InvoiceAnomalyDetectionLaunch struct {
	FingerprintCheck string `xml:"sf:RealizadoProcesoSobreIntegridadHuellasRegFacturacion"`
	FingerprintCount string `xml:"sf:NumeroDeRegistrosFacturacionProcesadosSobreIntegridadHuellas,omitempty"`
	SignatureCheck   string `xml:"sf:RealizadoProcesoSobreIntegridadFirmasRegFacturacion"`
	SignatureCount   string `xml:"sf:NumeroDeRegistrosFacturacionProcesadosSobreIntegridadFirmas,omitempty"`
	ChainCheck       string `xml:"sf:RealizadoProcesoSobreTrazabilidadCadenaRegFacturacion"`
	ChainCount       string `xml:"sf:NumeroDeRegistrosFacturacionProcesadosSobreTrazabilidadCadena,omitempty"`
	DateCheck        string `xml:"sf:RealizadoProcesoSobreTrazabilidadFechasRegFacturacion"`
	DateCount        string `xml:"sf:NumeroDeRegistrosFacturacionProcesadosSobreTrazabilidadFechas,omitempty"`
}

InvoiceAnomalyDetectionLaunch contains data for launching the anomaly detection process on invoice registration records.

type InvoiceCancellation

type InvoiceCancellation struct {
	XMLName                  xml.Name           `xml:"sum1:RegistroAnulacion"`
	SUM1                     string             `xml:"xmlns:sum1,attr,omitempty"`
	IDVersion                string             `xml:"sum1:IDVersion"`
	IDFactura                *IDFacturaAnulada  `xml:"sum1:IDFactura"`
	RefExterna               string             `xml:"sum1:RefExterna,omitempty"`
	SinRegistroPrevio        string             `xml:"sum1:SinRegistroPrevio,omitempty"`
	RechazoPrevio            string             `xml:"sum1:RechazoPrevio,omitempty"`
	GeneradoPor              string             `xml:"sum1:GeneradoPor,omitempty"`
	Generador                *Party             `xml:"sum1:Generador,omitempty"`
	Encadenamiento           *Encadenamiento    `xml:"sum1:Encadenamiento"`
	SistemaInformatico       *Software          `xml:"sum1:SistemaInformatico"`
	FechaHoraHusoGenRegistro string             `xml:"sum1:FechaHoraHusoGenRegistro"`
	TipoHuella               string             `xml:"sum1:TipoHuella"`
	Huella                   string             `xml:"sum1:Huella"`
	Signature                *xmldsig.Signature `xml:"ds:Signature,omitempty"`
}

InvoiceCancellation contains the details of an invoice cancellation

func (*InvoiceCancellation) Bytes

func (c *InvoiceCancellation) Bytes() ([]byte, error)

Bytes prepares an XML document suitable for persistence. Signed documents use compact XML to preserve the enveloped signature.

func (*InvoiceCancellation) BytesIndent added in v0.43.0

func (c *InvoiceCancellation) BytesIndent() ([]byte, error)

BytesIndent returns the indented XML document bytes, which breaks the signature of a signed document.

func (*InvoiceCancellation) ChainData

func (c *InvoiceCancellation) ChainData() *ChainData

ChainData provides the details for this cancellation entry.

type InvoiceExportPeriod

type InvoiceExportPeriod struct {
	PeriodStart              string                             `xml:"sf:FechaHoraHusoInicioPeriodoExport"`
	PeriodEnd                string                             `xml:"sf:FechaHoraHusoFinPeriodoExport"`
	FirstInvoiceRecord       *EventInvoiceRecordWithFingerprint `xml:"sf:RegistroFacturacionInicialPeriodo"`
	LastInvoiceRecord        *EventInvoiceRecordWithFingerprint `xml:"sf:RegistroFacturacionFinalPeriodo"`
	RegistrationRecordCount  string                             `xml:"sf:NumeroDeRegistrosFacturacionAltaExportados"`
	TotalTaxSum              string                             `xml:"sf:SumaCuotaTotalAlta"`
	TotalAmountSum           string                             `xml:"sf:SumaImporteTotalAlta"`
	CancellationRecordCount  string                             `xml:"sf:NumeroDeRegistrosFacturacionAnulacionExportados"`
	ExportedRecordsDiscarded string                             `xml:"sf:RegistrosFacturacionExportadosDejanDeConservarse"`
}

InvoiceExportPeriod contains data about an export of invoice registration records for a given period.

type InvoiceRegistration

type InvoiceRegistration struct {
	XMLName                             xml.Name              `xml:"sum1:RegistroAlta"`
	SUM1                                string                `xml:"xmlns:sum1,attr,omitempty"`
	IDVersion                           string                `xml:"sum1:IDVersion"`
	IDFactura                           *IDFactura            `xml:"sum1:IDFactura"`
	RefExterna                          string                `xml:"sum1:RefExterna,omitempty"`
	NombreRazonEmisor                   string                `xml:"sum1:NombreRazonEmisor"`
	Subsanacion                         string                `xml:"sum1:Subsanacion,omitempty"`
	RechazoPrevio                       string                `xml:"sum1:RechazoPrevio,omitempty"`
	TipoFactura                         string                `xml:"sum1:TipoFactura"`
	TipoRectificativa                   string                `xml:"sum1:TipoRectificativa,omitempty"`
	FacturasRectificadas                *FacturasRectificadas `xml:"sum1:FacturasRectificadas,omitempty"`
	FacturasSustituidas                 *FacturasSustituidas  `xml:"sum1:FacturasSustituidas,omitempty"`
	ImporteRectificacion                *ImporteRectificacion `xml:"sum1:ImporteRectificacion,omitempty"`
	FechaOperacion                      string                `xml:"sum1:FechaOperacion,omitempty"`
	DescripcionOperacion                string                `xml:"sum1:DescripcionOperacion"`
	FacturaSimplificadaArt7273          string                `xml:"sum1:FacturaSimplificadaArt7273,omitempty"`
	FacturaSinIdentifDestinatarioArt61d string                `xml:"sum1:FacturaSinIdentifDestinatarioArt61d,omitempty"`
	Macrodato                           string                `xml:"sum1:Macrodato,omitempty"`
	EmitidaPorTerceroODestinatario      string                `xml:"sum1:EmitidaPorTerceroODestinatario,omitempty"`
	Tercero                             *Party                `xml:"sum1:Tercero,omitempty"`
	Destinatarios                       []*Destinatario       `xml:"sum1:Destinatarios,omitempty"`
	Cupon                               string                `xml:"sum1:Cupon,omitempty"`
	Desglose                            *Desglose             `xml:"sum1:Desglose"`
	CuotaTotal                          num.Amount            `xml:"sum1:CuotaTotal"`
	ImporteTotal                        num.Amount            `xml:"sum1:ImporteTotal"`
	Encadenamiento                      *Encadenamiento       `xml:"sum1:Encadenamiento"`
	SistemaInformatico                  *Software             `xml:"sum1:SistemaInformatico"`
	FechaHoraHusoGenRegistro            string                `xml:"sum1:FechaHoraHusoGenRegistro"`
	NumRegistroAcuerdoFacturacion       string                `xml:"sum1:NumRegistroAcuerdoFacturacion,omitempty"`
	IdAcuerdoSistemaInformatico         string                `xml:"sum1:IdAcuerdoSistemaInformatico,omitempty"` //nolint:revive,staticcheck
	TipoHuella                          string                `xml:"sum1:TipoHuella"`
	Huella                              string                `xml:"sum1:Huella"`
	Signature                           *xmldsig.Signature    `xml:"ds:Signature,omitempty"`
}

InvoiceRegistration contains the details of an invoice registration

func (*InvoiceRegistration) Bytes

func (r *InvoiceRegistration) Bytes() ([]byte, error)

Bytes prepares an XML document suitable for persistence. Signed documents use compact XML to preserve the enveloped signature.

func (*InvoiceRegistration) BytesIndent added in v0.43.0

func (r *InvoiceRegistration) BytesIndent() ([]byte, error)

BytesIndent returns the indented XML document bytes, which breaks the signature of a signed document.

func (*InvoiceRegistration) ChainData

func (r *InvoiceRegistration) ChainData() *ChainData

ChainData provides the details for this registration entry.

type InvoiceRequest

type InvoiceRequest struct {
	XMLName xml.Name              `xml:"sum:RegFactuSistemaFacturacion"`
	Header  *InvoiceRequestHeader `xml:"sum:Cabecera"`
	Lines   []*InvoiceRequestLine `xml:"sum:RegistroFactura,omitempty"`
}

InvoiceRequest represents the root element of a RegFactuSistemaFacturacion document

func (*InvoiceRequest) AddCancellation

func (req *InvoiceRequest) AddCancellation(d *InvoiceCancellation)

AddCancellation adds the requested document to the request body.

func (*InvoiceRequest) AddRegistration

func (req *InvoiceRequest) AddRegistration(d *InvoiceRegistration)

AddRegistration adds the provided document to the list of registrations.

func (*InvoiceRequest) Envelop

func (req *InvoiceRequest) Envelop() *Envelope

Envelop provides a SOAP Envelope around the InvoiceRequest, ready to send off via the API.

type InvoiceRequestHeader

type InvoiceRequestHeader struct {
	Obligado           Issuer              `xml:"sum1:ObligadoEmision"`
	Representante      *Issuer             `xml:"sum1:Representante,omitempty"`
	RemisionVoluntaria *RemisionVoluntaria `xml:"sum1:RemisionVoluntaria,omitempty"`
}

InvoiceRequestHeader contains the header information for a VeriFactu document

type InvoiceRequestLine

type InvoiceRequestLine struct {
	Registration *InvoiceRegistration `xml:"sum1:RegistroAlta,omitempty"`
	Cancellation *InvoiceCancellation `xml:"sum1:RegistroAnulacion,omitempty"`
}

InvoiceRequestLine contains either an invoice registration or cancellation

func (*InvoiceRequestLine) ChainData

func (line *InvoiceRequestLine) ChainData() *ChainData

ChainData provides the chaining data for this line inside the invoice request.

type InvoiceResponse

type InvoiceResponse struct {
	XMLName xml.Name `xml:"RespuestaRegFactuSistemaFacturacion"`
	Header  struct {
		Issuer             InvoiceResponseIssuer               `xml:"ObligadoEmision"`
		Representative     *InvoiceResponseIssuer              `xml:"Representante,omitempty"`
		RemisionVoluntaria *InvoiceResponseVoluntarySubmission `xml:"sum1:RemisionVoluntaria,omitempty"`
	} `xml:"Cabecera"`
	Wait   int                    `xml:"TiempoEsperaEnvio"`
	Status string                 `xml:"EstadoEnvio"`
	Lines  []*InvoiceResponseLine `xml:"RespuestaLinea"`
}

InvoiceResponse defines the response fields from the VeriFactu gateway.

func (*InvoiceResponse) Bytes

func (ir *InvoiceResponse) Bytes() ([]byte, error)

Bytes returns the XML document bytes.

func (*InvoiceResponse) BytesIndent added in v0.43.0

func (ir *InvoiceResponse) BytesIndent() ([]byte, error)

BytesIndent returns the indented XML document bytes.

type InvoiceResponseIssuer

type InvoiceResponseIssuer struct {
	Name string `xml:"NombreRazon"`
	NIF  string `xml:"NIF"`
}

InvoiceResponseIssuer maps the response from the invoice request for the issuer.

type InvoiceResponseLine

type InvoiceResponseLine struct {
	XMLName xml.Name `xml:"RespuestaLinea"`
	ID      struct {
		Issuer string `xml:"IDEmisorFactura"`
		Code   string `xml:"NumSerieFactura"`
		Date   string `xml:"FechaExpedicionFactura"`
	} `xml:"IDFactura"`
	Operation struct {
		Type             OpType `xml:"TipoOperacion"`
		Correction       string `xml:"Subsanacion,omitempty"`
		RejectedPrevious string `xml:"RechazoPrevio,omitempty"`
		NoPrevious       string `xml:"SinRegistroPrevio,omitempty"`
	} `xml:"Operacion"`
	Ref         string `xml:"RefExterna,omitempty"`
	Status      string `xml:"EstadoRegistro"`
	Code        string `xml:"CodigoErrorRegistro,omitempty"`
	Description string `xml:"DescripcionErrorRegistro,omitempty"`

	// Duplicated contains information about possible duplicated requests
	// that may need to be handled differently.
	Duplicated *InvoiceResponseLineDuplicated `xml:"RegistroDuplicado,omitempty"`
}

InvoiceResponseLine defines the contents of a single line of the request.

func (*InvoiceResponseLine) Error

func (r *InvoiceResponseLine) Error() error

Error provides a specific error repsonse for the individual line so that it can be handled correctly by the consumer.

func (*InvoiceResponseLine) Message

func (r *InvoiceResponseLine) Message() string

Message provides the description of the issue reported by the gateway, or the status of the line when no description was provided. The status is not included alongside the description as it is already available separately.

type InvoiceResponseLineDuplicated

type InvoiceResponseLineDuplicated struct {
	ID          string `xml:"IdPeticionRegistroDuplicado"`
	Status      string `xml:"EstadoRegistroDuplicado"`
	Code        string `xml:"CodigoErrorRegistro,omitempty"`
	Description string `xml:"DescripcionErrorRegistro,omitempty"`
}

InvoiceResponseLineDuplicated describes details about the detected duplicate.

type InvoiceResponseVoluntarySubmission

type InvoiceResponseVoluntarySubmission struct {
	Date     string `xml:"FechaFinVerifactu,omitempty"`
	Incident string `xml:"Incidencia,omitempty"`
}

InvoiceResponseVoluntarySubmission for additional header data.

type Issuer

type Issuer struct {
	NombreRazon string `xml:"sum1:NombreRazon"`
	NIF         string `xml:"sum1:NIF"`
}

Issuer represents an obligated party in the document

type OpType

type OpType string

OpType defines the type of operation that was performed.

const (
	OpTypeRegistration OpType = "Alta"
	OpTypeCancellation OpType = "Anulacion"
)

Operation types.

type Option

type Option func(*Client)

Option is used to configure the client.

var WithCorporateSeal Option = func(c *Client) {
	c.withSeal = true
}

WithCorporateSeal uses the specific VERI*FACTU endpoints for communicating with a legal entity's corporate seal instead of a regular certificate issued to individuals. In Spanish these are called "Sello de Entidad".

func InProduction

func InProduction() Option

InProduction defines the connection to use the production environment.

func InSandbox

func InSandbox() Option

InSandbox defines the connection to use the testing environment.

func NoVerifactu added in v0.40.0

func NoVerifactu() Option

NoVerifactu configures the client for a NO VERI*FACTU invoicing system. Records in NO VERI*FACTU systems must be signed, so this option also enables signing; use WithSigning to pass additional signing options if needed.

func WithCertificate

func WithCertificate(cert *xmldsig.Certificate) Option

WithCertificate defines the signing certificate to use when producing the VeriFactu document.

func WithCurrentTime

func WithCurrentTime(curTime time.Time) Option

WithCurrentTime defines the current time to use when generating the VeriFactu document. Only useful for testing.

func WithRepresentative

func WithRepresentative(name, nif string) Option

WithRepresentative can be used to define a legal representative of the entity legally obliged to issue the invoice, usually the supplier. This may be required when the supplier's digital certificate is not available.

func WithSigning

func WithSigning(opts ...xmldsig.Option) Option

WithSigning sets additional xmldsig options that will be passed through to SignDocument for each record. This is useful for controlling the document ID and signing time in tests.

type Party

type Party struct {
	NombreRazon string  `xml:"sum1:NombreRazon"`
	NIF         string  `xml:"sum1:NIF,omitempty"`
	IDOtro      *IDOtro `xml:"sum1:IDOtro,omitempty"`
}

Party represents a in the document, covering fields Generador, Tercero and IDDestinatario

type PreviousEvent

type PreviousEvent struct {
	EventType           string `xml:"sf:TipoEvento"`
	GenerationTimestamp string `xml:"sf:FechaHoraHusoGenEvento"`
	Fingerprint         string `xml:"sf:HuellaEvento"`
}

PreviousEvent contains information about the previous event registration used for chaining.

type Record added in v0.43.0

type Record struct {
	// Fingerprint as stated in the record.
	Fingerprint string
	// PreviousFingerprint as stated in the record, empty for the first record of a chain.
	PreviousFingerprint string
	// ComputedFingerprint is recomputed from the fields the fingerprint covers, differing when any of them was altered.
	ComputedFingerprint string
	// GenerationTimestamp is when the record was generated, with its time zone.
	GenerationTimestamp string
}

Record contains the chain details read back from a record, to check its fingerprint, which covers only some fields and not the signature.

func ParseRecord added in v0.43.0

func ParseRecord(data []byte) (*Record, error)

ParseRecord reads the chain details of an invoice registration, cancellation or event record.

type RegistroAnterior

type RegistroAnterior struct {
	IDEmisorFactura        string `xml:"sum1:IDEmisorFactura"`
	NumSerieFactura        string `xml:"sum1:NumSerieFactura"`
	FechaExpedicionFactura string `xml:"sum1:FechaExpedicionFactura"`
	Huella                 string `xml:"sum1:Huella"`
}

RegistroAnterior contains information about the previous registration

type RemisionVoluntaria

type RemisionVoluntaria struct {
	FechaFinVerifactu string `xml:"sum1:FechaFinVerifactu,omitempty"`
	Incidencia        string `xml:"sum1:Incidencia,omitempty"`
}

RemisionVoluntaria contains voluntary submission details

type Software

type Software struct {
	NombreRazon                 string `xml:"sum1:NombreRazon"`
	NIF                         string `xml:"sum1:NIF"`
	NombreSistemaInformatico    string `xml:"sum1:NombreSistemaInformatico"`
	IdSistemaInformatico        string `xml:"sum1:IdSistemaInformatico"` //nolint:revive,staticcheck
	Version                     string `xml:"sum1:Version"`
	NumeroInstalacion           string `xml:"sum1:NumeroInstalacion"` // may need to be overridden at run time
	TipoUsoPosibleSoloVerifactu string `xml:"sum1:TipoUsoPosibleSoloVerifactu,omitempty"`
	TipoUsoPosibleMultiOT       string `xml:"sum1:TipoUsoPosibleMultiOT,omitempty"`
	IndicadorMultiplesOT        string `xml:"sum1:IndicadorMultiplesOT,omitempty"`
}

Software contains the details about the software that is using this library to generate VeriFactu documents. These details are included in the final document.

Directories

Path Synopsis
Package addon provides the VeriFactu addon for GOBL, covering both the VERI*FACTU and NO VERI*FACTU modalities.
Package addon provides the VeriFactu addon for GOBL, covering both the VERI*FACTU and NO VERI*FACTU modalities.
cmd
gobl.verifactu command
Package main provides the command line interface to the VeriFactu package.
Package main provides the command line interface to the VeriFactu package.
Package test provides common functions for testing.
Package test provides common functions for testing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址