Issue Document

POST /v2/documentos/emitir

Sends fiscal documents for validation at AGT. A single endpoint handles all document types: invoices, invoice/receipts, credit notes, debit notes, receipts and more.

Why use this endpoint? This is the gateway’s main endpoint. After creating the necessary series, use this endpoint to submit each fiscal document. AGT accepts the document immediately and returns a requestIdAGT. Final validation is deferred, you should check the result later via status.


Request

Authentication

Authorization: Bearer feak_...

or

x-api-key: feak_...

Required scope: facturas:emitir or *

Body (JSON)

General structure

FieldTypeRequiredDescription
nifstring✅ YesIssuer taxpayer NIF
privateKeystring✅ YesIssuer RSA private key in PEM
companyNamestring✅ YesIssuer name/company name
idempotencyKeystringRecommendedUnique key to allow safe retries (see Timeouts and Retries)
documentosarray✅ YesList of documents (min 1, max 30)

documentos[] object

FieldTypeRequiredDescription
numerostring✅ YesUnique document number (e.g. "FT FT3926S9043N/1")
tipostring✅ YesType: FT, FR, NC, ND, RC, RG, etc.
datastring✅ YesIssue date in YYYY-MM-DD format
clienteobject✅ YesCustomer data
cliente.nomestring✅ YesCustomer name
cliente.nifstring✅ YesCustomer NIF ("999999999" for final consumer)
cliente.paisstringNoISO country code (default: "AO")
itensarray⚠️Document lines. Do not use for RC/RG/AR
reciboDearray⚠️Receipt origin documents. Only for RC/RG/AR
totaisobjectNoDocument totals (calculated automatically if omitted)
totais.totalnumber✅Total including tax
totais.subtotalnumberNoTotal excluding tax
totais.totalImpostosnumberNoTotal tax
eacCodestringNoCAE code (5 characters)

itens[] object, Document lines

FieldTypeRequiredDescription
codigostring✅ YesProduct/service code
descricaostring✅ YesProduct/service description
quantidadenumber✅ YesQuantity (integer or decimal)
unidadestring✅ YesUnit of measure (e.g. "UN", "KG", "H")
precoUnitarionumber✅ YesUnit price excluding tax
taxanumberNoVAT percentage (default: 14). Use 0 for exempt
motivoIsencaostringNoExemption code when taxa: 0 (e.g. "M00")
descontonumberNoLine discount amount (default: 0)
isServicobooleanNotrue = service, false = good (default)
operationTypestringNoOverride AGT operation type
retencaoTipostringNoWithholding type: "IRT", "II", "IS", "IVA"
retencaoTaxanumberNoWithholding percentage (e.g. 6.5 for 6.5%)
referenciaobject⚠️Origin document. Required for NC and ND
referencia.documentostring✅Origin document number (e.g. "FT FT3926S9043N/1")
referencia.motivostringNoCorrection reason

reciboDe[] object, Only for RC/RG/AR

FieldTypeRequiredDescription
documentostring✅ YesDocument number to regularize
dataDocumentostringNoOrigin document date (YYYY-MM-DD)
valornumber✅ YesValue to regularize (excluding tax)

Response

Success (200 OK)

{
  "success": true,
  "requestIdAGT": "202600002471491",
  "dataEnvio": "2026-07-25T18:50:30.257Z",
  "documentos": [
    { "numero": "FT FT3926S9043N/1", "tipo": "FT" }
  ]
}

Response Fields

FieldTypeDescription
successbooleantrue, document submitted to AGT
requestIdAGTstringAGT ID to check status later
dataEnviostringISO 8601 submission timestamp
documentosarrayList of submitted documents

⚠️ Important: AGT performs deferred validation. success: true only means the document was accepted for processing. To know if it was validated or rejected, use status with the requestIdAGT.


Payload Examples

Simple Invoice (FT)

{
  "nif": "5000537039",
  "privateKey": "-----BEGIN PRIVATE KEY-----\n...",
  "companyName": "SONHE TESTE",
  "documentos": [{
    "numero": "FT FT3926S9043N/1",
    "tipo": "FT",
    "data": "2026-07-25",
    "cliente": { "nome": "Cliente Exemplo", "nif": "999999999", "pais": "AO" },
    "itens": [{
      "codigo": "PROD001",
      "descricao": "Example product",
      "quantidade": 2,
      "unidade": "UN",
      "precoUnitario": 5000,
      "taxa": 14
    }]
  }]
}

Invoice Withholding Tax (FT + IRT)

{
  "nif": "5000537039",
  "privateKey": "-----BEGIN PRIVATE KEY-----\n...",
  "companyName": "SONHE TESTE",
  "documentos": [{
    "numero": "FT FT3926S9043N/2",
    "tipo": "FT",
    "data": "2026-07-25",
    "cliente": { "nome": "Cliente Serviço", "nif": "999999999", "pais": "AO" },
    "itens": [{
      "codigo": "CONS001",
      "descricao": "Consulting service",
      "quantidade": 1,
      "unidade": "UN",
      "precoUnitario": 100000,
      "taxa": 14,
      "isServico": true,
      "retencaoTipo": "IRT",
      "retencaoTaxa": 6.5
    }]
  }]
}

Credit Note (NC), Reference to origin document

{
  "nif": "5000537039",
  "privateKey": "-----BEGIN PRIVATE KEY-----\n...",
  "companyName": "SONHE TESTE",
  "documentos": [{
    "numero": "NC NC3926S7016N/1",
    "tipo": "NC",
    "data": "2026-07-25",
    "cliente": { "nome": "Cliente Devolução", "nif": "999999999", "pais": "AO" },
    "itens": [{
      "codigo": "PROD001",
      "descricao": "Return of defective product",
      "quantidade": 1,
      "unidade": "UN",
      "precoUnitario": 5000,
      "taxa": 14,
      "referencia": {
        "documento": "FT FT3926S9043N/1",
        "motivo": "Defective product"
      }
    }]
  }]
}

Receipt (RC), No lines, with references to paid documents

{
  "nif": "5000537039",
  "privateKey": "-----BEGIN PRIVATE KEY-----\n...",
  "companyName": "SONHE TESTE",
  "documentos": [{
    "numero": "RC RC3926S2186N/1",
    "tipo": "RC",
    "data": "2026-07-25",
    "cliente": { "nome": "Cliente Pagamento", "nif": "999999999", "pais": "AO" },
    "reciboDe": [{
      "documento": "FT FT3926S9043N/1",
      "dataDocumento": "2026-07-25",
      "valor": 10000
    }]
  }]
}

Batch / Multiple documents

{
  "nif": "5000537039",
  "privateKey": "-----BEGIN PRIVATE KEY-----\n...",
  "companyName": "SONHE TESTE",
  "documentos": [
    {
      "numero": "FT FT3926S9043N/3",
      "tipo": "FT",
      "data": "2026-07-25",
      "cliente": { "nome": "Cliente A", "nif": "999999999", "pais": "AO" },
      "itens": [{ "codigo": "A001", "descricao": "Product A", "quantidade": 1, "unidade": "UN", "precoUnitario": 3000, "taxa": 14 }]
    },
    {
      "numero": "FR FR3926S6237N/1",
      "tipo": "FR",
      "data": "2026-07-25",
      "cliente": { "nome": "Cliente B", "nif": "999999999", "pais": "AO" },
      "itens": [{ "codigo": "B001", "descricao": "Product B", "quantidade": 2, "unidade": "UN", "precoUnitario": 1500, "taxa": 14 }]
    }
  ]
}

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 the facturas:emitir scope

Validation Errors

HTTPcodeMessageCause
400INVALID_JSONInvalid JSON body.Request body is not valid JSON
400VALIDATION_ERRORInvalid payload. Check documentation.Required fields missing or invalid
400VALIDATION_ERRORInvalid option: expected one of “FT”|“FR”|…Invalid document tipo

AGT Errors

HTTPcodeMessageCause
502AGT_ERRORsecretOrPrivateKey must be an asymmetric key…Invalid or corrupt private key
502AGT_ERRORCommunication error with AGTAGT service unavailable
409CONFLICTPrevious issuance in indeterminate state at AGT…Retry of an issuance that failed with timeout and could not be reconciled

Timeouts and Retries

AGT validates documents deferredly and its bus (OSB) may be slow or fail. When this happens, we return:

HTTPcodeMeaning
504AGT_TIMEOUTAGT did not respond within the time limit
502AGT_UNAVAILABLEAGT returned an internal error (e.g. OSB-380000)

In these cases the result is indeterminate: AGT may have processed the document anyway. Therefore:

  1. Always send an idempotencyKey. Without it there is no safe way to retry an issuance.
  2. Retry with the SAME idempotencyKey — never resubmit the document with a new number.
  3. The gateway automatically reconciles with AGT: if the document was registered, it returns success (_reconciled: true); if not, it submits normally; if it cannot confirm, it returns 409 CONFLICT.

⚠️ Duplicate document: AGT accepts documents with the same number at registration time (HTTP 200). Rejection for duplication only appears in deferred validation, when checking status.


Code Examples

TypeScript / Node.js

const API_KEY = "feak_bfc76ba48c0c286c9ce4bb2fcd7e178a399e329c59e529776bb5e01b0bfe8712";
const GATEWAY_URL = "https://connect.factflexi.com";

interface EmitirResultado {
  success: boolean;
  requestIdAGT: string;
  dataEnvio: string;
  documentos: { numero: string; tipo: string }[];
}

async function emitirDocumento(payload: object): Promise<EmitirResultado> {
  const response = await fetch(`${GATEWAY_URL}/v2/documentos/emitir`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY,
    },
    body: JSON.stringify(payload),
  });

  const data = await response.json();
  if (!data.success) throw new Error(`${data.code}: ${data.error}`);
  return data;
}

// Usage, issue a simple invoice
const resultado = await emitirDocumento({
  nif: "5000537039",
  privateKey: "-----BEGIN PRIVATE KEY-----\n...",
  companyName: "SONHE TESTE",
  documentos: [{
    numero: "FT FT3926S9043N/1",
    tipo: "FT",
    data: "2026-07-25",
    cliente: { nome: "Cliente", nif: "999999999", pais: "AO" },
    itens: [{
      codigo: "PROD001", descricao: "Produto",
      quantidade: 2, unidade: "UN", precoUnitario: 5000, taxa: 14,
    }],
  }],
});

console.log(`Document submitted. requestIdAGT: ${resultado.requestIdAGT}`);

Python

import requests

API_KEY = "feak_bfc76ba48c0c286c9ce4bb2fcd7e178a399e329c59e529776bb5e01b0bfe8712"
GATEWAY_URL = "https://connect.factflexi.com"

def emitir_documento(payload: dict) -> dict:
    response = requests.post(
        f"{GATEWAY_URL}/v2/documentos/emitir",
        json=payload,
        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')}")
    return data

# Usage, issue invoice with retention
resultado = emitir_documento({
    "nif": "5000537039",
    "privateKey": "-----BEGIN PRIVATE KEY-----\n...",
    "companyName": "SONHE TESTE",
    "documentos": [{
        "numero": "FT FT3926S9043N/3",
        "tipo": "FT",
        "data": "2026-07-25",
        "cliente": {"nome": "Cliente", "nif": "999999999", "pais": "AO"},
        "itens": [{
            "codigo": "CONS001", "descricao": "Consultoria",
            "quantidade": 1, "unidade": "UN", "precoUnitario": 100000,
            "taxa": 14, "isServico": True,
            "retencaoTipo": "IRT", "retencaoTaxa": 6.5,
        }],
    }],
})

print(f"Submitted. requestIdAGT: {resultado['requestIdAGT']}")

PHP

<?php
define('API_KEY', 'feak_bfc76ba48c0c286c9ce4bb2fcd7e178a399e329c59e529776bb5e01b0bfe8712');
define('GATEWAY_URL', 'https://connect.factflexi.com');

function emitirDocumento(array $payload): array {
    $ch = curl_init(GATEWAY_URL . '/v2/documentos/emitir');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'x-api-key: ' . API_KEY,
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        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']}");
    }
    return $data;
}

// Usage
$resultado = emitirDocumento([
    'nif' => '5000537039',
    'privateKey' => "-----BEGIN PRIVATE KEY-----\n...",
    'companyName' => 'SONHE TESTE',
    'documentos' => [[
        'numero' => 'FT FT3926S9043N/5',
        'tipo' => 'FT',
        'data' => '2026-07-25',
        'cliente' => ['nome' => 'Cliente', 'nif' => '999999999', 'pais' => 'AO'],
        'itens' => [[
            'codigo' => 'PROD001', 'descricao' => 'Produto',
            'quantidade' => 2, 'unidade' => 'UN',
            'precoUnitario' => 5000, 'taxa' => 14,
        ]],
    ]],
]);

echo "Submitted. requestIdAGT: {$resultado['requestIdAGT']}\n";

Rules by Document Type

TypeitensreciboDereferenciaNotes
FT Invoice✅ Required❌❌Normal fiscal document
FR Invoice/Receipt✅ Required❌❌Invoice that also serves as receipt
NC Credit Note✅ Required❌✅ RequiredReturn/discount, reference origin document
ND Debit Note✅ Required❌OptionalOvercharge correction
RC Receipt❌✅ Required❌Payment receipt
RG General Receipt❌✅ Required❌Other receipts
AR Collection Notice/Receipt❌✅ Required❌Notice + receipt