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
| Field | Type | Required | Description |
|---|
nif | string | ✅ Yes | Issuer taxpayer NIF |
privateKey | string | ✅ Yes | Issuer RSA private key in PEM |
companyName | string | ✅ Yes | Issuer name/company name |
idempotencyKey | string | Recommended | Unique key to allow safe retries (see Timeouts and Retries) |
documentos | array | ✅ Yes | List of documents (min 1, max 30) |
documentos[] object
| Field | Type | Required | Description |
|---|
numero | string | ✅ Yes | Unique document number (e.g. "FT FT3926S9043N/1") |
tipo | string | ✅ Yes | Type: FT, FR, NC, ND, RC, RG, etc. |
data | string | ✅ Yes | Issue date in YYYY-MM-DD format |
cliente | object | ✅ Yes | Customer data |
cliente.nome | string | ✅ Yes | Customer name |
cliente.nif | string | ✅ Yes | Customer NIF ("999999999" for final consumer) |
cliente.pais | string | No | ISO country code (default: "AO") |
itens | array | ⚠️ | Document lines. Do not use for RC/RG/AR |
reciboDe | array | ⚠️ | Receipt origin documents. Only for RC/RG/AR |
totais | object | No | Document totals (calculated automatically if omitted) |
totais.total | number | ✅ | Total including tax |
totais.subtotal | number | No | Total excluding tax |
totais.totalImpostos | number | No | Total tax |
eacCode | string | No | CAE code (5 characters) |
itens[] object, Document lines
| Field | Type | Required | Description |
|---|
codigo | string | ✅ Yes | Product/service code |
descricao | string | ✅ Yes | Product/service description |
quantidade | number | ✅ Yes | Quantity (integer or decimal) |
unidade | string | ✅ Yes | Unit of measure (e.g. "UN", "KG", "H") |
precoUnitario | number | ✅ Yes | Unit price excluding tax |
taxa | number | No | VAT percentage (default: 14). Use 0 for exempt |
motivoIsencao | string | No | Exemption code when taxa: 0 (e.g. "M00") |
desconto | number | No | Line discount amount (default: 0) |
isServico | boolean | No | true = service, false = good (default) |
operationType | string | No | Override AGT operation type |
retencaoTipo | string | No | Withholding type: "IRT", "II", "IS", "IVA" |
retencaoTaxa | number | No | Withholding percentage (e.g. 6.5 for 6.5%) |
referencia | object | ⚠️ | Origin document. Required for NC and ND |
referencia.documento | string | ✅ | Origin document number (e.g. "FT FT3926S9043N/1") |
referencia.motivo | string | No | Correction reason |
reciboDe[] object, Only for RC/RG/AR
| Field | Type | Required | Description |
|---|
documento | string | ✅ Yes | Document number to regularize |
dataDocumento | string | No | Origin document date (YYYY-MM-DD) |
valor | number | ✅ Yes | Value 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
| Field | Type | Description |
|---|
success | boolean | true, document submitted to AGT |
requestIdAGT | string | AGT ID to check status later |
dataEnvio | string | ISO 8601 submission timestamp |
documentos | array | List 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
| 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 the facturas:emitir scope |
Validation Errors
| HTTP | code | Message | Cause |
|---|
| 400 | INVALID_JSON | Invalid JSON body. | Request body is not valid JSON |
| 400 | VALIDATION_ERROR | Invalid payload. Check documentation. | Required fields missing or invalid |
| 400 | VALIDATION_ERROR | Invalid option: expected one of “FT”|“FR”|… | Invalid document tipo |
AGT Errors
| HTTP | code | Message | Cause |
|---|
| 502 | AGT_ERROR | secretOrPrivateKey must be an asymmetric key… | Invalid or corrupt private key |
| 502 | AGT_ERROR | Communication error with AGT | AGT service unavailable |
| 409 | CONFLICT | Previous 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:
| HTTP | code | Meaning |
|---|
| 504 | AGT_TIMEOUT | AGT did not respond within the time limit |
| 502 | AGT_UNAVAILABLE | AGT returned an internal error (e.g. OSB-380000) |
In these cases the result is indeterminate: AGT may have processed the document anyway. Therefore:
- Always send an
idempotencyKey. Without it there is no safe way to retry an issuance. - Retry with the SAME
idempotencyKey — never resubmit the document with a new number. - 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;
}
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
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;
}
$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
| Type | itens | reciboDe | referencia | Notes |
|---|
| FT Invoice | ✅ Required | ❌ | ❌ | Normal fiscal document |
| FR Invoice/Receipt | ✅ Required | ❌ | ❌ | Invoice that also serves as receipt |
| NC Credit Note | ✅ Required | ❌ | ✅ Required | Return/discount, reference origin document |
| ND Debit Note | ✅ Required | ❌ | Optional | Overcharge correction |
| RC Receipt | ❌ | ✅ Required | ❌ | Payment receipt |
| RG General Receipt | ❌ | ✅ Required | ❌ | Other receipts |
| AR Collection Notice/Receipt | ❌ | ✅ Required | ❌ | Notice + receipt |