> ## Documentation Index
> Fetch the complete documentation index at: https://docs-mx.taxo.ws/llms.txt
> Use this file to discover all available pages before exploring further.

# Common Errors & Troubleshooting

> Resolve common issues and errors when integrating with Taxo API

## Authentication Errors

<AccordionGroup>
  <Accordion title="Invalid API Key (401 Unauthorized)" icon="key">
    **Error Message:** `401 Unauthorized - Invalid API key`

    **Causes:**

    * API key is incorrect or expired
    * API key not included in Authorization header
    * Wrong header format

    **Solutions:**

    ```bash theme={null}
    # Correct format
    Authorization: Bearer YOUR_API_KEY

    # Test your API key
    curl -X GET "https://api.taxo.co/v1/health" \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    **Prevention:**

    * Store API keys securely in environment variables
    * Implement API key rotation procedures
    * Monitor for expired keys
  </Accordion>

  <Accordion title="Invalid SAT Credentials (400 Bad Request)" icon="shield-exclamation">
    **Error Message:** `400 Bad Request - Invalid CIEC credentials`

    **Causes:**

    * Incorrect CIEC username or password
    * Expired CIEC password
    * Account locked due to failed attempts
    * SAT system maintenance

    **Solutions:**

    1. Verify credentials by logging into SAT portal manually
    2. Reset CIEC password if expired
    3. Wait 30 minutes if account is locked
    4. Check SAT system status

    **Example Response:**

    ```json theme={null}
    {
      "error": {
        "code": "INVALID_CREDENTIALS",
        "message": "The provided CIEC password is incorrect",
        "details": {
          "field": "credentials.password"
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="Rate Limit Exceeded (429 Too Many Requests)" icon="clock">
    **Error Message:** `429 Too Many Requests - Rate limit exceeded`

    **Rate Limits:**

    * Extraction Creation: 10 requests per hour
    * Status Checks: 100 requests per minute
    * Document Downloads: 1000 requests per hour

    **Solutions:**

    ```javascript theme={null}
    // Implement exponential backoff
    async function retryWithBackoff(operation, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          return await operation();
        } catch (error) {
          if (error.status === 429) {
            const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
            await new Promise(resolve => setTimeout(resolve, delay));
          } else {
            throw error;
          }
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Extraction Errors

<AccordionGroup>
  <Accordion title="Extraction Failed (FAILED Status)" icon="x-circle">
    **Common Causes:**

    * Invalid date range (too large or in future)
    * RFC not found in SAT system
    * SAT system temporary unavailability
    * Network connectivity issues

    **Diagnostic Steps:**

    1. Check extraction status details:

    ```bash theme={null}
    curl -X GET "https://api.taxo.co/v1/extractions/{jobId}" \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    2. Verify RFC exists in SAT:

    ```bash theme={null}
    # Test with smaller date range
    {
      "period": {
        "from": "2024-01-01",
        "to": "2024-01-07"  # 1 week instead of full month
      }
    }
    ```

    **Solutions:**

    * Reduce date range to maximum 3 months
    * Verify RFC is active and registered
    * Retry during SAT business hours (6 AM - 10 PM Mexico time)
  </Accordion>

  <Accordion title="No Documents Found (0 Documents)" icon="folder-open">
    **Possible Causes:**

    * No documents exist for the specified period
    * Incorrect direction filter (INBOUND vs OUTBOUND)
    * Wrong information type
    * Overly restrictive filters

    **Diagnostic Questions:**

    * Are you sure documents exist for this period?
    * Is the direction filter correct?
    * Are there any emitter filters applied?

    **Example - Remove Filters:**

    ```json theme={null}
    {
      "options": {
        "informationType": "INVOICE",
        // Remove direction to get both INBOUND and OUTBOUND
        "period": {
          "from": "2024-01-01",
          "to": "2024-01-31"
        }
      }
      // Remove filters object entirely
    }
    ```
  </Accordion>

  <Accordion title="Extraction Timeout" icon="clock-exclamation">
    **Error:** Extraction remains in PROCESSING status for over 1 hour

    **Causes:**

    * Large date range with many documents
    * SAT system overload
    * Network connectivity issues

    **Solutions:**

    1. **Split Large Requests:**

    ```javascript theme={null}
    // Split by month
    const months = [
      { from: '2024-01-01', to: '2024-01-31' },
      { from: '2024-02-01', to: '2024-02-29' },
      { from: '2024-03-01', to: '2024-03-31' }
    ];

    for (const period of months) {
      const extraction = await createExtraction({ ...options, period });
      await waitForCompletion(extraction.publicId);
    }
    ```

    2. **Monitor Progress:**

    ```javascript theme={null}
    async function monitorExtraction(jobId, timeoutMs = 3600000) { // 1 hour
      const startTime = Date.now();
      
      while (Date.now() - startTime < timeoutMs) {
        const status = await getExtractionStatus(jobId);
        
        if (status.status === 'COMPLETED' || status.status === 'FAILED') {
          return status;
        }
        
        console.log(`Progress: ${status.completedCount}/${status.discoveryCount}`);
        await new Promise(resolve => setTimeout(resolve, 30000)); // 30s
      }
      
      throw new Error('Extraction timeout');
    }
    ```
  </Accordion>
</AccordionGroup>

## Document Download Errors

<AccordionGroup>
  <Accordion title="Document Not Found (404)" icon="file-slash">
    **Error Message:** `404 Not Found - Document not found`

    **Causes:**

    * Document ID is incorrect
    * Document has expired (retention policy)
    * Document was not successfully extracted

    **Solutions:**

    1. Verify document exists in extraction:

    ```bash theme={null}
    curl -X GET "https://api.taxo.co/v1/extractions/{jobId}" \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    2. Check document list in response:

    ```json theme={null}
    {
      "documents": [
        {
          "id": "doc_123456",
          "type": "INVOICE",
          "status": "AVAILABLE"
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="File Type Not Available" icon="file-exclamation">
    **Error:** Requested file type (XML/PDF) not available

    **Availability by Document Type:**

    * **INVOICE**: XML ✅, PDF ✅
    * **TAX\_STATUS**: XML ❌, PDF ✅
    * **TAX\_RETENTION**: XML ✅, PDF ✅

    **Solution:**

    ```bash theme={null}
    # Check available types first
    curl -X GET "https://api.taxo.co/v1/extractions/{jobId}/documents/{docId}" \
      -H "Authorization: Bearer YOUR_API_KEY"

    # Response shows available types
    {
      "availableFormats": ["XML", "PDF"]
    }
    ```
  </Accordion>

  <Accordion title="Download Timeout" icon="download">
    **Causes:**

    * Large PDF files
    * Network connectivity issues
    * Server overload

    **Solutions:**

    ```javascript theme={null}
    // Increase timeout for downloads
    const response = await axios.get(downloadUrl, {
      timeout: 60000, // 60 seconds
      responseType: 'arraybuffer'
    });

    // Implement retry for failed downloads
    async function downloadWithRetry(url, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          return await axios.get(url, { timeout: 60000 });
        } catch (error) {
          if (i === maxRetries - 1) throw error;
          await new Promise(resolve => setTimeout(resolve, 5000));
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Webhook Issues

<AccordionGroup>
  <Accordion title="Webhook Not Receiving Events" icon="webhook">
    **Diagnostic Checklist:**

    <Checklist>
      <Check>Webhook URL is publicly accessible</Check>
      <Check>Webhook endpoint returns 2xx status code</Check>
      <Check>SSL certificate is valid (for HTTPS URLs)</Check>
      <Check>Webhook responds within 30 seconds</Check>
      <Check>Firewall allows incoming connections</Check>
    </Checklist>

    **Test Your Webhook:**

    ```bash theme={null}
    # Test webhook endpoint manually
    curl -X POST "https://your-domain.com/webhook" \
      -H "Content-Type: application/json" \
      -d '{"test": "webhook"}'
    ```

    **Common Issues:**

    * Using HTTP instead of HTTPS
    * Webhook behind authentication/firewall
    * Slow response times (>30 seconds)
    * Invalid SSL certificates
  </Accordion>

  <Accordion title="Webhook Authentication Failures" icon="shield-x">
    **Verify Webhook Signatures:**

    ```javascript theme={null}
    const crypto = require('crypto');

    function verifyWebhookSignature(payload, signature, secret) {
      const expectedSignature = crypto
        .createHmac('sha256', secret)
        .update(payload)
        .digest('hex');
      
      return crypto.timingSafeEqual(
        Buffer.from(signature, 'hex'),
        Buffer.from(expectedSignature, 'hex')
      );
    }

    // Express.js middleware
    app.post('/webhook', (req, res) => {
      const signature = req.headers['x-taxo-signature'];
      const payload = JSON.stringify(req.body);
      
      if (!verifyWebhookSignature(payload, signature, WEBHOOK_SECRET)) {
        return res.status(401).send('Invalid signature');
      }
      
      // Process webhook
      res.status(200).send('OK');
    });
    ```
  </Accordion>

  <Accordion title="Duplicate Webhook Events" icon="copy">
    **Implement Idempotency:**

    ```javascript theme={null}
    const processedEvents = new Set();

    app.post('/webhook', (req, res) => {
      const eventId = req.body.event.id;
      
      // Check if already processed
      if (processedEvents.has(eventId)) {
        return res.status(200).send('Already processed');
      }
      
      try {
        // Process event
        processWebhookEvent(req.body);
        processedEvents.add(eventId);
        res.status(200).send('OK');
      } catch (error) {
        // Don't add to processed set on failure
        res.status(500).send('Processing failed');
      }
    });
    ```
  </Accordion>
</AccordionGroup>

## Performance Issues

<AccordionGroup>
  <Accordion title="Slow API Responses" icon="gauge">
    **Diagnostic Steps:**

    1. Check API response times:

    ```javascript theme={null}
    const startTime = Date.now();
    const response = await makeAPICall();
    const responseTime = Date.now() - startTime;
    console.log(`API response time: ${responseTime}ms`);
    ```

    2. Identify bottlenecks:

    * Network latency
    * Large response payloads
    * Server processing time

    **Optimization Strategies:**

    * Use pagination for large result sets
    * Implement response caching
    * Minimize payload size
    * Use connection pooling
  </Accordion>

  <Accordion title="Memory Issues with Large Files" icon="memory">
    **Problem:** Out of memory when downloading large PDF files

    **Solution - Stream Downloads:**

    ```javascript theme={null}
    const fs = require('fs');
    const axios = require('axios');

    async function downloadLargeFile(url, filename) {
      const response = await axios({
        method: 'GET',
        url: url,
        responseType: 'stream'
      });
      
      const writer = fs.createWriteStream(filename);
      response.data.pipe(writer);
      
      return new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject);
      });
    }
    ```
  </Accordion>
</AccordionGroup>

## Data Issues

<AccordionGroup>
  <Accordion title="Incomplete Document Data" icon="file-minus">
    **Symptoms:**

    * Missing XML elements
    * Corrupted PDF files
    * Truncated content

    **Solutions:**

    1. **Re-download the document:**

    ```bash theme={null}
    curl -X GET "https://api.taxo.co/v1/extractions/{jobId}/documents/{docId}/download?type=XML" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      --output document.xml
    ```

    2. **Validate XML structure:**

    ```javascript theme={null}
    const { DOMParser } = require('xmldom');

    function validateXML(xmlString) {
      try {
        const parser = new DOMParser();
        const doc = parser.parseFromString(xmlString, 'text/xml');
        
        // Check for parsing errors
        const errors = doc.getElementsByTagName('parsererror');
        return errors.length === 0;
      } catch (error) {
        return false;
      }
    }
    ```
  </Accordion>

  <Accordion title="Character Encoding Issues" icon="language">
    **Problem:** Special characters not displaying correctly

    **Solutions:**

    ```javascript theme={null}
    // Ensure UTF-8 encoding
    const response = await axios.get(url, {
      responseType: 'arraybuffer'
    });

    const decoder = new TextDecoder('utf-8');
    const xmlContent = decoder.decode(response.data);

    // For Node.js
    const content = Buffer.from(response.data).toString('utf-8');
    ```
  </Accordion>
</AccordionGroup>

## Quick Diagnosis Tool

Use this checklist to quickly diagnose common issues:

<Checklist>
  <Check>API key is valid and not expired</Check>
  <Check>Using correct base URL (production vs staging)</Check>
  <Check>Request headers include proper Authorization</Check>
  <Check>RFC format is correct (12-13 characters)</Check>
  <Check>Date range is valid and not in the future</Check>
  <Check>CIEC credentials are current and working</Check>
  <Check>Network connectivity is stable</Check>
  <Check>Request payload follows API schema</Check>
  <Check>Webhook endpoint is accessible (if using webhooks)</Check>
  <Check>Rate limits are not exceeded</Check>
</Checklist>

## Getting Help

When contacting support, please include:

<AccordionGroup>
  <Accordion title="API Request Details" icon="code">
    * API endpoint used
    * Request method (GET, POST, etc.)
    * Request headers (excluding sensitive data)
    * Request payload (excluding credentials)
    * Response status code
    * Response body
  </Accordion>

  <Accordion title="Error Information" icon="bug">
    * Complete error message
    * Error code (if available)
    * Timestamp when error occurred
    * Steps to reproduce the issue
    * Expected vs actual behavior
  </Accordion>

  <Accordion title="Environment Details" icon="server">
    * Programming language and version
    * SDK/library version (if using)
    * Operating system
    * Network configuration
    * Are you behind a proxy/firewall?
  </Accordion>
</AccordionGroup>

## Support Channels

<CardGroup cols={2}>
  <Card title="Email Support" icon="envelope">
    **[support@taxo.co](mailto:support@taxo.co)**

    Response time: 24-48 hours
    Priority support available for enterprise customers
  </Card>

  <Card title="Developer Forum" icon="comments">
    **[Community Forum](https://community.taxo.co)**

    Get help from other developers
    Share integration examples
  </Card>

  <Card title="Status Page" icon="heart-pulse">
    **[status.taxo.co](https://status.taxo.co)**

    Check API status and uptime
    Subscribe to incident notifications
  </Card>

  <Card title="Documentation" icon="book">
    **Latest API docs and guides**

    Always up-to-date
    Interactive examples
  </Card>
</CardGroup>
