### Basic SDK Initialization Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Initialize the Facturapi SDK with your API key. This is the most basic setup required to start making API calls. ```javascript const facturapi = require('facturapi'); const client = new facturapi.Facturapi('YOUR_SECRET_KEY'); ``` -------------------------------- ### Install FacturAPI Node.js Client Source: https://github.com/facturapi/facturapi-node/blob/main/README.md Install the FacturAPI Node.js client using npm. ```bash npm i facturapi ``` -------------------------------- ### SDK Initialization with Options Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Initialize the Facturapi SDK with additional configuration options such as API version and custom headers. This allows for more advanced setup. ```javascript const facturapi = require('facturapi'); const client = new facturapi.Facturapi('YOUR_SECRET_KEY', { apiVersion: 'v2', headers: { 'X-Custom-Header': 'value' } }); ``` -------------------------------- ### Quick Start: Create and Stamp Invoice Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md Initialize the Facturapi client, create a customer, product, and invoice, then stamp the draft. Ensure your FACTURAPI_KEY is set in the environment variables. ```typescript import Facturapi from 'facturapi'; // Initialize const facturapi = new Facturapi(process.env.FACTURAPI_KEY!); // Create customer const customer = await facturapi.customers.create({ legal_name: 'Acme Corp', tax_id: 'AAA010101AAA', email: 'info@acme.com', address: { zip: '06800', country: 'MEX' }, }); // Create product const product = await facturapi.products.create({ description: 'Consulting Service', product_key: '86101600', unit_key: 'H87', unit_name: 'Service', price: 5000, tax_included: false, }); // Create invoice const invoice = await facturapi.invoices.create({ customer: customer.id, items: [{ quantity: 1, product: product.id }], payment_form: Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA_DE_FONDOS, payment_method: Facturapi.PaymentMethod.PAGO_EN_UNA_EXHIBICION, }); // Stamp invoice const stamped = await facturapi.invoices.stampDraft(invoice.id); console.log(`Invoice ${stamped.uuid} created successfully!`); ``` -------------------------------- ### Basic SDK Initialization Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Initialize the Facturapi SDK with your API key. Ensure the API key is securely stored and accessed, for example, via environment variables. ```typescript import Facturapi from 'facturapi'; const facturapi = new Facturapi(process.env.FACTURAPI_KEY!); ``` -------------------------------- ### CommonJS Usage of Facturapi Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Example of how to import and use the Facturapi SDK in a CommonJS environment. ```javascript const Facturapi = require('facturapi').default; const facturapi = new Facturapi(process.env.FACTURAPI_KEY); ``` -------------------------------- ### list() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Gets a paginated list of customers. Supports search parameters like page number and limit. ```APIDOC ## list() ### Description Gets a paginated list of customers. ### Method GET (inferred from SDK method) ### Endpoint /customers (inferred from SDK context) ### Parameters #### Path Parameters None #### Query Parameters - **params** (Record) - Required - Search parameters (page, limit, etc.) #### Request Body None ### Request Example ```json { "page": 1, "limit": 10 } ``` ### Response #### Success Response (200) - **SearchResult** (object) - An object containing a list of customers and pagination information #### Response Example ```json { "data": [ { "id": "cus_xxxxxxxxxxxx", "legal_name": "Walter White", "tax_id": "WIWA761018", "email": "walterwhite@gmail.com", "address": { "zip": "06800", "country": "MEX" }, "created_at": "2023-10-27T10:00:00.000Z" } ], "total": 1, "page": 1, "limit": 10 } ``` ``` -------------------------------- ### Use Log IDs for Support Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/errors.md In case of an error, log the `logId` provided by Facturapi to facilitate support requests. This example shows how to access and display the `logId` from a FacturapiError. ```typescript try { await facturapi.invoices.create({...}); } catch (error) { if (error instanceof FacturapiError && error.logId) { console.log(`Error: ${error.message}`); console.log(`Contact support with Log ID: ${error.logId}`); } } ``` -------------------------------- ### Validation Error Response Example Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/errors.md A typical JSON structure for a 422 validation error from the Facturapi API. ```json { "status": 422, "code": "validation_error", "message": "Validation failed", "errors": [ { "code": "required", "message": "Field is required", "path": "customer.legal_name", "location": "body" }, { "code": "invalid_format", "message": "Invalid email format", "path": "customer.email", "location": "body" } ] } ``` -------------------------------- ### create() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new product with the provided data. ```APIDOC ## create() ### Description Creates a new product. ### Method `create(data: Record): Promise` ### Parameters #### Request Body - **data** (Record) - Required - Product data (description, price, product_key, unit_key, etc.) ### Request Example ```typescript const product = await facturapi.products.create({ description: 'Laptop', product_key: '43232113', unit_key: 'H87', unit_name: 'Piece', price: 1500, tax_included: false, }); ``` ### Response #### Success Response (200) - **Product** object ``` -------------------------------- ### SDK Initialization with Options Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Initialize the Facturapi SDK with an API key and custom configuration options. This allows specifying the API version and adding custom headers to all requests. ```typescript const facturapi = new Facturapi(process.env.FACTURAPI_KEY!, { apiVersion: 'v2', headers: { 'Custom-Header': 'value' }, }); ``` -------------------------------- ### Get Organization Details Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Retrieves the organization details associated with the authenticated API key. This is useful for fetching current organization information. ```typescript const org = await facturapi.organizations.me(); ``` -------------------------------- ### Configure Request Timeout in Node.js Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Configure request timeouts at the Node.js level using AbortController and setTimeout. This example sets a 30-second timeout. ```typescript // Node.js only const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 30000); // 30 seconds try { const customer = await facturapi.customers.retrieve('cus_123'); } finally { clearTimeout(timeout); } ``` -------------------------------- ### Initialize Facturapi Client with API Keys Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Instantiate the Facturapi client using API keys loaded from environment variables. Use the production key for live operations and the test key for sandbox environments. ```typescript // For production (live mode) const liveClient = new Facturapi(process.env.FACTURAPI_KEY!); ``` ```typescript // For testing (test mode) const testClient = new Facturapi(process.env.FACTURAPI_TEST_KEY!); ``` -------------------------------- ### Facturapi SDK Initialization Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md Demonstrates how to initialize the Facturapi SDK client using an API key for both JavaScript/TypeScript (ESM) and CommonJS environments. ```APIDOC ## Facturapi SDK Initialization ### Description Initialize the Facturapi SDK client with your API key. This client serves as the entry point for all subsequent operations. ### JavaScript/TypeScript (ESM) ```typescript import Facturapi from 'facturapi'; const facturapi = new Facturapi(process.env.FACTURAPI_KEY!); ``` ### CommonJS ```javascript const Facturapi = require('facturapi').default; const facturapi = new Facturapi(process.env.FACTURAPI_KEY); ``` ### Configuration Types - **FacturapiOptions**: SDK initialization options. - **ApiVersion**: Specifies the API version, e.g., 'v1' or 'v2'. ``` -------------------------------- ### Create and Stamp an Invoice Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md This snippet shows the complete process of creating a customer, a product, an invoice, stamping it, and downloading the PDF. Ensure you have the Facturapi SDK initialized. ```typescript // 1. Create customer const customer = await facturapi.customers.create({ legal_name: 'Customer Name', tax_id: 'WIWA761018', email: 'customer@example.com', address: { zip: '06800', country: 'MEX' }, }); // 2. Create product const product = await facturapi.products.create({ description: 'Service', product_key: '84101700', unit_key: 'H87', unit_name: 'Piece', price: 1000, tax_included: false, }); // 3. Create invoice const invoice = await facturapi.invoices.create({ customer: customer.id, items: [{ quantity: 1, product: product.id, }], payment_form: Facturapi.PaymentForm.EFECTIVO, payment_method: Facturapi.PaymentMethod.PAGO_EN_UNA_EXHIBICION, }); // 4. Stamp (finalize) invoice const stamped = await facturapi.invoices.stampDraft(invoice.id); // 5. Download const pdf = await facturapi.invoices.downloadPdf(stamped.id); ``` -------------------------------- ### Initialize FacturAPI Client Source: https://github.com/facturapi/facturapi-node/blob/main/README.md Initialize the FacturAPI client with your API key. Ensure the FACTURAPI_KEY environment variable is set. ```typescript import Facturapi from 'facturapi'; const facturapi = new Facturapi(process.env.FACTURAPI_KEY!); ``` ```javascript const Facturapi = require('facturapi').default; ``` -------------------------------- ### Create a New Product Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Use this method to add a new product to your Facturapi account. Ensure all required fields like description, price, and product_key are provided. ```typescript const product = await facturapi.products.create({ description: 'Laptop', product_key: '43232113', unit_key: 'H87', unit_name: 'Piece', price: 1500, tax_included: false, }); ``` -------------------------------- ### Handle Facturapi API Errors Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md This example demonstrates how to catch and handle specific Facturapi errors, including checking error codes, messages, and support log IDs for debugging. ```typescript try { const invoice = await facturapi.invoices.retrieve('inv_123'); } catch (error) { if (error instanceof FacturapiError) { console.error(`Error ${error.status}: ${error.code}`); if (error.errors) { error.errors.forEach(e => console.error(` ${e.path}: ${e.message}`)); } if (error.logId) { console.error(`Support Log ID: ${error.logId}`); } } } ``` -------------------------------- ### SDK Initialization with API Version v1 (Legacy) Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Initialize the Facturapi SDK for the legacy API version 1. Only use this version if you are maintaining existing integrations. ```typescript const facturapi = new Facturapi(apiKey, { apiVersion: 'v1' }); // Base URL: https://www.facturapi.io/v1 ``` -------------------------------- ### Handle Invite Errors Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/errors.md Manage errors that can occur during user invitation to a team, such as duplicate emails or invalid roles. This example logs the specific error message provided by Facturapi. ```typescript try { await facturapi.organizations.inviteUserToTeam('org_123', { email: 'user@example.com', role: 'admin', }); } catch (error) { if (error instanceof FacturapiError) { console.log('Invite failed:', error.message); } } ``` -------------------------------- ### BASE_URL Property Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Allows getting or setting the base URL for API requests made by the Facturapi client instance. This is useful for testing against a local server or a different API endpoint. ```APIDOC ## BASE_URL Property ### Description Allows getting or setting the base URL for API requests made by the Facturapi client instance. This is useful for testing against a local server or a different API endpoint. ### Usage #### Get Base URL ```typescript const currentBaseUrl = facturapi.BASE_URL; ``` #### Set Base URL ```typescript facturapi.BASE_URL = 'http://localhost:3000/v2'; ``` ``` -------------------------------- ### create() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new customer in the organization. It requires customer data such as legal name, tax ID, email, and address. ```APIDOC ## create() ### Description Creates a new customer in the organization. ### Method POST (inferred from SDK method) ### Endpoint /customers (inferred from SDK context) ### Parameters #### Path Parameters None #### Query Parameters - **params** (Record) - Optional - Query parameters #### Request Body - **data** (Record) - Required - Customer data (legal_name, tax_id, email, address, etc.) ### Request Example ```json { "legal_name": "Walter White", "tax_id": "WIWA761018", "email": "walterwhite@gmail.com", "address": { "zip": "06800", "country": "MEX" } } ``` ### Response #### Success Response (200) - **Customer** (object) - The created customer object #### Response Example ```json { "id": "cus_xxxxxxxxxxxx", "legal_name": "Walter White", "tax_id": "WIWA761018", "email": "walterwhite@gmail.com", "address": { "zip": "06800", "country": "MEX" }, "created_at": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Configure Facturapi for Browser Environment Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md The SDK works in browsers using the Fetch API. Ensure the Fetch API is available in your environment. ```typescript // Fetch API is required in browser const facturapi = new Facturapi(FACTURAPI_TEST_KEY); try { const customers = await facturapi.customers.list({ limit: 10 }); } catch (error) { console.error('API Error:', error); } ``` -------------------------------- ### Handle Invoice Cancellation Errors Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/errors.md Manage errors that occur during invoice cancellation. This example uses a switch statement to handle specific error codes like 'invoice_not_found', 'invoice_already_canceled', and 'cancellation_rejected'. ```typescript try { const canceled = await facturapi.invoices.cancel('inv_123', { motive: Facturapi.CancellationMotive.ERRORES_CON_RELACION, }); } catch (error) { if (error instanceof FacturapiError) { switch (error.code) { case 'invoice_not_found': console.log('Invoice does not exist'); break; case 'invoice_already_canceled': console.log('Invoice is already canceled'); break; case 'cancellation_rejected': console.log('SAT rejected the cancellation'); break; } } } ``` -------------------------------- ### Handling HTTP Status Codes Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Provides an example of handling errors based on their HTTP status codes. This is useful for categorizing errors like authentication failures, validation issues, or server errors. ```javascript try { // ... API call } catch (error) { switch (error.status) { case 401: console.error('Authentication failed. Check your API key.'); break; case 422: console.error('Validation error:', error.details); break; default: console.error('An error occurred:', error); } } ``` -------------------------------- ### create Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new organization with the provided data. ```APIDOC ## POST /organizations ### Description Creates a new organization. ### Method POST ### Endpoint /organizations ### Parameters #### Request Body - **data** (Record) - Yes - Organization data ### Response #### Success Response (200) - **Organization** (object) - Organization object ### Response Example ```json { "id": "org_123", "name": "Example Org" } ``` ``` -------------------------------- ### SDK Initialization with API Version v2 Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Initialize the Facturapi SDK explicitly for API version 2. This is the default and recommended version for new implementations. ```typescript const facturapi = new Facturapi(apiKey); // or explicitly: const facturapi = new Facturapi(apiKey, { apiVersion: 'v2' }); // Base URL: https://www.facturapi.io/v2 ``` -------------------------------- ### Create a Customer Source: https://github.com/facturapi/facturapi-node/blob/main/README.md Create a new customer in FacturAPI. Requires legal name, tax ID, email, and address details. ```typescript const customer = await facturapi.customers.create({ legal_name: 'Walter White', tax_id: 'WIWA761018', email: 'walterwhite@gmail.com', address: { zip: '06800', country: 'MEX', }, }); ``` -------------------------------- ### Set API Keys using Environment Variables Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Store your production and test API keys in a .env file. Never hardcode sensitive credentials directly in your code. ```bash # .env file FACTURAPI_KEY=sk_live_xxxxx # Production FACTURAPI_TEST_KEY=sk_test_xxxxx # Test/Sandbox ``` -------------------------------- ### Instantiate Facturapi Client Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Instantiate the Facturapi client with your API key. Options for API version and custom headers can be provided. ```typescript import Facturapi from 'facturapi'; const facturapi = new Facturapi(process.env.FACTURAPI_KEY!); ``` ```typescript const facturapi = new Facturapi(process.env.FACTURAPI_KEY!, { apiVersion: 'v2', headers: { 'Custom-Header': 'value' } }); ``` -------------------------------- ### create() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new receipt with the provided data. ```APIDOC ## POST /receipts ### Description Creates a new receipt. ### Method POST ### Endpoint /receipts ### Parameters #### Request Body - **data** (Record) - Yes - Receipt data ### Response #### Success Response (200) - **Receipt** (object) - The created receipt object. ``` -------------------------------- ### Package.json Build Configuration Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Defines the entry points for different module formats and type definitions in your `package.json`. Setting `sideEffects` to `false` enables tree-shaking. ```json { "main": "dist/index.cjs.js", "module": "dist/index.es.js", "types": "dist/index.d.ts", "sideEffects": false } ``` -------------------------------- ### Subscribe to All Webhook Events Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/enums.md Demonstrates how to subscribe to all available events using the wildcard '*'. This is useful for setting up a general webhook listener for all Facturapi notifications. ```typescript await facturapi.webhooks.create({ url: 'https://example.com/webhook', enabled_events: ['*'], }); ``` -------------------------------- ### Configure Facturapi for Development Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Use this configuration for development environments. It requires a test API key and sets a specific 'X-Environment' header. ```typescript const facturapi = new Facturapi(process.env.FACTURAPI_TEST_KEY!, { apiVersion: 'v2', headers: { 'X-Environment': 'development', }, }); ``` -------------------------------- ### Manage Products Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md These methods allow for the creation, listing, retrieval, updating, and deletion of product records within the system. ```typescript facturapi.products.create(data) // Create product facturapi.products.list(params) // List products facturapi.products.retrieve(id) // Get one facturapi.products.update(id, data) // Update facturapi.products.del(id) // Delete ``` -------------------------------- ### FacturapiOptions Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Configuration options for initializing the Facturapi client, allowing customization of API version and HTTP headers. ```APIDOC ## FacturapiOptions ### Description Initialization options for Facturapi client. ### Type Definition ```typescript interface FacturapiOptions { apiVersion?: ApiVersion; headers?: Record; } ``` ### Fields | Field | Type | Description | |-------|------|-------------| | apiVersion | 'v1' \| 'v2' | API version (default: 'v2') | | headers | object | Custom HTTP headers | ``` -------------------------------- ### Create a New Customer Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Use this method to add a new customer to your organization. Provide all required customer data, including legal name, tax ID, email, and address. ```typescript const customer = await facturapi.customers.create({ legal_name: 'Walter White', tax_id: 'WIWA761018', email: 'walterwhite@gmail.com', address: { zip: '06800', country: 'MEX', }, }); ``` -------------------------------- ### Facturapi Client Constructor Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Initializes a new instance of the Facturapi client. This client is used to interact with the Facturapi API. You can specify the API version and custom headers through the options object. ```APIDOC ## Facturapi Client Constructor ### Description Initializes a new instance of the Facturapi client. This client is used to interact with the Facturapi API. You can specify the API version and custom headers through the options object. ### Signature ```typescript class Facturapi { constructor(apiKey: string, options?: FacturapiOptions) } ``` ### Parameters #### Constructor Parameters - **apiKey** (string) - Required - API key (test or live) for authentication. - **options** (FacturapiOptions) - Optional - Configuration options. - **options.apiVersion** ('v1' | 'v2') - Optional - API version to use. Defaults to 'v2'. - **options.headers** (Record) - Optional - Custom HTTP headers. Defaults to {}. ### Example ```typescript import Facturapi from 'facturapi'; // Basic initialization const facturapi = new Facturapi(process.env.FACTURAPI_KEY!); // With options const facturapiWithOptions = new Facturapi(process.env.FACTURAPI_KEY!, { apiVersion: 'v2', headers: { 'Custom-Header': 'value' } }); ``` ``` -------------------------------- ### list() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Retrieves a paginated list of products, with optional search parameters. ```APIDOC ## list() ### Description Gets a paginated list of products. ### Method `list(params?: Record | null): Promise>` ### Parameters #### Query Parameters - **params** (Record) - Optional - Search parameters (page, limit, etc.) ### Request Example ```typescript const result = await facturapi.products.list({ page: 1 }); ``` ### Response #### Success Response (200) - **SearchResult** ``` -------------------------------- ### retrieve() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Fetches a single product by its unique ID. ```APIDOC ## retrieve() ### Description Gets a single product by ID. ### Method `retrieve(id: string): Promise` ### Parameters #### Path Parameters - **id** (string) - Required - Product ID ### Request Example ```typescript const product = await facturapi.products.retrieve('prod_123'); ``` ### Response #### Success Response (200) - **Product** object ### Throws Rejects if id is empty ``` -------------------------------- ### create() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new valid invoice (CFDI) with the provided invoice data and optional query parameters. ```APIDOC ## create() ### Description Creates a new valid invoice (CFDI). ### Method Signature ```typescript create( body: Record, params?: Record | null ): Promise ``` ### Parameters #### Request Body - **body** (Record) - Required - Invoice data (customer, items, payment_form, etc.) #### Query Parameters - **params** (Record) - Optional - Query parameters ### Returns - **Invoice** object ### Example ```typescript const invoice = await facturapi.invoices.create({ customer: 'cus_123', payment_form: Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA_DE_FONDOS, items: [ { quantity: 1, product: 'prod_123', }, ], }); ``` ``` -------------------------------- ### Configure Facturapi for Production Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md This configuration is for production environments and uses the production API key. ```typescript const facturapi = new Facturapi(process.env.FACTURAPI_KEY!, { apiVersion: 'v2', }); ``` -------------------------------- ### Configure Facturapi for React Native Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md The SDK is compatible with React Native, provided that fetch, FormData, and Blob are available. ```typescript import Facturapi from 'facturapi'; // Works if fetch, FormData, and Blob are available const facturapi = new Facturapi(FACTURAPI_KEY); ``` -------------------------------- ### Facturapi Client Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Documentation for the main Facturapi Client class and its properties. ```APIDOC ## Facturapi Client ### Description Main class for interacting with the Facturapi API. Provides access to various modules and configuration options. ### Properties - **apiKey** (string): Your Facturapi API key. - **options** (FacturapiOptions): Configuration options for the client. ### Methods (Details for specific methods would be listed here if available in the source) ``` -------------------------------- ### Core Classes for Resource Management Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md Lists the core classes available in the SDK for managing different resources like customers, products, invoices, and more. ```APIDOC ## Core Classes ### Description The SDK provides dedicated classes for managing various resources. Instantiate the `Facturapi` client first, then access these resources through it. | Class | Purpose | |---|---| | **Customers** | Customer resource management | | **Products** | Product catalog management | | **Invoices** | Invoice creation and management | | **Receipts** | Receipt management | | **Retentions** | Tax retention documents | | **Organizations** | Organization and team management | | **Webhooks** | Webhook endpoints and signatures | | **Catalogs** | Product/unit catalog search | | **CartaPorteCatalogs** | Transport-related catalogs | | **ComercioExteriorCatalogs** | International commerce codes | | **Tools** | Utility functions | ``` -------------------------------- ### listLiveApiKeys Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Lists all live API keys associated with an organization. ```APIDOC ## listLiveApiKeys(id: string) ### Description Lists all live API keys for a given organization. ### Method GET (assumed, based on action) ### Endpoint /organizations/{id}/live-api-keys (assumed) ### Parameters #### Path Parameters - **id** (string) - Yes - Organization ID ### Returns Array of ApiKeys ``` -------------------------------- ### Products Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Operations for managing products: create, list, retrieve, update, and delete. ```APIDOC ## Products ### Description Manage product and service catalog. ### Methods - **create(productData)**: Creates a new product. - **list(queryOptions)**: Retrieves a list of products. - **retrieve(productId)**: Fetches a specific product by ID. - **update(productId, productData)**: Updates an existing product. - **delete(productId)**: Removes a product. ``` -------------------------------- ### Using Idempotency Keys for Retries Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Demonstrates how to use idempotency keys to safely retry API requests. This prevents unintended duplicate operations when network issues occur. ```javascript const idempotencyKey = require('uuid').v4(); try { const result = await client.invoices.create({ // ... invoice data }, { idempotencyKey: idempotencyKey }); } catch (error) { // Handle error, potentially retry with the same idempotencyKey console.error('Request failed:', error); } ``` -------------------------------- ### createWebhook Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new webhook subscription to receive event notifications. Requires specifying the callback URL and the events to subscribe to. ```APIDOC ## create() ### Description Creates a new webhook subscription to receive event notifications. Requires specifying the callback URL and the events to subscribe to. ### Method (Not specified, likely a SDK method call) ### Parameters #### Request Body - **data** (Record) - Yes - Webhook data (url, enabled_events, etc.) ### Response #### Success Response - **(Webhook)** - Webhook object ### Request Example ```typescript const webhook = await facturapi.webhooks.create({ url: 'https://example.com/webhook', enabled_events: ['invoice.status_updated'], }); ``` ``` -------------------------------- ### previewPdf Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Generates a PDF preview of an invoice before it is stamped. Requires the invoice data in the request body. Returns a binary download. ```APIDOC ## previewPdf() ### Description Previews an invoice PDF before stamping. ### Method Signature ```typescript previewPdf(body: Record): Promise ``` ### Parameters #### Request Body - **body** (Record) - Required - Invoice data ### Returns Blob (browser) or NodeJS.ReadableStream (Node.js) ``` -------------------------------- ### Search Products Catalog Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Use this method to search the products catalog. It accepts an optional object for search parameters like 'q', 'page', and 'limit'. ```typescript searchProducts(params: Record | null) ``` -------------------------------- ### Manage Webhooks with Facturapi Node.js SDK Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md Create, list, retrieve, update, and delete webhooks. Includes a utility to validate webhook signatures. Use this for handling events from Facturapi. ```typescript facturapi.webhooks.create(data) // Create webhook facturapi.webhooks.list(params) // List webhooks facturapi.webhooks.retrieve(id) // Get one facturapi.webhooks.update(id, data) // Update facturapi.webhooks.del(id) // Delete facturapi.webhooks.validateSignature(data) // Verify signature ``` -------------------------------- ### previewToInvoicePdf() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Generates a PDF preview for a batch of receipts intended for invoicing. ```APIDOC ## POST /receipts/invoice/to_invoice/pdf ### Description Generates a PDF preview for receipts-to-invoice. ### Method POST ### Endpoint /receipts/invoice/to_invoice/pdf ### Parameters #### Request Body - **data.keys** (string[]) - Yes - Receipt keys - **data.customer** (Record) - No - Customer data - **data.use** (string) - No - Invoice use code ### Response #### Success Response (200) - **BinaryDownload** (object) - Blob (browser) or NodeJS.ReadableStream (Node.js) of the PDF preview. ``` -------------------------------- ### Configure Facturapi for Testing Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Use this configuration for testing, including overriding the base URL if a mock server is in use. ```typescript const facturapi = new Facturapi(process.env.FACTURAPI_TEST_KEY!, { apiVersion: 'v2', }); // Override base URL if using mock server facturapi.BASE_URL = 'http://localhost:3000/v2'; ``` -------------------------------- ### OrganizationInviteCreateInput Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Input parameters required to create a new organization invitation. ```APIDOC ## OrganizationInviteCreateInput ### Description Input parameters required to create a new organization invitation. ### Type Definition ```typescript interface OrganizationInviteCreateInput { email: string; role?: string; } ``` ``` -------------------------------- ### update() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Updates an existing product with new data. ```APIDOC ## update() ### Description Updates a product. ### Method `update( id: string, data: Record ): Promise` ### Parameters #### Path Parameters - **id** (string) - Required - Product ID #### Request Body - **data** (Record) - Required - Fields to update ### Request Example ```typescript const updated = await facturapi.products.update('prod_123', { price: 2000, }); ``` ### Response #### Success Response (200) - **Updated Product** object ``` -------------------------------- ### Handling API Errors with Try-Catch Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Demonstrates how to use a try-catch block to handle potential errors when making API requests. This is a fundamental pattern for robust error management. ```javascript try { const invoice = await client.invoices.create({ // ... invoice data }); } catch (error) { console.error('An error occurred:', error); } ``` -------------------------------- ### listTeamRoleOperations Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Lists all available operations that can be assigned to roles. This helps in understanding the granular permissions that can be configured. ```APIDOC ## listTeamRoleOperations() ### Description Lists available operations for roles. ### Method ```typescript listTeamRoleOperations(organizationId: string): Promise ``` ### Parameters #### Path Parameters - **organizationId** (string) - Yes - Organization ID ### Returns Array of operation codes ``` -------------------------------- ### Create Webhook Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates a new webhook with the specified URL and events. Ensure the URL is accessible and the enabled_events array contains valid event types. ```typescript const webhook = await facturapi.webhooks.create({ url: 'https://example.com/webhook', enabled_events: ['invoice.status_updated'], }); ``` -------------------------------- ### listTeamAccess Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Lists all users who have access to an organization. ```APIDOC ## listTeamAccess(organizationId: string) ### Description Lists users with access to a specific organization. ### Method GET (assumed, based on action) ### Endpoint /organizations/{organizationId}/team-access (assumed) ### Parameters #### Path Parameters - **organizationId** (string) - Yes - Organization ID ### Returns Array of OrganizationUserAccess ``` -------------------------------- ### Product Interface Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Defines the structure for a product entity. Includes fields for identification, description, pricing, and tax-related information. ```typescript interface Product { id: string; organization: string; livemode: boolean; product_key: string; description: string; price: number; created_at: Date; tax_included: boolean; taxability: string; taxes: Tax[]; local_taxes: LocalTax[]; unit_key: string; unit_name: string; } ``` -------------------------------- ### Importing Facturapi SDK Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md Use these import statements depending on your project's module system. The SDK supports both ES Modules and CommonJS. ```typescript // ES Modules import Facturapi from 'facturapi'; ``` ```javascript // CommonJS const Facturapi = require('facturapi').default; ``` -------------------------------- ### Retrieve a Product by ID Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Fetches a single product's details using its unique ID. An empty ID will cause the promise to reject. ```typescript const product = await facturapi.products.retrieve('prod_123'); ``` -------------------------------- ### Manage Customers Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/INDEX.md Use these methods to create, list, retrieve, update, and delete customer records. Specific actions include validating tax information and sending edit links via email. ```typescript facturapi.customers.create(data) // Create customer facturapi.customers.list(params) // List customers facturapi.customers.retrieve(id) // Get one facturapi.customers.update(id, data) // Update facturapi.customers.del(id) // Delete facturapi.customers.validateTaxInfo(id) facturapi.customers.sendEditLinkByEmail(id, options) ``` -------------------------------- ### List Live API Keys Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Lists all live API keys associated with an organization. Requires the organization ID. ```typescript listLiveApiKeys(id: string): Promise ``` -------------------------------- ### Facturapi Instance Properties Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Exposes instance properties of the Facturapi client, providing managers for different API resources and utility tools. These include managers for customers, products, invoices, organizations, receipts, retentions, webhooks, and utility tools for catalogs. ```APIDOC ## Facturapi Instance Properties ### Description Exposes instance properties of the Facturapi client, providing managers for different API resources and utility tools. These include managers for customers, products, invoices, organizations, receipts, retentions, webhooks, and utility tools for catalogs. ### Properties - **apiVersion** ('v1' | 'v2'): The API version currently in use by the client instance. - **customers**: An instance of the `Customers` manager for customer-related operations. - **products**: An instance of the `Products` manager for product-related operations. - **invoices**: An instance of the `Invoices` manager for invoice-related operations. - **organizations**: An instance of the `Organizations` manager for organization-related operations. - **catalogs**: An instance of the `Catalogs` manager for searching catalog data. - **cartaPorteCatalogs**: An instance of the `CartaPorteCatalogs` manager for Carta Porte catalog tools. - **comercioExteriorCatalogs**: An instance of the `ComercioExteriorCatalogs` manager for Comercio Exterior catalog tools. - **receipts**: An instance of the `Receipts` manager for receipt-related operations. - **retentions**: An instance of the `Retentions` manager for retention-related operations. - **tools**: An instance of the `Tools` manager for utility functions. - **webhooks**: An instance of the `Webhooks` manager for webhook management. ``` -------------------------------- ### PreviewReceiptsToInvoicePdfInput Interface Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Defines the input for previewing a PDF of an invoice generated from receipts. Requires receipt keys and optionally accepts customer data and an invoice use code. ```typescript interface PreviewReceiptsToInvoicePdfInput { keys: string[]; customer?: Record | null; use?: string; } ``` -------------------------------- ### List Products with Pagination Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Retrieves a paginated list of products. You can specify search parameters like 'page' to control the results. ```typescript const result = await facturapi.products.list({ page: 1 }); ``` -------------------------------- ### downloadPdf() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Downloads the receipt in PDF format. ```APIDOC ## GET /receipts/{id}/pdf ### Description Downloads receipt in PDF format. ### Method GET ### Endpoint /receipts/{id}/pdf ### Parameters #### Path Parameters - **id** (string) - Yes - Receipt ID ### Response #### Success Response (200) - **BinaryDownload** (object) - Blob (browser) or NodeJS.ReadableStream (Node.js) of the receipt PDF. ``` -------------------------------- ### Create an Invoice Source: https://github.com/facturapi/facturapi-node/blob/main/README.md Create a new invoice in FacturAPI. Requires customer ID, payment form, and item details. Use constants like Facturapi.PaymentForm for payment forms. ```typescript const invoice = await facturapi.invoices.create({ customer: 'YOUR_CUSTOMER_ID', payment_form: Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA_DE_FONDOS, items: [ { quantity: 1, product: 'YOUR_PRODUCT_ID', }, ], }); ``` -------------------------------- ### Debugging with Log IDs Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/errors.md Explains how to use the `logId` included in every error to help Facturapi support trace requests and resolve issues. ```APIDOC ## Debugging with Log IDs ### Description Every error includes a `logId` that helps Facturapi support trace requests. ### Example for Support Request ```typescript try { await facturapi.invoices.create({...}); } catch (error) { if (error instanceof FacturapiError && error.logId) { console.log(`Error: ${error.message}`); console.log(`Contact support with Log ID: ${error.logId}`); } } ``` ``` -------------------------------- ### Building a Tax System Select Element Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/enums.md Illustrates how to create an HTML select element for tax systems using the Facturapi.TaxSystem enum. It maps enum entries to options for a dropdown. ```typescript import Facturapi from 'facturapi'; function TaxSystemSelect() { const options = Object.entries(Facturapi.TaxSystem).map( ([name, code]) => ({ name, code, }) ); return ( ); } ``` -------------------------------- ### OrganizationTeamRoleCreateInput Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Input parameters for creating a new custom team role. ```APIDOC ## OrganizationTeamRoleCreateInput ### Description Input parameters for creating a new custom team role. ### Type Definition ```typescript interface OrganizationTeamRoleCreateInput { name: string; template_code?: string | null; add?: string[]; remove?: string[]; } ``` ``` -------------------------------- ### toInvoice() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Creates an invoice by consolidating multiple receipts identified by their keys. ```APIDOC ## POST /receipts/invoice/to_invoice ### Description Creates an invoice from multiple receipts by key. ### Method POST ### Endpoint /receipts/invoice/to_invoice ### Parameters #### Request Body - **data.keys** (string[]) - Yes - Receipt keys to invoice - **data.customer** (Record) - No - Customer data - **data.use** (string) - No - Invoice use code - **data.dry_run** (boolean) - No - Preview without creating - **data.payment_form** (string) - No - Payment form code ### Response #### Success Response (200) - **Invoice** (object) - The created invoice object or dry-run summary. ### Request Example ```json { "keys": ["key1", "key2"], "customer": { "tax_id": "WIWA761018" } } ``` ``` -------------------------------- ### ApiKeys Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Provides information about API keys, including their ID, the first 12 characters, and creation timestamp. ```APIDOC ## ApiKeys ### Description Provides information about API keys, including their ID, the first 12 characters, and creation timestamp. ### Type Definition ```typescript interface ApiKeys { id: string; first_12: string; created_at: string; } ``` ``` -------------------------------- ### listTeamRoleTemplates Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Lists available role templates within an organization. Templates serve as pre-defined sets of permissions that can be used when creating new roles. ```APIDOC ## listTeamRoleTemplates() ### Description Lists role templates. ### Method ```typescript listTeamRoleTemplates(organizationId: string): Promise ``` ### Parameters #### Path Parameters - **organizationId** (string) - Yes - Organization ID ### Returns Array of OrganizationTeamRoleTemplate ``` -------------------------------- ### downloadZip() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Downloads the invoice as a ZIP file containing both PDF and XML formats. ```APIDOC ## downloadZip() ### Description Downloads invoice as ZIP (PDF + XML). ### Method Signature ```typescript downloadZip(id: string): Promise ``` ### Parameters #### Path Parameters - **id** (string) - Required - Invoice ID ### Returns - **Blob** (browser) or **NodeJS.ReadableStream** (Node.js) ``` -------------------------------- ### retrieve() Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Retrieves a single customer by their unique ID. Rejects if the ID is empty. ```APIDOC ## retrieve() ### Description Gets a single customer by ID. ### Method GET (inferred from SDK method) ### Endpoint /customers/{id} (inferred from SDK context and parameter) ### Parameters #### Path Parameters - **id** (string) - Required - Customer ID #### Query Parameters None #### Request Body None ### Request Example ```json { "id": "cus_123" } ``` ### Response #### Success Response (200) - **Customer** (object) - The requested customer object #### Response Example ```json { "id": "cus_123", "legal_name": "Walter White", "tax_id": "WIWA761018", "email": "walterwhite@gmail.com", "address": { "zip": "06800", "country": "MEX" }, "created_at": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Implement Client-Side Caching Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/configuration.md The SDK does not provide client-side caching. Implement your own caching strategy using structures like a Map to store and retrieve data efficiently. ```typescript const customerCache = new Map(); async function getCustomer(id: string): Promise { if (customerCache.has(id)) { return customerCache.get(id)!; } const customer = await facturapi.customers.retrieve(id); customerCache.set(id, customer); return customer; } ``` -------------------------------- ### listWebhooks Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Retrieves a paginated list of all configured webhooks. Supports filtering and sorting via search parameters. ```APIDOC ## list() ### Description Retrieves a paginated list of all configured webhooks. Supports filtering and sorting via search parameters. ### Method (Not specified, likely a SDK method call) ### Parameters #### Query Parameters - **params** (Record) - Yes - Search parameters ### Response #### Success Response - **(SearchResult)** - SearchResult object ``` -------------------------------- ### Tools Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/README.md Utility functions for common tasks like Tax ID validation. ```APIDOC ## Tools ### Description Utility functions for common tasks. ### Methods - **validateTaxId(taxId)**: Validates a Tax ID. ``` -------------------------------- ### OrganizationInviteResponseInput Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/types.md Input for responding to an organization invitation, specifying whether to accept or decline. ```APIDOC ## OrganizationInviteResponseInput ### Description Input for responding to an organization invitation, specifying whether to accept or decline. ### Type Definition ```typescript interface OrganizationInviteResponseInput { accept: boolean; } ``` ``` -------------------------------- ### Create Invoice Source: https://github.com/facturapi/facturapi-node/blob/main/_autodocs/api-reference.md Use this method to create a new valid invoice. Ensure all required fields like customer, payment form, and items are provided. ```typescript const invoice = await facturapi.invoices.create({ customer: 'cus_123', payment_form: Facturapi.PaymentForm.TRANSFERENCIA_ELECTRONICA_DE_FONDOS, items: [ { quantity: 1, product: 'prod_123', }, ], }); ```