Check Document Status
POST /v2/documentos/status Checks the validation result of documents previously submitted to AGT. AGT processes documents deferredly, this endpoint allows you to know if each document was validated or rejected, and which errors were found.
Why use this endpoint? After issuing a document via emitir, you receive a requestIdAGT. Use that ID here to verify if AGT accepted or rejected the document. AGT processing can take from a few seconds to several minutes.
Request
Authentication
Authorization: Bearer feak_... or
x-api-key: feak_... Required scope: facturas:consultar or facturas:emitir or *
Body (JSON)
| Field | Type | Required | Description |
|---|---|---|---|
nif | string | ✅ Yes | Issuer taxpayer NIF |
privateKey | string | ✅ Yes | Issuer RSA private key in PEM |
requestId | string | ✅ Yes | The requestIdAGT returned by the emitir endpoint |
Response
Success, All documents valid (200 OK)
{
"success": true,
"requestId": "202600002471491",
"resultCode": "0",
"resultado": "Todos os documentos validos",
"documentos": [
{
"numero": "FT FT3926S9043N/1",
"status": "valido"
}
]
} Success, Document invalid (200 OK)
{
"success": true,
"requestId": "202600002471572",
"resultCode": "2",
"resultado": "Nenhum documento valido",
"documentos": [
{
"numero": "FT FT3926S9043N/1",
"status": "invalido",
"erros": [
{
"codigo": "E09",
"descricao": "Factura especificada já consta no repositório do sistema"
}
]
}
]
} Processing still in progress (200 OK)
{
"success": true,
"requestId": "202600002471491",
"resultCode": "8",
"resultado": "Processamento em curso",
"documentos": []
} Response Fields
| Field | Type | Description |
|---|---|---|
success | boolean | true, query performed successfully |
requestId | string | The ID of the queried request |
resultCode | string | Global result code (see table below) |
resultado | string | Readable description of resultCode |
documentos | array | List of documents and their statuses |
documentos[].numero | string | Document number |
documentos[].status | string | "valido" or "invalido" |
documentos[].erros | array | List of errors (only when status: "invalido") |
documentos[].erros[].codigo | string | AGT error code |
documentos[].erros[].descricao | string | Error description |
resultCode Meaning
| Code | Meaning | What to do |
|---|---|---|
0 | All documents valid ✅ | Document was accepted by AGT |
1 | Valid and invalid documents ⚠️ | Check documentos[].status field |
2 | No document valid ❌ | Correct errors and reissue |
7 | Premature query ⏳ | Wait and repeat the request |
8 | Processing in progress ⏳ | Wait and repeat the request |
9 | Processing canceled ❌ | Contact AGT support |
Errors
Authentication Errors
| HTTP | code | Message | Cause |
|---|---|---|---|
| 401 | UNAUTHORIZED | Not authorized. | API Key was not sent |
| 401 | UNAUTHORIZED | Invalid API Key. | API Key does not exist or was revoked |
| 403 | FORBIDDEN | Insufficient scope. | The key does not have query scope |
Validation Errors
| HTTP | code | Message | Cause |
|---|---|---|---|
| 400 | INVALID_JSON | Invalid JSON body. | Request body is not valid JSON |
| 400 | VALIDATION_ERROR | Invalid payload. Required fields: nif, privateKey, requestId. | Missing fields |
| 400 | VALIDATION_ERROR | Too small: expected string to have >=1 characters | requestId empty |
AGT Errors
| HTTP | code | Message | Cause |
|---|---|---|---|
| 502 | AGT_ERROR | secretOrPrivateKey must be an asymmetric key… | Invalid private key |
| 502 | AGT_ERROR | Communication error with AGT | AGT service unavailable |
Code Examples
TypeScript / Node.js
const API_KEY = "feak_bfc76ba48c0c286c9ce4bb2fcd7e178a399e329c59e529776bb5e01b0bfe8712";
const GATEWAY_URL = "https://connect.factflexi.com";
async function consultarEstado(
nif: string,
privateKey: string,
requestId: string,
) {
const response = await fetch(`${GATEWAY_URL}/v2/documentos/status`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": API_KEY,
},
body: JSON.stringify({ nif, privateKey, requestId }),
});
const data = await response.json();
if (!data.success) {
throw new Error(`${data.code}: ${data.error}`);
}
console.log(`Resultado: ${data.resultado} (code: ${data.resultCode})`);
for (const doc of data.documentos) {
if (doc.status === "valido") {
console.log(` ✅ ${doc.numero}, Valid`);
} else {
console.log(` ❌ ${doc.numero}, Invalid`);
for (const erro of doc.erros || []) {
console.log(` [${erro.codigo}] ${erro.descricao}`);
}
}
}
return data;
}
// Usage
const estado = await consultarEstado(
"5000537039",
"-----BEGIN PRIVATE KEY-----\n...",
"202600002471491",
);
if (estado.resultCode === "8") {
console.log("Still processing, try again in a few seconds...");
} Python
import requests
import time
API_KEY = "feak_bfc76ba48c0c286c9ce4bb2fcd7e178a399e329c59e529776bb5e01b0bfe8712"
GATEWAY_URL = "https://connect.factflexi.com"
def consultar_estado(nif: str, private_key: str, request_id: str) -> dict:
response = requests.post(
f"{GATEWAY_URL}/v2/documentos/status",
json={"nif": nif, "privateKey": private_key, "requestId": request_id},
headers={
"Content-Type": "application/json",
"x-api-key": API_KEY,
},
)
data = response.json()
if not data.get("success"):
raise Exception(f"{data.get('code')}: {data.get('error')}")
print(f"Resultado: {data['resultado']} (code: {data['resultCode']})")
for doc in data["documentos"]:
if doc["status"] == "valido":
print(f" ✅ {doc['numero']}, Valid")
else:
print(f" ❌ {doc['numero']}, Invalid")
for erro in doc.get("erros", []):
print(f" [{erro['codigo']}] {erro['descricao']}")
return data
# Usage with polling until processing finishes
def aguardar_validacao(nif: str, private_key: str, request_id: str, max_tentativas=10):
for _ in range(max_tentativas):
estado = consultar_estado(nif, private_key, request_id)
if estado["resultCode"] not in ("7", "8"):
return estado
time.sleep(3)
raise Exception("Timeout: processing still in progress")
# Usage
estado = aguardar_validacao(
"5000537039",
"-----BEGIN PRIVATE KEY-----\n...",
"202600002471491",
) PHP
<?php
define('API_KEY', 'feak_bfc76ba48c0c286c9ce4bb2fcd7e178a399e329c59e529776bb5e01b0bfe8712');
define('GATEWAY_URL', 'https://connect.factflexi.com');
function consultarEstado(
string $nif,
string $privateKey,
string $requestId
): array {
$ch = curl_init(GATEWAY_URL . '/v2/documentos/status');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-api-key: ' . API_KEY,
],
CURLOPT_POSTFIELDS => json_encode([
'nif' => $nif,
'privateKey' => $privateKey,
'requestId' => $requestId,
]),
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (!$data['success']) {
throw new Exception("{$data['code']}: {$data['error']}");
}
echo "Resultado: {$data['resultado']} (code: {$data['resultCode']})\n";
foreach ($data['documentos'] as $doc) {
if ($doc['status'] === 'valido') {
echo " ✅ {$doc['numero']}, Valid\n";
} else {
echo " ❌ {$doc['numero']}, Invalid\n";
foreach ($doc['erros'] ?? [] as $erro) {
echo " [{$erro['codigo']}] {$erro['descricao']}\n";
}
}
}
return $data;
}
// Usage
$estado = consultarEstado(
'5000537039',
"-----BEGIN PRIVATE KEY-----\n...",
'202600002471491'
);
// If still processing, wait
if (in_array($estado['resultCode'], ['7', '8'])) {
echo "Still processing. Try again.\n";
} Full Flow: Issue → Validate
The typical document issuance flow is:
- Create series (if needed) →
POST /v2/series/solicitar - Issue document →
POST /v2/documentos/emitir→ getrequestIdAGT - Check status →
POST /v2/documentos/statuswithrequestIdAGT - If
resultCodeis7or8→ wait and repeat step 3 - If
resultCodeis0→ ✅ document validated - If
resultCodeis1or2→ checkerros[]and correct
A renderizar...