### Complete Workflow Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-json-service-v4.md A comprehensive example demonstrating the initialization of the service, building a CFDI from data, configuring options, and issuing the document. ```APIDOC ## Complete Workflow Example ```javascript const IssueJsonServiceV4 = require("sw-sdk-nodejs").IssueJsonServiceV4; const fs = require("fs"); // Initialize service const params = { user: "company_user", password: "secure_password", url: "https://services.test.sw.com.mx" }; const service = IssueJsonServiceV4.Set(params); // Build CFDI from data const invoiceData = { version: "4.0", fecha: new Date().toISOString().replace(/Z$/, ""), emisor: { rfc: "COMPANY123456", nombre: "Mi Empresa SA de CV", regimenFiscal: "601" }, receptor: { rfc: "CUSTOMER987654", nombre: "Cliente Importante", usoCFDI: "G03" }, conceptos: [ { claveProdServ: "01010101", cantidad: 100, claveUnidad: "H87", unidad: "Pieza", descripcion: "Producto A", valorUnitario: 1000.00, importe: 100000.00 }, { claveProdServ: "01020101", cantidad: 2, claveUnidad: "H87", unidad: "Pieza", descripcion: "Producto B", valorUnitario: 5000.00, importe: 10000.00 } ], subTotal: 110000.00, moneda: "MXN", total: 127600.00, tipoDeComprobante: "I", formaPago: "01", metodoPago: "PUE", lugarExpedicion: "06500" }; // Configure V4 options const v4Options = { customId: "INV-2024-" + Date.now(), pdf: true, email: ["customer@example.com", "accounting@example.com"] }; // Issue the document service.ServiceV4IssueJsonV4(invoiceData, (err, res) => { if (err) { console.error("Error issuing document:", err.message); return; } if (res.status === 'success') { console.log("✓ Document issued successfully"); console.log(" UUID:", res.data.uuid); console.log(" Custom ID:", v4Options.customId); // Save results fs.writeFileSync("invoice-signed.xml", res.data.cfdi); fs.writeFileSync("tfd.txt", res.data.tfd); console.log(" Files saved: invoice-signed.xml, tfd.txt"); console.log(" Emails sent to: " + v4Options.email.join(", ")); } else { console.error("✗ Issue failed:", res.message); } }, v4Options); ``` ``` -------------------------------- ### Install SW SDK Node.js Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/README.md Use npm to install the SW SDK Node.js package. ```bash npm install sw-sdk-nodejs ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service-v4.md A comprehensive example demonstrating the full workflow of reading an unsigned CFDI, configuring V4 features, and issuing/stamping the document. ```APIDOC ## Complete Workflow Example ```javascript const fs = require("fs"); const IssueServiceV4 = require("sw-sdk-nodejs").IssueServiceV4; // Configuration const params = { user: "demo", password: "123456789", url: "https://services.test.sw.com.mx" }; // Read unsigned CFDI document const xml = fs.readFileSync("cfdi.xml", "utf8"); // Configure V4 features const customServiceV4 = { customId: "INVOICE-2024-000123", pdf: true, email: ["customer@company.com", "archive@company.com"] }; // Issue and stamp the document IssueServiceV4.Set(params).ServiceV4IssueV4(xml, (err, res) => { if (err) { console.error("Issue failed:", err.message); return; } if (res.status !== 'success') { console.error("Service error:", res.message); return; } // Extract results console.log("Document issued successfully"); console.log("UUID:", res.data.uuid); console.log("Custom ID:", customServiceV4.customId); console.log("TFD:", res.data.tfd); console.log("Signed CFDI:", res.data.cfdi); // Save the signed CFDI fs.writeFileSync("cfdi-signed.xml", res.data.cfdi); // Save the TFD fs.writeFileSync("tfd.txt", res.data.tfd); console.log("Files saved successfully"); }, false, customServiceV4); ``` ``` -------------------------------- ### Custom Service V4 with All Options Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-json-service-v4.md Example demonstrating how to configure all optional properties for the customServiceV4 parameter. ```javascript // All options const customServiceV4 = { customId: "ORD-2024-12345", pdf: true, email: ["customer@company.com", "sales@company.com"] }; ``` -------------------------------- ### Complete Cancellation Workflow Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/cancelation-retention-service.md This example demonstrates the full cancellation process using credentials and a digital certificate. It includes preparing parameters, creating the service instance, and handling the cancellation response. ```javascript const CancelationRetentionService = require("sw-sdk-nodejs").CancelationRetentionService; const fs = require("fs"); // Step 1: Prepare cancellation parameters const params = { user: "company_user", password: "secure_password", url: "https://services.test.sw.com.mx", uuid: "a1b2c3d4-e5f6-47g8-h9i0-j1k2l3m4n5o6", passwordCer: "certificate_password", rfc: "COMPANY123456", b64Cer: fs.readFileSync("certificate.cer", "utf8"), b64Key: fs.readFileSync("private.key", "utf8"), motivo: "02", folioSustitucion: null }; // Step 2: Create service and cancel const service = CancelationRetentionService.Set(params); service.CancelationByCSD((err, res) => { if (err) { console.error("❌ Cancellation error:", err.message); return; } if (res.status === 'success') { console.log("✓ Retention cancelled successfully"); console.log(" UUID:", params.uuid); console.log(" Cancellation response code:", res.data.folioStatus); } else { console.error("✗ Cancellation failed:", res.message); if (res.messageDetail) { console.error(" Details:", res.messageDetail); } } }); ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/cancelation-retention-service.md This example demonstrates the complete workflow for cancelling a retention using the `CancelationByCSD` method. It includes preparing cancellation parameters, initializing the service, and handling the response. ```APIDOC ## Complete Workflow Example ```javascript const CancelationRetentionService = require("sw-sdk-nodejs").CancelationRetentionService; const fs = require("fs"); // Step 1: Prepare cancellation parameters const params = { user: "company_user", password: "secure_password", url: "https://services.test.sw.com.mx", uuid: "a1b2c3d4-e5f6-47g8-h9i0-j1k2l3m4n5o6", passwordCer: "certificate_password", rfc: "COMPANY123456", b64Cer: fs.readFileSync("certificate.cer", "utf8"), b64Key: fs.readFileSync("private.key", "utf8"), motivo: "02", folioSustitucion: null }; // Step 2: Create service and cancel const service = CancelationRetentionService.Set(params); service.CancelationByCSD((err, res) => { if (err) { console.error("❌ Cancellation error:", err.message); return; } if (res.status === 'success') { console.log("✓ Retention cancelled successfully"); console.log(" UUID:", params.uuid); console.log(" Cancellation response code:", res.data.folioStatus); } else { console.error("✗ Cancellation failed:", res.message); if (res.messageDetail) { console.error(" Details:", res.messageDetail); } } }); ``` ``` -------------------------------- ### Token-Based Authentication Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Example of setting up and using token-based authentication with StampService. Ensure the token is manually renewed every 2 hours. ```javascript const StampService = require("sw-sdk-nodejs").StampService; const params = { url: "https://services.test.sw.com.mx", token: "T2lYQ0t4L0R..." // Manually managed token }; StampService.Set(params).StampV1(xml, callback); ``` -------------------------------- ### Configure All CustomServiceV4 Options Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md Example demonstrating how to configure all available options for the customServiceV4 object, including customId, pdf, and email addresses. ```javascript // All options const customServiceV4 = { customId: "INV-2024-001", pdf: true, email: ["accounting@company.com", "archive@company.com"] }; ``` -------------------------------- ### Credential-Based Authentication Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Example of setting up and using credential-based authentication with StampService. The service handles automatic token renewal. ```javascript const StampService = require("sw-sdk-nodejs").StampService; const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; StampService.Set(params).StampV1(xml, callback); // Token automatically renewed if expired ``` -------------------------------- ### Complete Stamp Retention Example with Error Handling Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-retention-service.md A full example demonstrating how to stamp a retention document using credentials-based authentication. Includes reading the document, calling the StampV3 method, and handling both success and various error scenarios. ```javascript const fs = require("fs"); const StampRetentionService = require("sw-sdk-nodejs").StampRetentionService; const params = { user: "company_user", password: "secure_password", url: "https://services.test.sw.com.mx" }; // Read the signed retention document const retentionXml = fs.readFileSync("retention-signed.xml", "utf8"); const service = StampRetentionService.Set(params); service.StampV3(retentionXml, (err, res) => { if (err) { console.error("Error stamping retention:", err); if (err.message.includes("XML")) { console.error("Invalid XML format"); } else if (err.message.includes("signature")) { console.error("Document signature verification failed"); } else if (err.message.includes("token")) { console.error("Authentication failed - token may have expired"); } return; } if (res.status === 'success') { console.log("✓ Retention document stamped successfully"); // Extract results console.log(" Folio:", res.data.folio); console.log(" UUID:", res.data.uuid); console.log(" Timestamp:", res.data.timestamp); // Save the stamped retention fs.writeFileSync("retention-stamped.xml", res.data.cfdi); console.log(" Saved to: retention-stamped.xml"); } else { console.error("✗ Stamping failed:", res.message); if (res.messageDetail) { console.error(" Details:", res.messageDetail); } } }); ``` -------------------------------- ### Custom Service V4 with PDF Option Only Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-json-service-v4.md Example showing how to enable PDF generation by setting the pdf option to true. ```javascript // Only PDF const customServiceV4 = { pdf: true }; ``` -------------------------------- ### Complete Stamp Service V4 Example with Error Handling Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md A comprehensive example demonstrating how to stamp a document using Stamp Service V4, including setting parameters, handling potential errors, and processing the response. ```javascript const fs = require("fs"); const StampServiceV4 = require("sw-sdk-nodejs").StampServiceV4; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const xml = fs.readFileSync("invoice.xml", "utf8"); const customServiceV4 = { customId: "INVOICE-2024-12345", pdf: true, email: ["finance@company.com", "archive@company.com"] }; StampServiceV4.Set(params).ServiceV4StampV1(xml, (err, res) => { if (err) { if (err.message.includes("customId")) { console.error("Invalid custom ID"); } else if (err.message.includes("email")) { console.error("Invalid email addresses"); } else { console.error("Stamping error:", err); } return; } if (res.status === 'success') { console.log("Document stamped successfully"); console.log("TFD:", res.data.tfd); console.log("Notifications sent to configured emails"); } else { console.error("Stamping failed:", res.message); } }, false, customServiceV4); ``` -------------------------------- ### Query Account Balance with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md This example shows how to query your account balance using an authentication token. The 'token', 'url', and 'urlApi' parameters are required. ```javascript const AccountBalanceService = require("sw-sdk-nodejs").AccountBalance; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }; AccountBalanceService.Set(params).GetAccountBalance((err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }); ``` -------------------------------- ### CustomServiceV4 Examples Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service-v4.md Illustrates various ways to configure the customServiceV4 object, including setting all options, only PDF generation, email as a string, and an empty object for default settings. ```javascript // All options const customServiceV4 = { customId: "FACT-2024-456", pdf: true, email: ["customer@example.com", "accounting@example.com"] }; ``` ```javascript // Only PDF generation const customServiceV4 = { pdf: true }; ``` ```javascript // Email as comma-separated string const customServiceV4 = { email: "invoice@customer.com,accounting@customer.com" }; ``` ```javascript // Empty object (all defaults to false) const customServiceV4 = {}; ``` -------------------------------- ### Base64 Encoding Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service.md Demonstrates how to encode an XML document to base64 format before sending it to the Stamp Service. ```APIDOC ## Base64 Encoding ### Description To send XML in base64 format, you need to encode the XML string. ### Code Example ```javascript const fs = require("fs"); const StampService = require("sw-sdk-nodejs").StampService; const xml = fs.readFileSync("signed-document.xml", "utf8"); const xmlB64 = Buffer.from(xml, "utf8").toString("base64"); StampService.Set(params).StampV1(xmlB64, (err, res) => { // ... }, true); // Set isB64 to true ``` ``` -------------------------------- ### Configure CustomServiceV4 with Comma-Separated Emails Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md Example illustrating how to provide email addresses as a comma-separated string in the customServiceV4 object. ```javascript // Email as comma-separated string const customServiceV4 = { email: "user1@example.com,user2@example.com" }; ``` -------------------------------- ### Configure CustomServiceV4 for PDF Generation Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md Example showing how to configure the customServiceV4 object to only enable PDF generation by setting the pdf option to true. ```javascript // Only PDF generation const customServiceV4 = { pdf: true }; ``` -------------------------------- ### Configure Empty CustomServiceV4 Object Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md Example of an empty customServiceV4 object, which will use default settings (all options set to false or empty). ```javascript // Empty object (all defaults to false) const customServiceV4 = {}; ``` -------------------------------- ### Pool Service Instances Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md For performance-critical applications, consider pooling service instances. This example shows creating a small pool with auto-renewal capabilities. ```javascript // Create a small pool of service instances with auto-renewal const services = Array(5).fill(null).map(() => StampService.Set({ user, password, url }) ); ``` -------------------------------- ### Example Usage of ServiceCallback Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/types.md Illustrates how to use the ServiceCallback function to handle potential errors and process successful responses from asynchronous service methods. ```javascript service.someMethod((err, res) => { if (err) { console.error("Error:", err.message); } else { console.log("Success:", res.data); } }); ``` -------------------------------- ### Authentication - Get Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md Obtains an authentication token required to consume SW sapien® services. Requires valid user credentials. ```APIDOC ## Authentication - Get Token ### Description Method to obtain an authentication token indispensable for consuming SW sapien® services. Requires a valid user and password. ### Method `Authentication.auth(params).Token(callback)` ### Parameters #### Parameters Object (`params`) - **url** (string) - Required - The URL of the SW services. - **user** (string) - Required - The user credentials. - **password** (string) - Required - The password for the user credentials. ### Request Example ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; Authentication.auth(params).Token((err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }); ``` ### Response #### Success Response - **token** (string) - The authentication token. - **validity** (string) - The validity period of the token (e.g., '2 hrs'). #### Response Example ```json { "token": "your_auth_token", "validity": "2 hrs" } ``` ``` -------------------------------- ### Initialize StampService Without URL Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/errors.md This error occurs when StampService is initialized without the required 'url' or 'urlApi' parameter. Ensure these parameters are provided during service setup. ```javascript // Throws error StampService.Set({ user: "demo", password: "123456789" // Missing url/urlApi }); ``` ```javascript const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; StampService.Set(params); ``` -------------------------------- ### Complete CFDI Issuance Workflow Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service-v4.md A comprehensive example demonstrating the full workflow for issuing and stamping a CFDI document using Issue Service V4. Includes reading the XML, configuring custom service options, handling responses, and saving output files. ```javascript const fs = require("fs"); const IssueServiceV4 = require("sw-sdk-nodejs").IssueServiceV4; // Configuration const params = { user: "demo", password: "123456789", url: "https://services.test.sw.com.mx" }; // Read unsigned CFDI document const xml = fs.readFileSync("cfdi.xml", "utf8"); // Configure V4 features const customServiceV4 = { customId: "INVOICE-2024-000123", pdf: true, email: ["customer@company.com", "archive@company.com"] }; // Issue and stamp the document IssueServiceV4.Set(params).ServiceV4IssueV4(xml, (err, res) => { if (err) { console.error("Issue failed:", err.message); return; } if (res.status !== 'success') { console.error("Service error:", res.message); return; } // Extract results console.log("Document issued successfully"); console.log("UUID:", res.data.uuid); console.log("Custom ID:", customServiceV4.customId); console.log("TFD:", res.data.tfd); console.log("Signed CFDI:", res.data.cfdi); // Save the signed CFDI fs.writeFileSync("cfdi-signed.xml", res.data.cfdi); // Save the TFD fs.writeFileSync("tfd.txt", res.data.tfd); console.log("Files saved successfully"); }, false, customServiceV4); ``` -------------------------------- ### Authenticate and Get Token with Authentication Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/README.md Obtain an authentication token using user credentials. This token can then be used for subsequent service calls that require authentication. ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; const auth = Authentication.auth(params); auth.Token((err, res) => { if (err) { console.error("Auth failed:", err); return; } const token = res.data.token; console.log("Token valid for 2 hours:", token); // Use token in service calls const StampService = require("sw-sdk-nodejs").StampService; StampService.Set({ token, url: params.url }) .StampV1(xml, callback); }); ``` -------------------------------- ### Stamp Retention XML in Base64 using Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md Use this example to stamp retention XML provided in Base64 format with an authentication token. The XML must be sealed and valid before encoding. ```javascript const fs = require("fs"); const path = require("path"); const StampRetentionService = require("sw-sdk-nodejs").StampRetentionService; const isBase64 = true; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const xmlPath = path.join(__dirname, "fileRetentionSign.xml"); const xml = fs.readFileSync(xmlPath, "utf8"); const xmlB64 = Buffer.from(xml, "utf8").toString("base64"); StampRetentionService.Set(params).StampV3(xmlB64, (err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }, isBase64); ``` -------------------------------- ### Obtain Authentication Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md Use this method to get an authentication token required for consuming SW Sapien services. Ensure you have valid user credentials. The generated token is valid for 2 hours. ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; const auth = Authentication.auth(params); auth.Token((err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }); ``` -------------------------------- ### Basic Stamping Usage with SW SDK Node.js Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/README.md Demonstrates how to initialize the StampService with credentials and stamp an XML file using StampV1. Ensure the XML file exists and credentials are valid. ```javascript const StampService = require("sw-sdk-nodejs").StampService; const fs = require("fs"); // Initialize service with credentials const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; // Read XML and stamp const xml = fs.readFileSync("invoice.xml", "utf8"); StampService.Set(params).StampV1(xml, (err, res) => { if (err) { console.error("Error:", err); } else { console.log("Stamped successfully:", res.data.tfd); } }); ``` -------------------------------- ### Example Retention XML Structure Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-retention-service.md This is an example of a valid retention XML structure required by the Stamp Retention Service. It includes essential elements like Emisor, Receptor, Periodo, Totales, Impuestos, and Signature. ```xml ``` -------------------------------- ### Initialize CancelationRetentionService with Token and XML Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/cancelation-retention-service.md Configure and create an instance of CancelationRetentionService using an authentication token and a signed cancellation XML. Ensure the `token`, `url`, and `xml` parameters are correctly provided. ```javascript const CancelationRetentionService = require("sw-sdk-nodejs").CancelationRetentionService; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", xml: signedCancellationXml }; const cancelRetService = CancelationRetentionService.Set(params); ``` -------------------------------- ### Create Authentication Service Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/authentication.md Create an instance of the AuthenticationService by providing your SW service URL, username, and password. This instance is then used to perform authentication operations. ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; const auth = Authentication.auth(params); ``` -------------------------------- ### Get Account Balance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/account-balance-service.md Retrieve the current stamp balance for the authenticated account. The result is passed to a callback function. ```javascript const AccountBalance = require("sw-sdk-nodejs").AccountBalance; const params = { user: "demo", password: "123456789", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }; AccountBalance.Set(params).GetAccountBalance((err, res) => { if (err) { console.error("Failed to get balance:", err); return; } if (res.status === 'success') { console.log("Current balance:", res.data.balance, "stamps"); } else { console.error("Error:", res.message); } }); ``` -------------------------------- ### Configure StampServiceV4 Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md Use the static Set method to create a configured instance of StampServiceV4. Provide authentication credentials (token or user/password) and the service URL. The urlApi parameter is optional. ```javascript const StampServiceV4 = require("sw-sdk-nodejs").StampServiceV4; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const stampServiceV4 = StampServiceV4.Set(params); ``` -------------------------------- ### Authentication Methods Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service-v4.md Demonstrates how to set up authentication for the Issue Service V4 using either token-based or credentials-based methods. ```APIDOC ## Authentication The service supports two authentication methods: 1. **Token-based (recommended for production):** ```javascript IssueServiceV4.Set({ token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }) ``` 2. **Credentials-based (token auto-renewal):** ```javascript IssueServiceV4.Set({ user: "demo", password: "123456789", url: "https://services.test.sw.com.mx" }) ``` ``` -------------------------------- ### Configure StampRetentionService Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-retention-service.md Use the static Set method to create a configured instance of StampRetentionService. Provide authentication token and service URL. ```javascript const StampRetentionService = require("sw-sdk-nodejs").StampRetentionService; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const stampRetentionService = StampRetentionService.Set(params); ``` -------------------------------- ### Import Authentication Module Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/authentication.md Import the Authentication module from the SW SDK for Node.js. This is the first step before using any authentication-related functionalities. ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; ``` -------------------------------- ### CustomServiceV4 Validation Error Example Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service-v4.md Demonstrates how a customId exceeding the 100-character limit triggers a validation error when attempting to set parameters for IssueServiceV4. ```javascript // This will throw validation error const invalid = { customId: "A".repeat(101), // Exceeds 100 chars }; try { IssueServiceV4.Set(params).ServiceV4IssueV1(xml, callback, false, invalid); } catch (err) { console.error("Validation error:", err.message); } ``` -------------------------------- ### Authentication.auth(params) Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/authentication.md Creates an instance of the AuthenticationService configured with the provided parameters. This is the entry point for using the authentication service. ```APIDOC ## Authentication.auth(params) ### Description Creates an instance of the AuthenticationService configured with the provided parameters. This is the entry point for using the authentication service. ### Method Static method ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (Object) - Required - Configuration object for the AuthenticationService. - **url** (string) - Required - Base URL for SW services (e.g., `https://services.test.sw.com.mx`) - **user** (string) - Required - Username provided by SW - **password** (string) - Required - Password provided by SW ### Request Example ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; const auth = Authentication.auth(params); ``` ### Response #### Success Response - **AuthenticationService** - A configured service instance #### Response Example (Instance of AuthenticationService, not directly representable as JSON) ### Throws - Error: If `params` is empty or missing required credentials ``` -------------------------------- ### Configure StampService Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service.md Use the Set factory method to create a configured instance of StampService. Provide either a token or user/password credentials along with the service URL. ```javascript const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const stampService = StampService.Set(params); ``` -------------------------------- ### Get Account Balance with AccountBalance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/README.md Retrieve the current account balance using the AccountBalance service. This requires specific API endpoint configurations. ```javascript const AccountBalance = require("sw-sdk-nodejs").AccountBalance; const params = { user: "demo", password: "123456789", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }; AccountBalance.Set(params).GetAccountBalance((err, res) => { if (err) { console.error("Error:", err); } else { console.log("Current balance:", res.data.balance, "stamps"); } }); ``` -------------------------------- ### Initialize AccountBalance Service Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/account-balance-service.md Create a configured instance of the Account Balance Service using the Set factory method. Provide authentication details and service URLs. ```javascript const AccountBalance = require("sw-sdk-nodejs").AccountBalance; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }; const balanceService = AccountBalance.Set(params); ``` -------------------------------- ### Manual Token Management with Authentication Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Shows how to manually obtain a token using the Authentication module when using static tokens. The obtained token can then be used for subsequent requests. ```javascript const Authentication = require("sw-sdk-nodejs").Authentication; const auth = Authentication.auth({ url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }); auth.Token((err, res) => { if (!err) { const newToken = res.data.token; // Use this token for the next 2 hours } }); ``` -------------------------------- ### Importing SW SDK Node.js Classes Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/README.md Shows how to import various service classes from the main SWSDK module. These classes are used for authentication, stamping, issuance, cancellation, and account management. ```javascript const SWSDK = require("sw-sdk-nodejs"); // Authentication const Authentication = SWSDK.Authentication; // Stamping (pre-signed documents) const StampService = SWSDK.StampService; const StampServiceV4 = SWSDK.StampServiceV4; const StampRetentionService = SWSDK.StampRetentionService; // Issuance (unsigned documents) const IssueService = SWSDK.IssueService; const IssueServiceV4 = SWSDK.IssueServiceV4; const IssueJsonService = SWSDK.IssueJsonService; const IssueJsonServiceV4 = SWSDK.IssueJsonServiceV4; // Cancellation const CancelationService = SWSDK.CancelationService; const CancelationRetentionService = SWSDK.CancelationRetentionService; // Account management const AccountBalance = SWSDK.AccountBalance; ``` -------------------------------- ### Missing Cancellation Parameters for Specific Method Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/errors.md This error indicates that required parameters for a specific cancellation method are missing. For example, 'folioSustitucion' is required when 'motivo' is '01'. ```javascript // For UUID cancellation - missing folioSustitucion when motivo="01" const params = { url: "https://services.test.sw.com.mx", token: "T2lYQ0t4L0R...", rfc: "EKU9003173C9", uuid: "478569b5-c323-4dc4-91cf-b6e9f6979527", motivo: "01" // Missing folioSustitucion }; ``` ```javascript const params = { // ... all previous params ... motivo: "01", folioSustitucion: "b3641a4b-7177-4323-aaa0-29bd34bf1ff8" // Required for motivo="01" }; ``` -------------------------------- ### Production Configuration Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Configure for production using environment variables for sensitive data like tokens. This enhances security. ```javascript const params = { url: "https://services.sw.com.mx", urlApi: "https://api.sw.com.mx", token: process.env.SW_TOKEN // From secure environment variable }; ``` -------------------------------- ### Timbrado JSON with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md This example demonstrates how to stamp a CFDI using a JSON payload and authenticating with an API token. This is a common and secure method for integrating with the stamping service. ```javascript const IssueJsonService = require("sw-sdk-nodejs").IssueJsonService; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const json = { "version": "4.0", "fecha": "2024-01-01T12:00:00", "emisor": { "rfc": "EKU9003173C9", "nombre": "ESCUELA KEMPER URGATE", "regimenFiscal": "601" }, "receptor": { "rfc": "URE180429TM6", "nombre": "UNIVERSIDAD REGIOMONTANA", "usoCFDI": "G03" }, "conceptos": [ { "claveProdServ": "01010101", "cantidad": 1, "claveUnidad": "H87", "unidad": "Pieza", "descripcion": "Producto de prueba", "valorUnitario": 100.00, "importe": 100.00 } ], "subTotal": 100.00, "moneda": "MXN", "total": 116.00, "tipoDeComprobante": "I", "formaPago": "01", "metodoPago": "PUE", "lugarExpedicion": "06400" }; IssueJsonService.Set(params).IssueJsonV1(json, (err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }); ``` -------------------------------- ### Configure IssueServiceV4 Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service-v4.md Create a configured instance of IssueServiceV4 using the static Set method with authentication token and service URL. ```javascript const IssueServiceV4 = require("sw-sdk-nodejs").IssueServiceV4; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const issueServiceV4 = IssueServiceV4.Set(params); ``` -------------------------------- ### Using CSD Certificates for Cancellation Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Provides an example of how to structure the parameters object for cancellation operations when using CSD certificates, including the Base64 encoded certificate and key. ```javascript const params = { // ... auth params ... b64Cer: b64Cer, b64Key: b64Key, passwordCer: "password_from_sat" }; ``` -------------------------------- ### Initialize CancelationService with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/cancelation-service.md Initialize the CancelationService using the static `Set` method with authentication token and cancellation parameters. Ensure all required parameters for the chosen cancellation method are provided. ```javascript const CancelationService = require("sw-sdk-nodejs").CancelationService; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", rfc: "EKU9003173C9", uuid: "478569b5-c323-4dc4-91cf-b6e9f6979527", motivo: "02", folioSustitucion: null }; const cancelService = CancelationService.Set(params); ``` -------------------------------- ### Timbrado XML in Base64 with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md This example shows how to stamp an XML CFDI by sending its Base64 encoded representation using an authentication token. This is useful when the service expects Base64 input. ```javascript const fs = require("fs"); const path = require("path"); const IssueService = require("sw-sdk-nodejs").IssueService; const isBase64 = true; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const xmlPath = path.join(__dirname, "file.xml"); const xml = fs.readFileSync(xmlPath, "utf8"); const xmlB64 = Buffer.from(xml, "utf8").toString("base64"); IssueService.Set(params).IssueV1(xmlB64, (err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }, isBase64); ``` -------------------------------- ### Configure IssueJsonService Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-json-service.md Use the static `Set` method to create a configured instance of IssueJsonService. Provide authentication details (token or user/password) and the service URL. ```javascript const IssueJsonService = require("sw-sdk-nodejs").IssueJsonService; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const issueJsonService = IssueJsonService.Set(params); ``` -------------------------------- ### Set Account Balance Service with Token Authentication Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/account-balance-service.md Configure the Account Balance Service using a token for authentication. This method is recommended for production environments. ```javascript AccountBalance.Set({ token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }) ``` -------------------------------- ### Automatic Token Renewal for Expired Tokens Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/errors.md When using credential-based authentication, the SDK automatically renews the token before the next request if it has expired. This example shows how the SDK handles token expiration transparently. ```javascript // With credentials - automatic renewal const service = StampService.Set({ user: "demo", password: "123456789", url: "https://services.test.sw.com.mx" }); // First call uses token service.StampV1(xml1, callback); // After 2+ hours - token automatically renewed service.StampV1(xml2, callback); ``` -------------------------------- ### Configure IssueJsonServiceV4 Instance Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-json-service-v4.md Create a configured instance of IssueJsonServiceV4 using the static Set method. Provide authentication token and service URL. ```javascript const IssueJsonServiceV4 = require("sw-sdk-nodejs").IssueJsonServiceV4; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const issueJsonServiceV4 = IssueJsonServiceV4.Set(params); ``` -------------------------------- ### Validate CustomServiceV4 Object with Errors Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/stamp-service-v4.md Demonstrates validation of the customServiceV4 object, highlighting common errors such as exceeding customId length and incorrect pdf type. This example shows how to catch validation errors. ```javascript // Invalid - will throw error const invalid = { customId: "A".repeat(101), // Exceeds 100 chars pdf: "true" // Must be boolean }; try { StampServiceV4.Set(params).ServiceV4StampV1(xml, callback, false, invalid); } catch (validationError) { console.error("Validation error:", validationError.message); } ``` -------------------------------- ### Remove Stamps from Sub-account with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md This example shows how to remove stamps from a child account using token authentication. Provide the target user's ID, the quantity of stamps to remove, and an optional comment. ```javascript const AccountBalanceService = require("sw-sdk-nodejs").AccountBalance; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }; const idUser = "fafb2ac2-62ca-49f8-91de-14cea73b01eb"; const stampsToRemove = 1; const comment = "Prueba JS"; AccountBalanceService.Set(params).RemoveStamps(idUser, stampsToRemove, comment, (err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }); ``` -------------------------------- ### Add Stamps to Sub-account with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/README.md This example demonstrates adding stamps to a child account using token authentication. You need to provide the target user's ID, the quantity of stamps, and an optional comment. ```javascript const AccountBalanceService = require("sw-sdk-nodejs").AccountBalance; const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx" }; const idUser = "fafb2ac2-62ca-49f8-91de-14cea73b01eb"; const stampsToAdd = 1; const comment = "Prueba JS"; AccountBalanceService.Set(params).AddStamps(idUser, stampsToAdd, comment, (err, res) => { if (err) { console.error("Error:", err); } else { console.log(res); } }); ``` -------------------------------- ### Use Tokens in Production Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Prefer using tokens over username/password for production environments. Load tokens from environment variables for better security. ```javascript // ✅ Better for production const params = { token: process.env.SW_TOKEN, url: process.env.SW_URL }; ``` -------------------------------- ### Configure IssueService with Token Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/issue-service.md Configure the IssueService instance using a token for authentication. This is the recommended method for production environments. ```javascript const params = { token: "T2lYQ0t4L0R...", url: "https://services.test.sw.com.mx" }; const issueService = IssueService.Set(params); ``` -------------------------------- ### Import CancelationRetentionService Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/cancelation-retention-service.md Import the CancelationRetentionService class from the SW SDK. ```javascript const CancelationRetentionService = require("sw-sdk-nodejs").CancelationRetentionService; ``` -------------------------------- ### Development/Testing Configuration Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/configuration.md Use these parameters for development and testing environments. Ensure sensitive information is not hardcoded. ```javascript const params = { url: "https://services.test.sw.com.mx", urlApi: "https://api.test.sw.com.mx", user: "demo_user", password: "demo_password" }; ``` -------------------------------- ### Initialize StampService Without Authentication Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/errors.md This error is thrown if StampService is initialized without any authentication credentials, such as user/password or a token. Provide valid authentication details. ```javascript // Throws error StampService.Set({ url: "https://services.test.sw.com.mx" // Missing user, password, or token }); ``` ```javascript // Option 1: Use credentials const params = { url: "https://services.test.sw.com.mx", user: "demo", password: "123456789" }; // Option 2: Use token const params = { url: "https://services.test.sw.com.mx", token: "T2lYQ0t4L0R..." }; ``` -------------------------------- ### Import AccountBalance Service Source: https://github.com/lunasoft/sw-sdk-nodejs/blob/master/_autodocs/api-reference/account-balance-service.md Import the AccountBalance class from the SDK. This is required before using any of its methods. ```javascript const AccountBalance = require("sw-sdk-nodejs").AccountBalance; ```