Download the PHP package krendil007/verifactu-php without Composer
On this page you can find all versions of the php package krendil007/verifactu-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download krendil007/verifactu-php
More information about krendil007/verifactu-php
Files in krendil007/verifactu-php
Package verifactu-php
Short Description Librería para la integración del sistema de la agencia tributaria española "Veri*factu" (verifactu)
License MIT
Informations about the package verifactu-php
Verifactu PHP Library
[ES] Librería completa (registro, consulta, anulación) orientada a objetos para la integración del sistema de facturación digital de Verifactu.
[EN] Full object oriented (register, query, cancellation) library for integration of Verifactu digital invoicing system.
Disclaimer: this is an open source library, not an invoicing system. It is provided without any warranties; it is the sole responsibility of the integrator to verify its correct operation and compliance with legal or technical requirements. The library includes automated tests to help verify its functionality, but use in production is at your own risk.
A modern PHP library for integrating with 🇪🇸Spain’s AEAT Verifactu system (digital invoice submission, cancellation, querying, and events) according to the official regulatory technical specification.
[!NOTE] This library supports verfactu transactions only. For non verifactu signed transactions, such as those required when not using invoicing software, you may look for a different library.
Table of Contents
- Introduction
- Features
- Installation
- Basic Usage
- AEAT Workflow Overview
- Configuration
- Main Models
- Service Reference
- Error Handling
- Developing and testing
- Contributing
- License
- Acknowledgements
Introduction
This library provides an object-oriented, strongly-typed and extensible interface to Spain’s AEAT Verifactu digital invoicing system, including:
- Invoice registration (Alta)
- Invoice cancellation (Anulación)
- Querying previously submitted invoices
- Event notification (system-level events required by law)
- QR code generation (for inclusion on invoices)
- Built-in XML signature (XAdES enveloped) and hash calculation
- Error translation using the official AEAT code dictionary
It is designed for easy Composer-based installation and seamless integration into any modern PHP 8.0+ application.
Features
- PSR-4 namespaced (
eseperio\verifactu) - Models mapped to AEAT XSDs for strong validation and serialization
- Fully modular, easily testable architecture
- Certificate management for SOAP and XML signature
- Compatible with both production and testing AEAT endpoints
- Lightweight QR code generation (no unnecessary dependencies)
- Developer-friendly validation and error reporting
Installation
Install via Composer:
Basic Usage
1. Configuration
Before using any service, you must configure the library with your certificate, password, certificate type, and
environment.
Choose between certificate type (certificate or seal) and environment (production or sandbox) according to
whether you'll be working in production or testing.
- Use
Verifactu::TYPE_CERTIFICATEfor a personal/company certificate, orVerifactu::TYPE_SEALfor a seal certificate. - Use
Verifactu::ENVIRONMENT_PRODUCTIONfor real submissions, orVerifactu::ENVIRONMENT_SANDBOXfor AEAT homologation/testing.
2. Register an Invoice (Alta)
3. Cancel an Invoice (Anulación)
4. Query Submitted Invoices
5. Generate QR for an Invoice
The library provides flexible options for generating QR codes for invoices, supporting different renderers, resolutions, and output formats.
Available Options:
-
Destination Types:
QrGeneratorService::DESTINATION_STRING: Returns the raw image data (default)QrGeneratorService::DESTINATION_FILE: Saves to a temporary file and returns the file path
-
Renderer Types:
QrGeneratorService::RENDERER_GD: Uses GD library (default, widely available)QrGeneratorService::RENDERER_IMAGICK: Uses ImageMagick (if available)QrGeneratorService::RENDERER_SVG: Generates SVG format (vector-based)
- Resolution: Size in pixels (default: 300)
AEAT Workflow Overview
The typical workflow to comply with AEAT Verifactu regulation is:
- Prepare Invoice Data: Build an
InvoiceSubmissionmodel (orInvoiceCancellation,EventRecord, etc.) with all required fields. - Generate Hash (Huella): The library calculates the SHA-256 hash of the invoice using official field ordering.
- Serialize to XML: The library creates an XML structure strictly matching the AEAT XSD.
- Digitally Sign XML: The library signs the XML block using XAdES enveloped and your digital certificate.
- Transmit to AEAT: The signed XML is sent to AEAT via SOAP using the appropriate endpoint and certificate authentication.
- Parse Response: The response is parsed into a typed model (
InvoiceResponse,QueryResponse, etc.), translating error codes using the official dictionary. - Handle Results: Use the CSV, status, and error details to update your ERP, notify users, or perform follow-up actions.
The same flow applies to cancellations and events, changing only the data model and XML structure.
Configuration
The library is configured using the Verifactu::config() method, which accepts the following parameters:
Certificate Types
Verifactu::TYPE_CERTIFICATE: For a personal or company certificateVerifactu::TYPE_SEAL: For a seal certificate
Environments
Verifactu::ENVIRONMENT_PRODUCTION: For real submissions to AEATVerifactu::ENVIRONMENT_SANDBOX: For testing in AEAT's homologation environment
The library automatically selects the appropriate SOAP endpoints and QR verification URLs based on the certificate type and environment.
Advanced Configuration
If you need more control over the configuration, you can use the VerifactuService::config() method directly:
Main Models
The library provides a comprehensive set of object-oriented models that represent different aspects of the AEAT
Verifactu system. All models extend the base Model class, which provides validation functionality.
Core Models
- InvoiceRecord: Abstract base class for invoice records (submissions and cancellations)
- InvoiceSubmission: For registering new invoices (Alta)
- InvoiceCancellation: For cancelling existing invoices (Anulación)
- InvoiceQuery: For querying submitted invoices
- InvoiceResponse: The result of a registration or cancellation
- QueryResponse: The result of a query/filter
- EventRecord: For system events as required by AEAT
Component Models
- InvoiceId: Invoice identification block used within both Alta and Anulación
- Breakdown: Tax breakdown information for invoices
- BreakdownDetail: Individual tax rate breakdown item
- Chaining: Invoice chaining information for hash linkage
- ComputerSystem: Information about the computer system generating the invoice
- LegalPerson: Represents a legal entity (person or company) with identification
- OtherID: Alternative identification for non-Spanish entities
- PreviousInvoiceChaining: Information about the previous invoice in a chain
- Recipient: Invoice recipient information
- RectificationBreakdown: Breakdown for rectification invoices
Enumerations
The library uses enum classes for type-safe constants:
- HashType: Hash algorithm types (SHA-256)
- InvoiceType: Invoice types (F1, F2, R1, R2, etc.)
- OperationQualificationType: Tax operation qualifications
- PeriodType: Month or quarter periods
- RectificationType: Types of invoice rectifications
- YesNoType: Yes/No values for boolean fields
- GeneratorType: Invoice generator types
- ThirdPartyOrRecipientType: Types of third parties or recipients
Model Validation
All models provide validation through the validate() method:
XML Serialization
Models can be serialized to XML using the toXml() method, which returns a DOMDocument:
See the /src/models directory for PHPDoc details and validation rules for each model.
Service Reference
The library is organized into specialized services that handle different aspects of the AEAT Verifactu integration.
While most operations can be performed through the main Verifactu facade, you can also use these services directly for
more advanced use cases.
Main Services
- Verifactu: The main facade class that provides a simplified API for common operations.
- VerifactuService: Orchestrates the main workflow (validate → hash → serialize → sign → SOAP → parse).
Specialized Services
-
HashGeneratorService: Implements AEAT-compliant SHA-256 hash calculation for invoices.
-
XmlSignerService: Digitally signs XML blocks using XAdES Enveloped and your certificate.
-
SoapClientFactoryService: Configures and creates secure SOAP clients with certificates.
-
QrGeneratorService: Generates AEAT-compliant QR codes for invoices in various formats.
-
ResponseParserService: Converts AEAT XML/SOAP responses to model objects.
-
EventDispatcherService: Handles event submission to AEAT endpoints.
- CertificateManagerService: Manages certificate and private key loading and validation.
Each service is designed to be used independently or as part of the overall workflow orchestrated by the
VerifactuService. This modular design allows for flexibility and testability.
Error Handling
The library provides comprehensive error handling at multiple levels:
Model Validation Errors
When using the validate() method on models, validation errors are returned as an associative array:
AEAT Response Errors
Errors returned by AEAT in SOAP responses are parsed into structured objects:
All AEAT error codes are mapped to human-readable messages using the official code dictionary in
/src/dictionaries/ErrorRegistry.php.
[!NOTE] If you receive the error: “The value of the NIF field in the ObligadoEmision block is not identified”, it means the issuer data you provided is not correct. They must exactly match your census data at the Spanish Tax Agency (AEAT). You can verify them on the AEAT website under “Mis datos censales”.
SOAP Communication Errors
When making SOAP requests, any communication errors (network issues, timeouts, etc.) will throw a SoapFault exception.
Also if soap validation does not pass in AEAT, a code will be returned by AEAT. Here is a list of common codes:
| Code | Description |
|---|---|
| 100 | The SOAP request signature is not valid |
| 101 | The SOAP request is empty |
| 102 | The SOAP request is not well-formed: SOAP Envelope not found |
| 103 | The SOAP request is not well-formed: SOAP Body not found |
| 104 | The SOAP request is not well-formed: SOAP Header not found |
| 106 | The certificate used in the SOAP signature is on a blocklist or is a test certificate |
Exception Handling
The library throws exceptions for various error conditions:
Common Error Types
- Validation Errors: Returned by the
validate()method when model properties don't meet requirements - AEAT Business Errors: Returned in the response when AEAT rejects the submission for business reasons
- Certificate Errors: Thrown when there are issues with the digital certificate
- SOAP Communication Errors: Thrown when there are network or protocol issues
- XML Parsing Errors: Thrown when there are issues parsing XML responses
Proper error handling is essential for a robust integration with AEAT Verifactu.
Contributing
- Open issues or pull requests with improvements, bugfixes, or feature requests.
- Please follow PSR coding standards and document all public classes/methods with PHPDoc.
- Contributions for additional AEAT document types or regulatory changes are welcome!
License
MIT License. See LICENSE file.
Acknowledgements
- Based on public technical documentation and XSDs by AEAT.
- QR generation via bacon/bacon-qr-code
- XML signature via robrichards/xmlseclibs
For more information on the Verifactu regulation, see the AEAT website
Developing and testing
Testing
This library includes comprehensive tests to ensure code quality and that documentation examples work correctly:
Setting up for Sandbox Testing
To run tests that interact with the AEAT Verifactu sandbox environment, you need to provide a valid certificate. The
library uses a .env file to securely load certificate information without committing it to the repository.
-
Copy the
.env.examplefile to.envin the project root: -
Edit the
.envfile and set the following variables: -
When you run any test command, the library will automatically check if the
.envfile exists and create it from.env.exampleif it doesn't. If the file is created automatically, you'll see a warning message indicating that you need to configure it. - Tests that require a certificate will be skipped if the
.envfile is not properly configured.
Note: The
.envfile is excluded from version control by.gitignoreto prevent accidentally committing sensitive information.[!NOTE] To run integration tests you must define TEST_ISSUER_NIF and TEST_ISSUER_NAME in
.env. Tests will throw an exception if they are not configured. These values must exactly match your AEAT census data (NIF and legal name). If they do not match, you will get issuer identification errors.
Development
See the CONTRIBUTING.md file for guidelines on how to contribute to this project, including setting up your development environment, running tests, and submitting pull requests.
All versions of verifactu-php with dependencies
robrichards/xmlseclibs Version ^3.0
php Version >=8.1
ext-soap Version *
ext-libxml Version *
ext-openssl Version *
ext-dom Version *
vlucas/phpdotenv Version ^5.5