### Implement Verifactu Invoice REST API with Express.js Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt This snippet demonstrates a full REST API implementation using Express.js to handle VeriFacTu invoice creation and cancellation. It includes helper functions for date conversion and configuration setup. The API exposes endpoints for creating invoices, canceling invoices, and a health check. ```javascript const express = require('express'); const { createVerifactuInvoice, cancelVerifactuInvoice } = require('verifactu-node-lib'); const app = express(); app.use(express.json()); const SOFTWARE_CONFIG = { developerName: process.env.VERIFACTU_DEVELOPER_NAME || "Tu Empresa S.L.", developerIrsId: process.env.VERIFACTU_DEVELOPER_ID || "B00000000", name: process.env.VERIFACTU_SOFTWARE_NAME || "API VeriFacTu", id: process.env.VERIFACTU_SOFTWARE_ID || "API_001", version: process.env.VERIFACTU_SOFTWARE_VERSION || "1.0.0", number: process.env.VERIFACTU_SOFTWARE_NUMBER || "12345", useOnlyVerifactu: true, useMulti: true, useCurrentMulti: false }; // Helper to convert date strings to Date objects function convertDates(obj) { if (obj.id?.issuedTime) obj.id.issuedTime = new Date(obj.id.issuedTime); if (obj.description?.operationDate) obj.description.operationDate = new Date(obj.description.operationDate); return obj; } // POST /api/verifactu/invoice - Create invoice app.post('/api/verifactu/invoice', async (req, res) => { try { const { invoice, previousInvoice, testing = true } = req.body; convertDates(invoice); if (previousInvoice?.issuedTime) previousInvoice.issuedTime = new Date(previousInvoice.issuedTime); const result = await createVerifactuInvoice(invoice, SOFTWARE_CONFIG, previousInvoice, {}, testing); res.json({ success: true, data: result }); } catch (error) { res.status(400).json({ success: false, error: error.message }); } }); // POST /api/verifactu/invoice/cancel - Cancel invoice app.post('/api/verifactu/invoice/cancel', async (req, res) => { try { const { cancelInvoice, previousInvoice, testing = true } = req.body; convertDates(cancelInvoice); if (previousInvoice?.issuedTime) previousInvoice.issuedTime = new Date(previousInvoice.issuedTime); const result = await cancelVerifactuInvoice(cancelInvoice, SOFTWARE_CONFIG, previousInvoice, {}, testing); res.json({ success: true, data: result }); } catch (error) { res.status(400).json({ success: false, error: error.message }); } }); // GET /api/verifactu/health - Health check app.get('/api/verifactu/health', (req, res) => { res.json({ status: 'ok', service: 'VeriFacTu API', version: '1.0.0' }); }); app.listen(3000, () => console.log('VeriFacTu API running on port 3000')); ``` ```bash # Create invoice via REST API curl -X POST http://localhost:3000/api/verifactu/invoice \ -H "Content-Type: application/json" \ -d '{ "invoice": { "issuer": { "irsId": "99999990S", "name": "Mi Empresa S.L." }, "recipient": { "irsId": "B87654321", "name": "Cliente S.A.", "country": "ES" }, "id": { "number": "FAC-2024-001", "issuedTime": "2024-06-27T10:00:00.000Z" }, "type": "F1", "description": { "text": "Servicios de consultoría" }, "vatLines": [{ "vatOperation": "S1", "base": 1000, "rate": 21, "amount": 210, "vatKey": "01" }], "total": 1210, "amount": 210 }, "testing": true }' # Cancel invoice via REST API curl -X POST http://localhost:3000/api/verifactu/invoice/cancel \ -H "Content-Type: application/json" \ -d '{ "cancelInvoice": { "issuer": { "irsId": "99999990S", "name": "Mi Empresa S.L." }, "id": { "number": "FAC-2024-001", "issuedTime": "2024-06-27T10:00:00.000Z" } }, "testing": true }' ``` -------------------------------- ### Create VeriFacTu Invoice with Node.js Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Generates a new electronic invoice compliant with VeriFacTu specifications using the verifactu-node-lib. It requires software and invoice details, and optionally accepts previous invoice information for chaining. The function returns the generated XML (base64 encoded), a QR code, chain information, and AEAT endpoint URLs. Ensure the 'verifactu-node-lib' is installed via npm. ```typescript import { createVerifactuInvoice, Invoice, Software, PreviousInvoiceId } from 'verifactu-node-lib'; // Software configuration (required for all operations) const software: Software = { developerName: "Mi Empresa Desarrolladora S.L.", developerIrsId: "B12345678", name: "Mi Software de Facturación", id: "SOFT_001", version: "1.0.0", number: "12345", useOnlyVerifactu: true, useMulti: true, useCurrentMulti: false }; // Invoice data const invoice: Invoice = { issuer: { irsId: "99999990S", name: "Mi Empresa S.L." }, recipient: { irsId: "B87654321", name: "Cliente S.A.", country: "ES" }, id: { number: "FAC-2024-001", issuedTime: new Date("2024-06-27T10:00:00.000Z") }, type: "F1", // F1=Complete, F2=Simplified, R1-R5=Corrective description: { text: "Servicios de consultoría tecnológica", operationDate: new Date("2024-06-27T09:00:00.000Z") }, vatLines: [ { vatOperation: "S1", // S1/S2=Subject, E1-E6=Exempt, N1/N2=Not subject base: 1000.00, rate: 21, amount: 210.00, vatKey: "01" // VAT regime key (01=General) } ], total: 1210.00, amount: 210.00 }; // Optional: Previous invoice for chaining const previousInvoice: PreviousInvoiceId = { issuerIrsId: "99999990S", number: "FAC-2024-000", issuedTime: new Date("2024-06-26T10:00:00.000Z"), hash: "abc123def456789012345678901234567890abcdef123456789012345678901234" }; try { const result = await createVerifactuInvoice( invoice, software, previousInvoice, // null for first invoice {}, true // isTesting (true for test environment) ); console.log('QR Code (data URL):', result.qrcode); console.log('Chain info for next invoice:', result.chainInfo); console.log('XML (base64):', result.verifactuXml); console.log('WSDL URL:', result.wsld); console.log('Endpoint URL:', result.endpoint); console.log('Hash:', result.hash); // Decode XML for inspection const xmlDecoded = Buffer.from(result.verifactuXml, 'base64').toString('utf8'); console.log('Decoded XML:', xmlDecoded); } catch (error) { console.error('Error creating invoice:', error.message); } // Result structure: // { // qrcode: "data:image/png;base64,...", // chainInfo: { issuerIrsId: "99999990S", number: "FAC-2024-001", issuedTime: Date, hash: "..." }, // verifactuXml: "PD94bWwgdmVyc2...", // wsld: "https://prewww1.aeat.es/.../SistemaFacturacion.wsdl", // endpoint: "https://prewww1.aeat.es/.../VerifactuSOAP", // hash: "ABC123..." // } ``` -------------------------------- ### VAT Operations and Regime Keys Reference Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Reference for configuring VAT lines with different operation types and regime keys. ```APIDOC ## VAT Operations and Regime Keys Reference This section provides details on configuring VAT lines with various operation types and regime keys as used by the VeriFacTu API. ### VAT Operations - **S1**: Standard VAT (Subject operation) - **E1-E6**: Exempt operations (e.g., E1 for Art.20, E2 for Art.21) - **N1-N2**: Not subject operations (e.g., N1 for Art.7) ### Regime Keys (`vatKey`) Common `vatKey` values include: - **"01"**: General regime - **"02"**: Export - **"03"**: Used goods, art objects, antiques - **"04"**: Investment gold - **"05"**: Travel agencies - **"07"**: Cash accounting - **"08"**: IPSI/IGIC operations - **"11"**: Business premises rental - **"17"**: Retail trader regime - **"18"**: Small business regime ### Example Usage (TypeScript) ```typescript import { VatLine } from 'verifactu-node-lib'; // Standard VAT (S1) const standardVat: VatLine = { vatOperation: "S1", base: 1000.00, rate: 21, amount: 210.00, vatKey: "01" }; // Exempt operation (E1) const exemptVat: VatLine = { vatOperation: "E1", base: 1000.00, rate: 0, amount: 0, vatKey: "02" }; ``` ``` -------------------------------- ### Reference Verifactu VAT Operations and Regime Keys Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt This TypeScript snippet provides a reference for configuring VAT lines within VeriFacTu invoices. It illustrates different VAT operations such as standard, surcharge, exempt, and non-subject operations, along with common regime keys. ```typescript import { VatLine } from 'verifactu-node-lib'; // Subject operation (S1) - Standard VAT const standardVat: VatLine = { vatOperation: "S1", base: 1000.00, rate: 21, amount: 210.00, vatKey: "01" // General regime }; // Subject operation with surcharge (S1) - Equivalence surcharge const surchargeVat: VatLine = { vatOperation: "S1", base: 1000.00, rate: 21, amount: 210.00, rate2: 5.2, // Equivalence surcharge rate amount2: 52.00, // Equivalence surcharge amount vatKey: "01" }; // Exempt operation (E1-E6) const exemptVat: VatLine = { vatOperation: "E1", // E1=Art.20, E2=Art.21, E3=Art.22, E4=Art.23-24, E5=Art.25, E6=Other base: 1000.00, rate: 0, amount: 0, vatKey: "02" // Export }; // Not subject operation (N1-N2) const notSubjectVat: VatLine = { vatOperation: "N1", // N1=Art.7, N2=Localization rules base: 1000.00, rate: 0, vatKey: "07" }; // Common vatKey values: // "01" - General regime // "02" - Export // "03" - Used goods, art objects, antiques // "04" - Investment gold // "05" - Travel agencies // "07" - Cash accounting // "08" - IPSI/IGIC operations // "11" - Business premises rental // "17" - Retail trader regime // "18" - Small business regime ``` -------------------------------- ### Create Simplified Invoice (F2) - TypeScript Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Creates a simplified Verifactu invoice (type F2) without requiring recipient identification, suitable for retail sales. Uses the 'createVerifactuInvoice' function with specific invoice details and software configuration. The output includes the hash of the created invoice. ```typescript import { createVerifactuInvoice, Invoice, Software } from 'verifactu-node-lib'; const software: Software = { developerName: "Mi Empresa Desarrolladora S.L.", developerIrsId: "B12345678", name: "Mi Software de Facturación", id: "SOFT_001", version: "1.0.0", number: "12345", useOnlyVerifactu: true, useMulti: true, useCurrentMulti: false }; const simplifiedInvoice: Invoice = { issuer: { irsId: "99999990S", name: "Mi Empresa S.L." }, // No recipient for simplified invoices id: { number: "SIMP-001", issuedTime: new Date("2024-06-27T14:00:00.000Z") }, type: "F2", // Simplified invoice type description: { text: "Venta en mostrador" }, vatLines: [ { vatOperation: "S1", base: 50.00, rate: 21, amount: 10.50, vatKey: "01" } ], total: 60.50, amount: 10.50 }; const result = await createVerifactuInvoice(simplifiedInvoice, software, null, {}, true); console.log('Simplified invoice hash:', result.chainInfo.hash); ``` -------------------------------- ### Invoice Management API Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Endpoints for creating and canceling VeriFacTu invoices. These endpoints utilize the verifactu-node-lib to interact with the VeriFacTu service. ```APIDOC ## POST /api/verifactu/invoice ### Description Creates a new VeriFacTu invoice. ### Method POST ### Endpoint /api/verifactu/invoice ### Parameters #### Request Body - **invoice** (object) - Required - The invoice details. - **previousInvoice** (object) - Optional - Details of the previous invoice if applicable. - **testing** (boolean) - Optional - Set to true for testing purposes, defaults to true. ### Request Example ```json { "invoice": { "issuer": { "irsId": "99999990S", "name": "Mi Empresa S.L." }, "recipient": { "irsId": "B87654321", "name": "Cliente S.A.", "country": "ES" }, "id": { "number": "FAC-2024-001", "issuedTime": "2024-06-27T10:00:00.000Z" }, "type": "F1", "description": { "text": "Servicios de consultoría" }, "vatLines": [{ "vatOperation": "S1", "base": 1000, "rate": 21, "amount": 210, "vatKey": "01" }], "total": 1210, "amount": 210 }, "testing": true } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (object) - The result of the invoice creation. #### Response Example ```json { "success": true, "data": { ... } } ``` ## POST /api/verifactu/invoice/cancel ### Description Cancels an existing VeriFacTu invoice. ### Method POST ### Endpoint /api/verifactu/invoice/cancel ### Parameters #### Request Body - **cancelInvoice** (object) - Required - The details of the invoice to cancel. - **previousInvoice** (object) - Optional - Details of the previous invoice if applicable. - **testing** (boolean) - Optional - Set to true for testing purposes, defaults to true. ### Request Example ```json { "cancelInvoice": { "issuer": { "irsId": "99999990S", "name": "Mi Empresa S.L." }, "id": { "number": "FAC-2024-001", "issuedTime": "2024-06-27T10:00:00.000Z" } }, "testing": true } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (object) - The result of the invoice cancellation. #### Response Example ```json { "success": true, "data": { ... } } ``` ``` -------------------------------- ### Create Corrective Invoice (R1) - TypeScript Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Generates a corrective Verifactu invoice (type R1) to amend a previous invoice. This function requires referencing the original invoice being corrected and includes details for the correction, such as credit notes and VAT adjustments. The output confirms the creation of the corrective invoice. ```typescript import { createVerifactuInvoice, Invoice, Software } from 'verifactu-node-lib'; const software: Software = { developerName: "Mi Empresa Desarrolladora S.L.", developerIrsId: "B12345678", name: "Mi Software de Facturación", id: "SOFT_001", version: "1.0.0", number: "12345", useOnlyVerifactu: true, useMulti: true, useCurrentMulti: false }; const correctiveInvoice: Invoice = { issuer: { irsId: "99999990S", name: "Mi Empresa S.L." }, recipient: { irsId: "B87654321", name: "Cliente S.A.", country: "ES" }, id: { number: "RECT-001", issuedTime: new Date("2024-06-28T10:00:00.000Z") }, type: "R1", // R1=Error in law, R2=Art. 80.1, R3=Art. 80.2, R4=Art. 80.3-6, R5=Simplified creditNote: { ids: [{ number: "FAC-2024-001", issuedTime: new Date("2024-06-27T10:00:00.000Z") }], style: "S", // S=Substitution, I=Difference creditBase: 100.00, creditVat: 21.00 }, description: { text: "Rectificación de factura FAC-2024-001" }, vatLines: [ { vatOperation: "S1", base: -100.00, // Negative for corrections rate: 21, amount: -21.00, vatKey: "01" } ], total: -121.00, amount: -21.00 }; const result = await createVerifactuInvoice(correctiveInvoice, software, null, {}, true); console.log('Corrective invoice created:', result.chainInfo.number); ``` -------------------------------- ### TypeScript Invoice Type Definitions for Verifactu Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Defines essential TypeScript types for representing Spanish electronic invoice data. Includes types for invoice classification, VAT statuses, identification details, issuer/recipient information, and the structure of results returned by the Verifactu library. These types are crucial for ensuring data integrity and correct formatting when generating invoices. ```typescript // Invoice types type InvoiceType = "F1" | "F2" | "F3" | "R1" | "R2" | "R3" | "R4" | "R5"; // F1=Complete, F2=Simplified, F3=Replacement, R1-R5=Corrective // VAT operations type VatType = "S1" | "S2"; // Subject to VAT type VatExemptReason = "E1" | "E2" | "E3" | "E4" | "E5" | "E6"; // Exempt type VatNotSubjectReason = "N1" | "N2"; // Not subject // Invoice identification interface InvoiceId { number: string; issuedTime: Date; replacement?: boolean; } // Previous invoice for chaining interface PreviousInvoiceId { issuerIrsId: string; number: string; issuedTime: Date; hash: string; } // Issuer information interface Issuer { irsId: string; // Spanish NIF/CIF name: string; } // Recipient with Spanish tax ID interface PartnerIrs { irsId: string; name: string; country?: CountryCode; } // Recipient with foreign ID interface PartnerOther { idType: "02" | "03" | "04" | "05" | "06" | "07"; id: string; name: string; country: CountryCode; } // Result from invoice operations interface VerifactuResult { qrcode: string | null; // QR code as data URL (null for cancellations) chainInfo: PreviousInvoiceId; // Info for next invoice in chain verifactuXml: string; // Base64 encoded XML wsld: string; // WSDL URL endpoint: string; // SOAP endpoint URL hash: string; // SHA-256 hash } ``` -------------------------------- ### Health Check API Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Endpoint to check the health status of the VeriFacTu API service. ```APIDOC ## GET /api/verifactu/health ### Description Checks the health status of the VeriFacTu API service. ### Method GET ### Endpoint /api/verifactu/health ### Response #### Success Response (200) - **status** (string) - The health status of the service (e.g., 'ok'). - **service** (string) - The name of the service. - **version** (string) - The version of the service. #### Response Example ```json { "status": "ok", "service": "VeriFacTu API", "version": "1.0.0" } ``` ``` -------------------------------- ### Cancel Verifactu Invoice - TypeScript Source: https://context7.com/zarpilla/verifactu-node-lib/llms.txt Cancels a previously issued VeriFacTu invoice using the 'cancelVerifactuInvoice' function. It requires invoice details, software configuration, and previous invoice information for chaining. This operation does not generate QR codes and returns cancellation XML and chain information. ```typescript import { cancelVerifactuInvoice, CancelInvoice, Software, PreviousInvoiceId } from 'verifactu-node-lib'; const software: Software = { developerName: "Mi Empresa Desarrolladora S.L.", developerIrsId: "B12345678", name: "Mi Software de Facturación", id: "SOFT_001", version: "1.0.0", number: "12345", useOnlyVerifactu: true, useMulti: true, useCurrentMulti: false }; const cancelInvoice: CancelInvoice = { issuer: { irsId: "99999990S", name: "Mi Empresa S.L." }, id: { number: "FAC-2024-001", issuedTime: new Date("2024-06-27T10:00:00.000Z") } }; // Previous invoice/operation for chaining const previousInvoice: PreviousInvoiceId = { issuerIrsId: "99999990S", number: "FAC-2024-001", issuedTime: new Date("2024-06-27T10:00:00.000Z"), hash: "def456abc789012345678901234567890abcdef123456789012345678901234" }; try { const result = await cancelVerifactuInvoice( cancelInvoice, software, previousInvoice, {}, true // isTesting ); console.log('Cancellation chain info:', result.chainInfo); console.log('Cancellation XML (base64):', result.verifactuXml); console.log('QR code:', result.qrcode); // null for cancellations } catch (error) { console.error('Error cancelling invoice:', error.message); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.