# Baixar CTEs em Lote: XML + DACTE em ZIP (`brasildados/baixar-ctes-lote-api`) Actor

Consulta chaves CT-e (modelo 57) em paralelo e gera .zip com XMLs e DACTEs. Retorna URL de download, contagens e status por chave. | Query CT-e access keys in parallel and get a .zip with XMLs and DACTEs. Returns download URL, counts and per-key status.

- **URL**: https://apify.com/brasildados/baixar-ctes-lote-api.md
- **Developed by:** [BrasilDados.org](https://apify.com/brasildados) (community)
- **Categories:** AI, Travel, E-commerce
- **Stats:** 1 total users, 1 monthly users, 0.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $300.00 / 1,000 por ct-e | per results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## 📦 Baixar CT-e em Lote: XML e DACTE em ZIP

Consulte uma ou mais chaves de acesso CT-e (modelo 57), **sem necessidade de certificado digital**, e receba um único arquivo `.zip` com os XMLs e os DACTEs (PDF) de todos os conhecimentos de transporte. Ideal para transportadoras, ERPs e rotinas de arquivo fiscal que precisam de vários documentos de uma vez sem fazer uma requisição por CT-e.

> 🎯 **Diferencial:** uma única chamada para até 50 chaves; o actor consulta em paralelo, monta o `.zip` com XMLs + DACTEs e devolve a URL pronta para download - sem precisar gerenciar cada CT-e individualmente.

---

### O que retorna

| | Campo | Descrição |
|---|---|---|
| 📦 | `zipUrl` | Link público para download do `.zip` (válido pela duração do run) |
| ✅ | `totalEncontradas` | Conhecimentos localizados e incluídos no ZIP |
| ❌ | `totalNaoEncontradas` | Chaves válidas sem CT-e no banco |
| ⚠️ | `totalInvalidas` | Chaves com dígito verificador incorreto |
| 🗂️ | `resultados[]` | Status por chave: `encontrado`, `temXml`, `temDacte`, `erro` |

**Estrutura interna do ZIP:**

````

cte-lote.zip
├── xmls/
│   └── 35121268...xml    ← XML completo da CT-e
├── dactes/
│   └── 35121268...pdf    ← DACTE em PDF
└── manifest.json         ← array com todos os resultados

````

---

### Por que usar

- 🔄 **Lote sem código extra** - envie até 50 chaves numa única chamada; sem loop de requisições
- ⚡ **8 consultas em paralelo** - todos os conhecimentos são buscados ao mesmo tempo
- 📁 **ZIP organizado** - XMLs em `xmls/`, DACTEs em `dactes/`, manifesto incluso
- 💰 **Cobrança justa** - paga somente por CT-e encontrada; inválidas e não encontradas não cobram
- 🔗 **Integração via API ou Standby** - lote assíncrono ou endpoint HTTP síncrono

---

### Como usar

**1. Cole as chaves de acesso**

No campo "Chaves de Acesso CT-e", informe uma ou mais chaves de 44 dígitos (pontuação é ignorada):

```json
{
  "chaves": [
    "35121268252816000146570010000016161002008470",
    "35121268252816000146570010000016171002008477"
  ]
}
````

**2. Execute o actor**

Clique em "Save & Start". O actor consulta cada CT-e em paralelo e gera o arquivo `.zip`.

**3. Baixe o ZIP**

Na aba **Output**, clique em **Arquivo ZIP (XMLs e DACTEs)** para baixar. Ou use a `zipUrl` retornada para integrar no seu sistema.

***

### Precificação

Cobrado por CT-e **encontrada** - `$0.10` por conhecimento localizado (evento `consulta-cte-lote`).

- Chaves inválidas (dígito verificador errado): **sem cobrança**
- CTs não encontradas no banco: **sem cobrança**
- 50 CTs encontradas: `$0.10 × 50 = $5.00`

***

### Exemplo de saída

```json
{
  "zipUrl": "https://api.apify.com/v2/key-value-stores/abc.../records/cte-lote.zip?signature=...",
  "totalChaves": 2,
  "totalEncontradas": 1,
  "totalNaoEncontradas": 1,
  "totalInvalidas": 0,
  "erros": [
    { "chave": "35121268252816000146570010000016171002008477", "erro": "CT-e não encontrado." }
  ],
  "geradoEm": "2026-06-09T10:20:54.324Z",
  "resultados": [
    {
      "chave": "35121268252816000146570010000016161002008470",
      "encontrado": true,
      "consultadoEm": "2026-06-09T10:20:52.955Z",
      "referenciaConsulta": "bd-af03c0f94e82",
      "temXml": true,
      "temDacte": true,
      "erro": null
    },
    {
      "chave": "35121268252816000146570010000016171002008477",
      "encontrado": false,
      "consultadoEm": "2026-06-09T10:20:53.100Z",
      "referenciaConsulta": "bd-c1d2e3f4a5b6",
      "temXml": false,
      "temDacte": false,
      "erro": "CT-e não encontrado."
    }
  ]
}
```

***

### Perguntas frequentes

**Quais CTs são suportadas?**
CT-e modelo 57 (conhecimento de transporte eletrônico). Não inclui NF-e (mercadoria) nem NFS-e (serviços). Para NF-e, use o actor [Baixar NF-e em Lote](https://apify.com/brasildados/baixar-nfes-lote-api?fpr=t5lwzq).

**Qual o limite de chaves por execução?**
50 chaves por run. Para volumes maiores, divida em lotes e execute sequencialmente.

**E se o DACTE não estiver disponível?**
Alguns CTs têm XML mas não têm DACTE disponível no banco. Nesse caso `temXml: true` e `temDacte: false` - o ZIP terá o XML mas não o PDF para aquela chave.

**O link do ZIP expira?**
Sim. O link `zipUrl` fica ativo pelo tempo de retenção do run (padrão Apify: 7 dias em planos pagos). Para arquivo permanente, baixe e guarde o ZIP no seu sistema.

**Posso chamar em tempo real (Standby)?**
Sim. O endpoint `POST /export` responde de forma síncrona. Veja os exemplos curl abaixo.

***

#### 🔌 Integração via API

**Execução em lote:**

```bash
curl -X POST "https://api.apify.com/v2/acts/brasildados~baixar-ctes-lote-api/run-sync-get-dataset-items?token=SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"chaves":["35121268252816000146570010000016161002008470","35121268252816000146570010000016171002008477"]}'
```

**Standby (`POST /export`):**

```bash
curl -X POST "https://brasildados--baixar-ctes-lote-api.apify.actor/export" \
  -H "Authorization: Bearer SEU_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  --compressed \
  -d '{"chaves":["35121268252816000146570010000016161002008470","35121268252816000146570010000016171002008477"]}'
```

***

### Actors relacionados

| Actor | Descrição |
|---|---|
| [Baixar NF-e em Lote](https://apify.com/brasildados/baixar-nfes-lote-api?fpr=t5lwzq) | Consulta e download de XML e DANFE de NF-e (modelo 55) em lote |
| [Consulta CT-e por Chave](https://apify.com/brasildados/api-consulta-cte-por-chave?fpr=t5lwzq) | Consulta individual com dados estruturados (transportador, volumes, valores) |
| [CNPJ Enrichment](https://apify.com/brasildados/brazil-enrich-data-lead-by-cnpj?fpr=t5lwzq) | Dados cadastrais completos por CNPJ (Simples, IE, Suframa, portais) |

***

### Legal

Este actor acessa informações de CT-e por meio de chave de acesso (dado público por design da SEFAZ para o portador da chave). O usuário é responsável por garantir que possui autorização para acessar os conhecimentos consultados.

***

### 🇬🇧 English

Query CT-e access keys (Brazilian freight documents, model 57) in parallel and receive a single `.zip` file with all XMLs and DACTEs (PDFs) — no need to fetch each CT-e individually.

**How to use:**

```json
{
  "chaves": ["35121268252816000146570010000016161002008470","35121268252816000146570010000016171002008477"]
}
```

**Batch run:**

```bash
curl -X POST "https://api.apify.com/v2/acts/brasildados~baixar-ctes-lote-api/run-sync-get-dataset-items?token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"chaves":["35121268252816000146570010000016161002008470","35121268252816000146570010000016171002008477"]}'
```

**Standby (`POST /export`):**

```bash
curl -X POST "https://brasildados--baixar-ctes-lote-api.apify.actor/export" \
  -H "Authorization: Bearer YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  --compressed \
  -d '{"chaves":["35121268252816000146570010000016161002008470","35121268252816000146570010000016171002008477"]}'
```

**Pricing:** $0.10 per found CT-e (event `consulta-cte-lote`). Invalid keys and not-found documents are not charged.

**Related:** [Individual CT-e lookup](https://apify.com/brasildados/api-consulta-cte-por-chave?fpr=t5lwzq) (structured data: carrier, volumes, values).

***

*Dúvidas ou problemas? <contato@brasildados.org> | [brasildados.org](https://brasildados.org)*

# Actor input Schema

## `chaves` (type: `array`):

Chaves de acesso CT-e com 44 dígitos (modelo 57). Pontuação e espaços são ignorados automaticamente. Máximo 50 chaves por execução - envie em lotes maiores via chamadas sequenciais. / CT-e access keys (44 digits, model 57). Punctuation and spaces are stripped automatically. Maximum 50 keys per run.

## Actor input object example

```json
{
  "chaves": [
    "35121268252816000146570010000016161002008470",
    "35121268252816000146570010000016171002008477"
  ]
}
```

# Actor output Schema

## `resultados` (type: `string`):

Itens consultados (um registro por item).

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "chaves": [
        "35121268252816000146570010000016161002008470",
        "35121268252816000146570010000016171002008477"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("brasildados/baixar-ctes-lote-api").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "chaves": [
        "35121268252816000146570010000016161002008470",
        "35121268252816000146570010000016171002008477",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("brasildados/baixar-ctes-lote-api").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "chaves": [
    "35121268252816000146570010000016161002008470",
    "35121268252816000146570010000016171002008477"
  ]
}' |
apify call brasildados/baixar-ctes-lote-api --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=brasildados/baixar-ctes-lote-api",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Baixar CTEs em Lote: XML + DACTE em ZIP",
        "description": "Consulta chaves CT-e (modelo 57) em paralelo e gera .zip com XMLs e DACTEs. Retorna URL de download, contagens e status por chave. | Query CT-e access keys in parallel and get a .zip with XMLs and DACTEs. Returns download URL, counts and per-key status.",
        "version": "1.0",
        "x-build-id": "EqN7bgy6PHim6GBVI"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/brasildados~baixar-ctes-lote-api/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-brasildados-baixar-ctes-lote-api",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/brasildados~baixar-ctes-lote-api/runs": {
            "post": {
                "operationId": "runs-sync-brasildados-baixar-ctes-lote-api",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/brasildados~baixar-ctes-lote-api/run-sync": {
            "post": {
                "operationId": "run-sync-brasildados-baixar-ctes-lote-api",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "chaves"
                ],
                "properties": {
                    "chaves": {
                        "title": "Chaves de Acesso CTE / CT-e Access Keys",
                        "minItems": 1,
                        "maxItems": 50,
                        "type": "array",
                        "description": "Chaves de acesso CT-e com 44 dígitos (modelo 57). Pontuação e espaços são ignorados automaticamente. Máximo 50 chaves por execução - envie em lotes maiores via chamadas sequenciais. / CT-e access keys (44 digits, model 57). Punctuation and spaces are stripped automatically. Maximum 50 keys per run.",
                        "items": {
                            "type": "string"
                        }
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
