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)

FieldTypeRequiredDescription
nifstring✅ YesIssuer taxpayer NIF
privateKeystring✅ YesIssuer RSA private key in PEM
requestIdstring✅ YesThe 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

FieldTypeDescription
successbooleantrue, query performed successfully
requestIdstringThe ID of the queried request
resultCodestringGlobal result code (see table below)
resultadostringReadable description of resultCode
documentosarrayList of documents and their statuses
documentos[].numerostringDocument number
documentos[].statusstring"valido" or "invalido"
documentos[].errosarrayList of errors (only when status: "invalido")
documentos[].erros[].codigostringAGT error code
documentos[].erros[].descricaostringError description

resultCode Meaning

CodeMeaningWhat to do
0All documents valid ✅Document was accepted by AGT
1Valid and invalid documents ⚠️Check documentos[].status field
2No document valid ❌Correct errors and reissue
7Premature query ⏳Wait and repeat the request
8Processing in progress ⏳Wait and repeat the request
9Processing canceled ❌Contact AGT support

Errors

Authentication Errors

HTTPcodeMessageCause
401UNAUTHORIZEDNot authorized.API Key was not sent
401UNAUTHORIZEDInvalid API Key.API Key does not exist or was revoked
403FORBIDDENInsufficient scope.The key does not have query scope

Validation Errors

HTTPcodeMessageCause
400INVALID_JSONInvalid JSON body.Request body is not valid JSON
400VALIDATION_ERRORInvalid payload. Required fields: nif, privateKey, requestId.Missing fields
400VALIDATION_ERRORToo small: expected string to have >=1 charactersrequestId empty

AGT Errors

HTTPcodeMessageCause
502AGT_ERRORsecretOrPrivateKey must be an asymmetric key…Invalid private key
502AGT_ERRORCommunication error with AGTAGT 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:

  1. Create series (if needed) → POST /v2/series/solicitar
  2. Issue document → POST /v2/documentos/emitir → get requestIdAGT
  3. Check status → POST /v2/documentos/status with requestIdAGT
  4. If resultCode is 7 or 8 → wait and repeat step 3
  5. If resultCode is 0 → ✅ document validated
  6. If resultCode is 1 or 2 → check erros[] and correct
A renderizar...