Pular para o conteúdo

Exemplos em Java

Setup

Requer Java 11+ (HttpClient nativo) e uma lib JSON (usando Jackson aqui).

pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.0</version>
</dependency>
Terminal window
export MYSE_API_BASE="https://api.mysebr.com.br/nfemyse-v3/rest"
export MYSE_API_TOKEN="seu_token_aqui"

Cliente HTTP centralizado

package com.example.myse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
public class MyseApi {
public static class ApiError extends RuntimeException {
public final int httpStatus;
public final JsonNode payload;
public final String requestId;
public ApiError(int s, String m, JsonNode p, String r) {
super(m);
this.httpStatus = s;
this.payload = p;
this.requestId = r;
}
}
private static final String BASE = System.getenv("MYSE_API_BASE");
private static final String TOKEN = System.getenv("MYSE_API_TOKEN");
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
public static JsonNode call(String method, String path, Map<String, ?> body)
throws Exception {
return call(method, path, body, Duration.ofSeconds(30));
}
/** Variante com timeout próprio (a classificação fiscal pede 70 a 90 s). */
public static JsonNode call(String method, String path, Map<String, ?> body, Duration timeout)
throws Exception {
HttpRequest.BodyPublisher publisher = (body == null)
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(body));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(BASE + path))
.timeout(timeout)
.header("Authorization", "Token " + TOKEN)
.header("Content-Type", "application/json")
.method(method, publisher)
.build();
HttpResponse<String> res = CLIENT.send(req, HttpResponse.BodyHandlers.ofString());
String requestId = res.headers().firstValue("X-Request-Id").orElse(null);
JsonNode json = MAPPER.readTree(res.body());
if (res.statusCode() >= 400) {
String msg = json.path("error").path("message").asText("HTTP " + res.statusCode());
throw new ApiError(res.statusCode(), msg, json, requestId);
}
if ("999".equals(json.path("status").asText())) {
String msg = json.path("data").path("erro").asText(
json.path("descricao").asText("erro")
);
String rid = json.path("meta").path("request_id").asText(requestId);
throw new ApiError(200, msg, json, rid);
}
return json;
}
}

Cenário: emitir NFCe com polling

public class EmissorNFCe {
private static final Set<String> TERMINAIS =
Set.of("004", "010", "900", "999");
public static JsonNode emitir(Pedido p) throws Exception {
Map<String, Object> body = Map.of(
"serie", "65",
"cfop", "5102",
"numero-origem", "PED-" + p.getId(),
"tp_pagamento", p.getFormaPagamento(),
"cliente", p.getCpfCnpjCliente(),
"itens", p.getItens().stream().map(i -> Map.of(
"produto", i.getSku(),
"quantidade", String.valueOf(i.getQtd()),
"valor-unitario", String.valueOf(i.getPreco())
)).toList()
);
JsonNode emissao = MyseApi.call("POST", "/nfce/emissao", body);
String status = emissao.path("status").asText();
if (!"001".equals(status) && !"050".equals(status)) {
throw new RuntimeException("Emissão falhou: " + emissao.path("descricao").asText());
}
String recibo = emissao.path("data").path("recibo").asText();
System.out.printf("[emissao] recibo=%s request_id=%s%n",
recibo, emissao.path("meta").path("request_id").asText());
// Polling
long inicio = System.currentTimeMillis();
long wait = 2000;
while (System.currentTimeMillis() - inicio < 5 * 60_000L) {
Thread.sleep(wait);
JsonNode consulta = MyseApi.call("GET", "/nfce/cupom/" + recibo, null);
String st = consulta.path("status").asText();
System.out.println("[polling] status=" + st);
if (TERMINAIS.contains(st)) {
if ("004".equals(st)) return consulta.path("data");
throw new RuntimeException("Status terminal não-sucesso: " + st);
}
wait = Math.min((long)(wait * 1.5), 30_000L);
}
throw new RuntimeException("Timeout aguardando recibo " + recibo);
}
}

Retry com backoff

public static <T> T comRetry(Callable<T> fn, int maxTentativas) throws Exception {
Exception last = null;
for (int i = 1; i <= maxTentativas; i++) {
try {
return fn.call();
} catch (MyseApi.ApiError e) {
if (e.payload != null && "999".equals(e.payload.path("status").asText())) {
throw e; // validação: não retentar
}
last = e;
} catch (Exception e) {
last = e;
}
if (i < maxTentativas) {
Thread.sleep(1000L * (long) Math.pow(2, i - 1));
}
}
throw last;
}

Helper de polling reutilizável

public class FiscalHelpers {
static final Set<String> TERMINAIS = Set.of("004", "010", "900", "999");
/** Polling com backoff exponencial até status terminal. */
public static JsonNode aguardarRecibo(String pathBase, String recibo) throws Exception {
return aguardarRecibo(pathBase, recibo, 5 * 60_000L);
}
public static JsonNode aguardarRecibo(String pathBase, String recibo, long timeoutMs)
throws Exception {
long inicio = System.currentTimeMillis();
long wait = 2000;
while (System.currentTimeMillis() - inicio < timeoutMs) {
Thread.sleep(wait);
JsonNode resp = MyseApi.call("GET", pathBase + "/" + recibo, null);
if (TERMINAIS.contains(resp.path("status").asText())) return resp;
wait = Math.min((long)(wait * 1.5), 30_000L);
}
throw new RuntimeException("Timeout aguardando recibo " + recibo);
}
public static void validarMotivo(String motivo) {
if (motivo.length() < 15 || motivo.length() > 255) {
throw new IllegalArgumentException("motivo deve ter entre 15 e 255 caracteres");
}
}
/** Texto da carta de correção (POST /nfe/correcao): 15 a 1000 caracteres desde a 3.15.1. */
public static void validarTextoCorrecao(String texto) {
int n = texto.codePointCount(0, texto.length());
if (n < 15 || n > 1000) {
throw new IllegalArgumentException("texto da correção deve ter entre 15 e 1000 caracteres");
}
}
}

Emitir NF-e (com transporte completo)

public static JsonNode emitirNFe(Pedido p) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("serie", "1");
body.put("cfop", "5102");
body.put("numero-origem", "PED-" + p.getId());
body.put("tipo", "S");
body.put("finalidade", "N");
body.put("valor-despesas", "0.00");
body.put("cliente", p.getCpfCnpjCliente());
Map<String, Object> transporte = new HashMap<>();
transporte.put("modalidade", "0");
transporte.put("transportadora", p.getTransportadora());
transporte.put("placa-veiculo", p.getPlaca());
transporte.put("valor-frete", p.getFrete());
transporte.put("valor-seguro", "0.00");
transporte.put("peso-bruto", p.getPesoBruto());
transporte.put("peso-liquido", p.getPesoLiquido());
transporte.put("quantidade-volume", "1");
transporte.put("especie-volume", "Caixa");
transporte.put("marca-volume", "Embalagem");
body.put("transporte", transporte);
body.put("itens", p.getItens().stream().map(i -> Map.of(
"produto", i.getSku(),
"quantidade", String.valueOf(i.getQtd()),
"valor-unitario", String.valueOf(i.getPreco())
)).toList());
if (p.getFaturas() != null) {
body.put("faturas", p.getFaturas().stream().map(f -> Map.of(
"valor", String.valueOf(f.getValor()),
"data", f.getData()
)).toList());
}
JsonNode emissao = MyseApi.call("POST", "/nfe/emissao", body);
String status = emissao.path("status").asText();
if (!"001".equals(status) && !"050".equals(status)) {
throw new RuntimeException("Emissão falhou: " + emissao.path("descricao").asText());
}
String recibo = emissao.path("data").path("recibo").asText();
JsonNode resultado = FiscalHelpers.aguardarRecibo("/nfe/nota", recibo);
if (!"004".equals(resultado.path("status").asText())) {
throw new RuntimeException("Status terminal não-sucesso: " + resultado.path("status"));
}
return resultado.path("data"); // inclui sefaz.chave, url-danfe, url-xml
}

Cancelar NF-e

public static JsonNode cancelarNFe(String chave, String motivo) throws Exception {
FiscalHelpers.validarMotivo(motivo);
JsonNode cancel = MyseApi.call("POST", "/nfe/cancelamento",
Map.of("chave", chave, "motivo", motivo));
if (!"001".equals(cancel.path("status").asText())) {
throw new RuntimeException(cancel.path("descricao").asText());
}
return FiscalHelpers.aguardarRecibo("/nfe/cancelamento",
cancel.path("data").path("recibo").asText());
}

Lançar carta de correção (CC-e)

/**
* O campo "motivo" na CC-e é o TEXTO da correção (xCorrecao): 15 a 1000 caracteres.
* (O motivo do cancelamento continua entre 15 e 255.)
*/
public static JsonNode cartaCorrecaoNFe(String chave, String textoCorrecao) throws Exception {
FiscalHelpers.validarTextoCorrecao(textoCorrecao);
JsonNode cce = MyseApi.call("POST", "/nfe/correcao",
Map.of("chave", chave, "motivo", textoCorrecao));
if (!"001".equals(cce.path("status").asText())) {
throw new RuntimeException(cce.path("descricao").asText());
}
return FiscalHelpers.aguardarRecibo("/nfe/correcao",
cce.path("data").path("recibo").asText());
}

Cancelar NFC-e

public static JsonNode cancelarNFCe(String chave, String motivo) throws Exception {
FiscalHelpers.validarMotivo(motivo);
JsonNode cancel = MyseApi.call("POST", "/nfce/cancelamento",
Map.of("chave", chave, "motivo", motivo));
if (!"001".equals(cancel.path("status").asText())) {
throw new RuntimeException(cancel.path("descricao").asText());
}
return FiscalHelpers.aguardarRecibo("/nfce/cancelamento",
cancel.path("data").path("recibo").asText());
}

Emitir NFS-e (Nota Fiscal de Serviço)

public static JsonNode emitirNFSe(Servico s) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("numero-origem", "OS-" + s.getId());
body.put("observacao", s.getObservacao());
body.put("nome-contato", s.getNomeContato());
body.put("telefone-contato", s.getTelefoneContato());
body.put("data-fim", s.getDataFim());
body.put("cliente", s.getCpfCnpjCliente());
body.put("itens", s.getItens().stream().map(i -> Map.of(
"produto", i.getCodigoServico(),
"quantidade", String.valueOf(i.getQtd()),
"valor-unitario", String.valueOf(i.getPreco())
)).toList());
JsonNode emissao = MyseApi.call("POST", "/nfse/emissao", body);
String status = emissao.path("status").asText();
if (!"001".equals(status) && !"050".equals(status)) {
throw new RuntimeException("Emissão NFSe falhou: " + emissao.path("descricao"));
}
String recibo = emissao.path("data").path("recibo").asText();
JsonNode resultado = FiscalHelpers.aguardarRecibo("/nfse/nota", recibo);
if (!"004".equals(resultado.path("status").asText())) {
throw new RuntimeException("Status terminal não-sucesso: " + resultado.path("status"));
}
return resultado.path("data");
}

Cancelar NFS-e

public static JsonNode cancelarNFSe(String chave, String motivo) throws Exception {
FiscalHelpers.validarMotivo(motivo);
return MyseApi.call("POST", "/nfse/cancelamento",
Map.of("chave", chave, "motivo", motivo));
}

Reconhecer nota de fornecedor (MD-e)

/**
* Códigos de reconhecimento:
* "210200" — Confirmação da operação (terminal, irreversível)
* "210210" — Ciência da operação (provisório, 15 dias)
* "210220" — Desconhecimento da operação
* "210240" — Operação não realizada
*/
public static JsonNode reconhecerNotaFornecedor(String chave, String codigo) throws Exception {
Set<String> validos = Set.of("210200", "210210", "210220", "210240");
if (!validos.contains(codigo)) {
throw new IllegalArgumentException("Código inválido: " + codigo);
}
JsonNode resp = MyseApi.call("POST", "/nffornecedor/reconhecimento",
Map.of("chave", chave, "codigo-reconhecimento", codigo));
if (!"001".equals(resp.path("status").asText())) {
throw new RuntimeException(resp.path("descricao").asText());
}
return FiscalHelpers.aguardarRecibo("/nffornecedor",
resp.path("data").path("recibo").asText());
}

Consulta completa por recibo

Para o polling, a consulta simples (/nfe/nota/{recibo}, /nfce/cupom/{recibo}) basta. A versão /completa traz o documento inteiro: itens, cliente e dados da SEFAZ e, na NF-e, também transporte, faturas e notas referenciadas. Veja Emitir NF-e e Emitir NFC-e.

JsonNode nfeCompleta = MyseApi.call("GET", "/nfe/nota/" + recibo + "/completa", null);
JsonNode nfceCompleta = MyseApi.call("GET", "/nfce/cupom/" + recibo + "/completa", null);
// NFC-e paginadas pelo path (forma legada): página 1, 50 por página (máximo 500)
JsonNode cupons = MyseApi.call("GET", "/nfce/paginacao/1/50", null);

Inutilizar numeração

Fecha na SEFAZ um buraco na numeração de NF-e ou NFC-e. É assíncrona, como a emissão. Veja Inutilizar numeração.

/** tipo: "nfe" (modelo 55) ou "nfce" (modelo 65). O corpo é o mesmo. */
public static JsonNode inutilizar(String tipo, String serie, String numeroInicial,
String numeroFinal, String justificativa) throws Exception {
FiscalHelpers.validarMotivo(justificativa); // mesma regra: 15 a 255 caracteres
JsonNode pedido = MyseApi.call("POST", "/" + tipo + "/inutilizacao", Map.of(
"serie", serie,
"numero-inicial", numeroInicial,
"numero-final", numeroFinal, // igual ao inicial para um número só
"justificativa", justificativa
// "ano", "2025": informe quando a numeração foi gerada em outro ano
));
if (!"001".equals(pedido.path("status").asText())) {
// 400: recusado na hora (número autorizado na faixa, faixa já na fila, certificado A3...)
throw new RuntimeException(pedido.path("data").path("erro").asText(pedido.path("descricao").asText()));
}
JsonNode resultado = FiscalHelpers.aguardarRecibo("/" + tipo + "/inutilizacao",
pedido.path("data").path("recibo").asText());
JsonNode sefaz = resultado.path("data").path("sefaz");
if (!"004".equals(resultado.path("status").asText())) {
// 900: a SEFAZ recusou (ex.: 241 = número já usado)
throw new RuntimeException("Inutilização recusada: " + sefaz.path("codigo").asText()
+ " " + sefaz.path("mensagem").asText());
}
return sefaz; // codigo 102 e protocolo da homologação
}

XML em lote por período

Pede o ZIP com os XMLs de NF-e ou NFC-e de um período (até 92 dias), consulta o protocolo e baixa o arquivo do link temporário. Veja Baixar XMLs por período.

/** Devolve o caminho do ZIP, ou null quando não havia nota no período. */
public static Path baixarXmlPeriodo(String tipo, String dataInicial, String dataFinal, Path destino)
throws Exception {
JsonNode pedido = MyseApi.call("POST", "/xml/solicitacao", Map.of(
"tipo", tipo, // "NFe" ou "NFCe"
"data-inicial", dataInicial, // AAAA-MM-DD
"data-final", dataFinal,
"email", "[email protected]"
));
String st = pedido.path("status").asText();
if (!"001".equals(st) && !"050".equals(st)) { // 050 = já havia uma solicitação igual em andamento
throw new RuntimeException(pedido.path("data").path("erro").asText(pedido.path("descricao").asText()));
}
String protocolo = pedido.path("data").path("protocolo").asText();
// Os status aqui não são os da nota: 005 pronto; 006 (sem notas) e 007 (falha) são finais
long wait = 2000;
long limite = System.currentTimeMillis() + 15 * 60_000L;
while (System.currentTimeMillis() < limite) {
Thread.sleep(wait);
JsonNode consulta = MyseApi.call("GET", "/xml/solicitacao/" + protocolo, null);
switch (consulta.path("status").asText()) {
case "002":
break; // processando
case "005": {
// Link temporário: só GET e SEM o header Authorization
URI url = URI.create(consulta.path("data").path("url-download").asText());
HttpResponse<Path> zip = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(url).GET().build(),
HttpResponse.BodyHandlers.ofFile(destino));
if (zip.statusCode() != 200) {
throw new RuntimeException("Download falhou: HTTP " + zip.statusCode());
}
return zip.body();
}
case "006":
return null;
default: // 007 falha (faça nova solicitação), 500 protocolo inexistente
throw new RuntimeException("Solicitação " + protocolo + ": "
+ consulta.path("descricao").asText());
}
wait = Math.min((long) (wait * 1.5), 30_000L);
}
throw new RuntimeException("Timeout aguardando protocolo " + protocolo);
}

Resumo diário

Totais por dia de NF-e e NFC-e emitidas, canceladas e denegadas, mais as falhas de emissão, para conciliação. Veja Resumo diário de emissões.

JsonNode resumo = MyseApi.call("GET",
"/resumo?data-inicial=2026-08-01&data-final=2026-08-06", null);
for (JsonNode dia : resumo.path("data").path("dias")) { // dias sem movimento não aparecem
JsonNode nfe = dia.path("nfe");
// canceladas está DENTRO de emitidas: válidas = emitidas - canceladas (nunca some os dois)
int nfeValidas = nfe.path("emitidas").asInt() - nfe.path("canceladas").asInt();
System.out.printf("%s NF-e válidas=%d NFC-e emitidas=%d falhas NFC-e=%d%n",
dia.path("data").asText(), nfeValidas,
dia.path("nfce").path("emitidas").asInt(),
dia.path("falhas").path("nfce").asInt());
}
int falhasNoPeriodo = resumo.path("data").path("totais").path("falhas").asInt();

Classificação fiscal

Sugestão de NCM, CFOP, CST, alíquotas e IBS/CBS de um produto ou serviço, na mesma chamada (sem recibo). É uma sugestão: confira com o contador antes de emitir. Veja Classificação fiscal.

// Timeout com folga: 70 s no individual, 90 s no lote (o padrão do cliente é 30 s)
public static JsonNode classificar(Map<String, Object> produto) throws Exception {
JsonNode resp = MyseApi.call("POST", "/classificacao-fiscal", produto, Duration.ofSeconds(70));
if (!"005".equals(resp.path("status").asText())) {
// 400: corrija o campo indicado; repetir igual não resolve
throw new IllegalArgumentException(resp.path("descricao").asText()
+ " (campo: " + resp.path("data").path("campo").asText() + ")");
}
return resp.path("data").path("pacote"); // chaves do pacote em snake_case
}
// Uso
Map<String, Object> produto = new HashMap<>(Map.of(
"referencia", "SKU-NB15",
"nome", "NOTEBOOK 15 POLEGADAS 8GB RAM",
"ncm", "8471.30.12", // com o NCM a resposta é bem mais rápida
"documento", "nfe",
"destinatario", "contribuinte",
"destino", "interestadual"
));
JsonNode pacote = classificar(produto);
// Perguntas que só a empresa sabe: responda e reenvie o MESMO produto, com todas as respostas
Map<String, Object> respostas = new HashMap<>();
for (int rodada = 0; rodada < 3 && pacote.path("perguntas_pendentes").size() > 0; rodada++) {
for (JsonNode p : pacote.path("perguntas_pendentes")) {
respostas.put(p.path("id").asText(), perguntarAoUsuario(p)); // booleano, escolha ou texto
}
produto.put("respostas", respostas);
pacote = classificar(produto);
}
System.out.println("CFOP sugerido: " + pacote.path("icms").path("cfop").path("valor").asText());
// Lote: de 1 a 10 por chamada; cada item tem status próprio
JsonNode lote = MyseApi.call("POST", "/classificacao-fiscal/lote", Map.of("produtos", List.of(
Map.of("referencia", "SKU-1", "nome", "ARROZ BRANCO TIPO 1 5KG", "ncm", "1006.30.21", "documento", "nfce"),
Map.of("referencia", "SRV-1", "natureza", "servico", "nome", "CORTE DE CABELO MASCULINO")
)), Duration.ofSeconds(90));
for (JsonNode item : lote.path("data").path("resultados")) {
if ("005".equals(item.path("status").asText())) {
revisar(item.path("referencia").asText(), item.path("pacote"));
} else { // 400: corrija item.campo; 999: reenvie só este produto
System.out.println(item.path("referencia").asText() + ": " + item.path("descricao").asText());
}
}

Rotinas

Uma rotina emite a mesma NFS-e sozinha em cada data da agenda (mensalidade, aluguel, condomínio). Depois de ativa, ela emite nota fiscal sem ninguém olhando: confira antes de criar. Veja Rotinas de emissão automática.

// 1. Modelos e campos: o "nome" de cada campo é a chave a usar em "parametros"
JsonNode modelos = MyseApi.call("GET", "/rotinas/modelos", null);
Map<String, Object> rotina = Map.of(
"modelo", "NFSE_RECORRENTE",
"nome", "Suporte mensal - ACME",
"periodicidade", "mensal",
"dia", 10,
"inicio", "2026-11-01",
// Exceção ao kebab-case: as chaves de parametros são os nomes do modelo (snake_case)
"parametros", Map.of(
"id_clifor", 1262804, // id de GET /rotinas/clientes?busca=
"id_produto", 88231, // id de GET /rotinas/servicos
"vl_servico", "3.500,50",
"ds_discriminacao", "Suporte técnico de {competencia}"
)
);
// 2. Conferir sem gravar
JsonNode conferida = MyseApi.call("POST", "/rotinas/validar", rotina);
if (!conferida.path("data").path("pode-ativar").asBoolean()) {
throw new IllegalStateException(conferida.path("descricao").asText() + " "
+ conferida.path("data").path("pendencias"));
}
// 3. Criar: sem "ativar", a rotina já sai ativa
JsonNode criada = MyseApi.call("POST", "/rotinas", rotina);
if (!"001".equals(criada.path("status").asText())) {
throw new IllegalStateException(criada.path("descricao").asText());
}
int id = criada.path("data").path("rotina").path("id-rotina").asInt();
// 4. A agenda não emite o mês da criação se o dia já passou: emita agora
JsonNode agora = MyseApi.call("POST", "/rotinas/" + id + "/emitir-agora",
Map.of("competencia", "2026-11"));
if (!"001".equals(agora.path("status").asText())) {
throw new IllegalStateException(agora.path("descricao").asText()); // ex.: competência já processada
}
// 5. Histórico: "Enviada para emissão" não é "autorizada"; o desfecho sai no recibo da NFS-e
JsonNode execucoes = MyseApi.call("GET", "/rotinas/" + id + "/execucoes", null);
for (JsonNode e : execucoes.path("data").path("execucoes")) {
if (!e.hasNonNull("recibo")) continue;
JsonNode nfse = FiscalHelpers.aguardarRecibo("/nfse/nota", e.path("recibo").asText());
System.out.println(e.path("competencia").asText() + ": " + nfse.path("status").asText());
}
// 6. Parar de emitir (só rotina ativa; retome com POST /rotinas/{id}/retomar)
MyseApi.call("POST", "/rotinas/" + id + "/pausar", null);
// Detalhe: agenda, pendências e o diagnóstico (por que emitiu ou não). 005; 500 = não encontrada
JsonNode det = MyseApi.call("GET", "/rotinas/" + id, null).path("data").path("rotina");
System.out.println(det.path("situacao").asText() + " | próxima: " + det.path("proxima-emissao").asText()
+ " | " + det.path("diagnostico").asText());
// Alterar: todos os campos opcionais, parcial nos parâmetros (o que não vier fica como estava).
// Em rotina PAUSADA, alterar não a religa (mande "ativar": true ou use /retomar).
JsonNode alterada = MyseApi.call("PUT", "/rotinas/" + id, Map.of(
"dia", 5,
"parametros", Map.of("vl_servico", 3800)
));
if (!"001".equals(alterada.path("status").asText())) { // 400: data.campo e/ou data.pendencias
throw new IllegalStateException(alterada.path("descricao").asText() + " " + alterada.path("data").path("campo").asText());
}
// Valor extra num mês: soma à nota e ao boleto só daquela competência (rotina ativa,
// próximos meses da agenda). Os meses possíveis vêm em competencias-disponiveis.
JsonNode extras = MyseApi.call("GET", "/rotinas/" + id + "/extras", null).path("data");
System.out.println("Meses possíveis: " + extras.path("competencias-disponiveis"));
JsonNode extra = MyseApi.call("PUT", "/rotinas/" + id + "/extras/2026-12", Map.of(
"valor", 250,
"motivo", "Visita técnica extra em 02/12" // 3 a 100 caracteres; aparece na nota
));
if (!"001".equals(extra.path("status").asText())) { // 400: modelo sem extra (ex.: condomínio), mês fechado
throw new IllegalStateException(extra.path("descricao").asText());
}
// Remover o extra (não vale para mês já emitido ou em emissão)
MyseApi.call("DELETE", "/rotinas/" + id + "/extras/2026-12", null);
// Excluir a rotina: 001 "Rotina excluída."
JsonNode excluida = MyseApi.call("DELETE", "/rotinas/" + id, null);

Certificado digital A1

Instala o .pfx da empresa e acompanha a validade, sem passar pela tela do FazNota. Responde na hora, sem recibo. Desde a 3.20.0. Veja Certificado digital A1.

Terminal window
export MYSE_PFX_SENHA="senha_do_pfx"
public static JsonNode instalarCertificadoA1(Path pfx) throws Exception {
String arquivo = Base64.getEncoder().encodeToString(Files.readAllBytes(pfx));
// A senha vem do ambiente (ou de um cofre). NUNCA registre em log a senha, o arquivo
// ou o corpo desta requisição: com os dois, qualquer um assina em nome da empresa.
String senha = Objects.requireNonNull(System.getenv("MYSE_PFX_SENHA"), "defina MYSE_PFX_SENHA");
JsonNode resp = MyseApi.call("POST", "/certificado/a1", Map.of("arquivo", arquivo, "senha", senha));
if (!"001".equals(resp.path("status").asText())) {
// 400: senha errada, não é ICP-Brasil, vencido, de outro CNPJ, vence antes do atual...
throw new IllegalStateException(resp.path("descricao").asText());
}
return resp.path("data"); // situacao, valido-ate, dias-para-vencer
}
// Monitoramento diário da validade
JsonNode cert = MyseApi.call("GET", "/certificado", null).path("data");
String situacao = cert.path("situacao").asText(); // VALIDO, A_VENCER, VENCIDO, NAO_INSTALADO, INDISPONIVEL
if ("A_VENCER".equals(situacao) || "VENCIDO".equals(situacao)) {
avisarCliente("Certificado vence em " + cert.path("dias-para-vencer").asInt()
+ " dias (" + cert.path("dt-validade").asText() + ")");
}

CIOT

Declara na ANTT a operação de transporte e devolve o código do CIOT. É para ETC com RNTRC ativo e certificado A1. Veja Emitir CIOT.

public static JsonNode emitirCiot(String numeroViagem) throws Exception {
// Os campos seguem o leiaute PEF da ANTT (PascalCase), não o kebab-case da v3
Map<String, Object> body = new HashMap<>();
body.put("numero-origem", numeroViagem); // estável por viagem: o reenvio devolve o recibo original
body.put("TipoOperacao", 1); // 1 carga lotação, 2 carga fracionada
body.put("CpfCnpjContratante", "12345678000199");
body.put("CpfCnpjDestinatario", "98765432000155");
body.put("ValorFrete", 1500.00);
body.put("Veiculos", List.of(Map.of("Placa", "ABC1D23", "NumeroEixos", "4")));
body.put("OrigemDestino", List.of(Map.of(
"Origem", Map.of("CodigoMunicipioOrigem", 4127700),
"Destino", Map.of("CodigoMunicipioDestino", 4104808),
"DistanciaPercorrida", 45
)));
body.put("DadosCarga", Map.of("CodigoNaturezaCarga", 9999, "CodigoTipoCarga", 5, "PesoCarga", 1000));
body.put("InfIndicadoresOperacionais", Map.of(
"IndAltoDesempenho", false, "IndRetornoVazio", false, "ComposicaoVeicular", false));
body.put("InfPagamento", List.of(Map.of(
"TipoPagamento", 6, "IndPagamento", 0, // Pix, à vista
"ChavePix", "[email protected]",
"IdentificadorPix", "FRETE-2026-1021"
)));
JsonNode pedido = MyseApi.call("POST", "/ciot/emissao", body);
if (!"001".equals(pedido.path("status").asText())) { // 400: A3, sem RNTRC, TipoOperacao inválido...
throw new RuntimeException(pedido.path("data").path("erro").asText(pedido.path("descricao").asText()));
}
// Se der 999 (falha com a ANTT), reenvie com o MESMO numero-origem: não gera um segundo CIOT
JsonNode resultado = FiscalHelpers.aguardarRecibo("/ciot", pedido.path("data").path("recibo").asText());
if (!"004".equals(resultado.path("status").asText())) { // 900: motivo em data.erro ou data.antt
throw new RuntimeException("CIOT recusado: " + resultado.path("data"));
}
return resultado.path("data"); // ciot, codigo-verificador, protocolo, situacao
}
// Encerrar ao fim da viagem (pelo código do CIOT ou pelo recibo da emissão)
JsonNode enc = MyseApi.call("POST", "/ciot/encerramento", Map.of("ciot", "123456789012"));
JsonNode encerrado = FiscalHelpers.aguardarRecibo("/ciot", enc.path("data").path("recibo").asText());
// Retificar: só carga FRACIONADA (TipoOperacao 2); lotação não admite (cancele e emita outro).
// Informe ao menos um campo; CodigoMunicipioOrigem e CodigoMunicipioDestino vão juntos.
JsonNode ret = MyseApi.call("POST", "/ciot/retificacao", Map.of(
"ciot", "123456789012",
"ValorFrete", 1650.00,
"PesoCarga", 1200
));
JsonNode retificado = FiscalHelpers.aguardarRecibo("/ciot", ret.path("data").path("recibo").asText()); // 004
// Cancelar (por "ciot" ou "recibo" da emissão). motivo obrigatório, até 500 caracteres.
// CIOT REJEITADO pela ANTT só é marcado como cancelado no FazNota, sem chamar a ANTT.
JsonNode canc = MyseApi.call("POST", "/ciot/cancelamento", Map.of(
"ciot", "123456789012",
"motivo", "Viagem cancelada pelo contratante."
));
JsonNode cancelado = FiscalHelpers.aguardarRecibo("/ciot", canc.path("data").path("recibo").asText());
if (!"010".equals(cancelado.path("status").asText())) {
throw new RuntimeException("Cancelamento recusado: " + cancelado.path("data").path("erro").asText());
}

RENAVE

Registra no RENAVE (SERPRO) a entrada e a saída de veículos do estoque da revenda, vinculadas à NF-e da operação. Veja RENAVE.

public static String entradaRenave(String chaveNFe) throws Exception {
// Os campos do RENAVE são camelCase (chaveNFe, valorCompra), não kebab-case
Map<String, Object> veiculo = Map.of(
"placa", "ABC1D23",
"numeroCrv", "123456789012",
"renavam", "01234567890",
"codigoSegurancaCrv", "12345678901",
"tipoCrv", "DIGITAL",
"dataHoraMedicaoHodometro", "2026-10-20T10:00:00",
"quilometragemHodometro", 52000,
"documentoProprietarioAtual", "98765432100",
"tipoDocumentoProprietarioAtual", "CPF"
);
JsonNode pedido = MyseApi.call("POST", "/renave/nota-fiscal/entrada", Map.of(
"chaveNFe", chaveNFe, // NF-e modelo 55 de entrada, emitida pela própria empresa
"cpfOperadorResponsavel", "12345678901",
"dataCompra", "2026-10-20",
"valorCompra", 45000.00,
"emailVendedor", "[email protected]",
"veiculo", veiculo
));
if (!"001".equals(pedido.path("status").asText())) { // 400: campo fora da regra, sem A1...
throw new RuntimeException(pedido.path("data").path("erro").asText(pedido.path("descricao").asText()));
}
JsonNode resultado = FiscalHelpers.aguardarRecibo("/renave", pedido.path("data").path("recibo").asText());
if (!"004".equals(resultado.path("status").asText())) { // 900: motivo em data.mensagem ou data.erro
throw new RuntimeException("RENAVE recusou: " + motivoRenave(resultado));
}
// Guarde o id-renave: ele identifica o registro no cancelamento
return resultado.path("data").path("id-renave").asText();
}
/**
* A resposta do RENAVE traz dados pessoais (CPF, endereço do comprador): nunca registre o
* "data" inteiro em log nem em exceção. Leia só o motivo.
*/
static String motivoRenave(JsonNode resp) {
JsonNode d = resp.path("data");
return resp.path("status").asText() + " " + d.path("mensagem").asText(d.path("erro").asText(""));
}
/** Envia, confere o 001 e aguarda o desfecho em GET /renave/{recibo}. */
static JsonNode operacaoRenave(String path, Map<String, ?> body) throws Exception {
JsonNode pedido = MyseApi.call("POST", path, body);
if (!"001".equals(pedido.path("status").asText())) { // 400: recusado na hora
throw new RuntimeException(pedido.path("data").path("erro").asText(pedido.path("descricao").asText()));
}
// 004 registrado · 010 cancelado · 900 recusado · 999 erro técnico (reenvie o MESMO pedido)
return FiscalHelpers.aguardarRecibo("/renave", pedido.path("data").path("recibo").asText());
}
// Saída do estoque (venda), vinculada à NF-e de venda modelo 55
JsonNode saida = operacaoRenave("/renave/nota-fiscal/saida", Map.of(
"chaveNFe", "35261012345678000190550010000012351000012356",
"cpfOperadorResponsavel", "12345678901",
"dataVenda", "2026-10-25",
"valorVenda", 52000.00,
"veiculo", Map.of("placa", "ABC1D23", "numeroCrv", "123456789012", "renavam", "01234567890"),
"comprador", Map.of(
"nome", "Maria Souza",
"email", "[email protected]",
"tipoDocumento", "CPF",
"numeroDocumento", "98765432100",
"endereco", Map.of(
"logradouro", "Av. Paulista", "numero", "1000", "bairro", "Bela Vista",
"cep", "01310100", "municipio", "São Paulo", "uf", "SP")
)
));
String idRenaveSaida = saida.path("data").path("id-renave").asText();
// Entrada de veículo PRÓPRIO (sem compra). A chaveNFe identifica o movimento no FazNota e não
// vai ao SERPRO. Aqui codigoSegurancaCrv, tipoCrv e o hodômetro também são obrigatórios.
Map<String, Object> veiculoProprio = new HashMap<>();
veiculoProprio.put("placa", "DEF4G56");
veiculoProprio.put("numeroCrv", "223456789012");
veiculoProprio.put("renavam", "11234567890");
veiculoProprio.put("codigoSegurancaCrv", "22345678901");
veiculoProprio.put("tipoCrv", "DIGITAL");
veiculoProprio.put("dataHoraMedicaoHodometro", "2026-10-20T09:00:00");
veiculoProprio.put("quilometragemHodometro", 18000);
JsonNode proprio = operacaoRenave("/renave/estoque/entrada-veiculo-proprio", Map.of(
"chaveNFe", "35261012345678000190550010000012361000012367",
"cpfOperadorResponsavel", "12345678901",
"dataEntradaEstoque", "2026-10-20",
"veiculo", veiculoProprio
));
// Cancelar uma entrada (compra ou veículo próprio) ou uma saída registrada com sucesso.
// Identifique por "id-renave" OU pelo "recibo" do registro; os dados do veículo vêm do registro.
JsonNode cancEntrada = operacaoRenave("/renave/estoque/cancelamento-entrada",
Map.of("id-renave", proprio.path("data").path("id-renave").asText()));
JsonNode cancSaida = operacaoRenave("/renave/estoque/cancelamento-saida",
Map.of("id-renave", idRenaveSaida));
if (!"010".equals(cancSaida.path("status").asText())) {
throw new RuntimeException("Cancelamento recusado: " + motivoRenave(cancSaida));
}

Listar com paginação

public static List<JsonNode> listarTodosClientes() throws Exception {
List<JsonNode> todos = new ArrayList<>();
int page = 1;
int pageSize = 100;
while (true) {
JsonNode resp = MyseApi.call("GET",
"/clientes?page=" + page + "&page_size=" + pageSize, null);
if (!"005".equals(resp.path("status").asText())) break;
JsonNode data = resp.path("data");
if (!data.isArray() || data.size() == 0) break;
data.forEach(todos::add);
if (data.size() < pageSize) break;
page++;
Thread.sleep(200);
}
return todos;
}

Tratamento de erros

try {
JsonNode nfce = EmissorNFCe.emitir(pedido);
System.out.println("NFCe emitida: " + nfce.path("sefaz").path("chave").asText());
} catch (MyseApi.ApiError e) {
logger.error("API error: status={} requestId={} msg={}",
e.httpStatus, e.requestId, e.getMessage());
throw e;
}

Health check (sem autenticação)

HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(BASE + "/health"))
.timeout(Duration.ofSeconds(5))
.build();
HttpResponse<String> res = CLIENT.send(req, HttpResponse.BodyHandlers.ofString());
JsonNode health = new ObjectMapper().readTree(res.body());
// { "status": "ok", "database": "ok", "timestamp": "..." }
// Profundo: SELECT 1 no banco + pool de conexões. 200 = UP; 503 = banco falhou ou pool saturado
HttpResponse<String> deep = CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create(BASE + "/health/deep")).timeout(Duration.ofSeconds(5)).build(),
HttpResponse.BodyHandlers.ofString());
JsonNode d = new ObjectMapper().readTree(deep.body());
boolean saudavel = deep.statusCode() == 200 && "UP".equals(d.path("status").asText());
// d.db.ok, d.db.latency_ms, d.pool.active/idle/waiting/total/max, d.total_ms
// Só as métricas do pool, sem tocar no banco (sempre 200; status STARTING enquanto inicializa)
HttpResponse<String> pool = CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create(BASE + "/health/pool")).timeout(Duration.ofSeconds(5)).build(),
HttpResponse.BodyHandlers.ofString());
JsonNode p = new ObjectMapper().readTree(pool.body()).path("pool");
System.out.printf("ativas=%d ociosas=%d esperando=%d max=%d%n",
p.path("active").asInt(), p.path("idle").asInt(), p.path("waiting").asInt(), p.path("max").asInt());

Alterar nota antes da emissão (PUT)

Disponível em NF-e (/nfe/{id}), NFC-e (/nfce/{id}) e NFS-e (/nfse/{id}). Só funciona enquanto a nota ainda não foi submetida para emissão.

public static JsonNode alterarNota(String tipo, String id, Map<String, ?> dados) throws Exception {
// tipo: "nfe" | "nfce" | "nfse"
return MyseApi.call("PUT", "/" + tipo + "/" + id, dados);
}
// Uso:
alterarNota("nfe", "12345", Map.of(
"serie", "1",
"cfop", "5102",
"cliente", "12345678000199",
"itens", List.of(Map.of(
"produto", "SKU-001", "quantidade", "3", "valor-unitario", "89.90"
))
));

Listagens

JsonNode nfes = MyseApi.call("GET", "/nfe?page=1&page_size=20", null);
JsonNode nfces = MyseApi.call("GET", "/nfce?page=1&page_size=50", null);
JsonNode nfses = MyseApi.call("GET", "/nfse?dataInicial=2026-05-01&page=1&page_size=20", null);
JsonNode fornecedor = MyseApi.call("GET", "/nffornecedor?page=1&page_size=20", null);
// Forma legada (path-based)
JsonNode nfesLegado = MyseApi.call("GET", "/nfe/paginacao/1/20", null);

Clientes (CRUD completo)

public static JsonNode cadastrarPF(PessoaFisica pf) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("tipo", "F");
body.put("nome", pf.getNome());
body.put("cpf", pf.getCpf());
body.put("rg", pf.getRg());
body.put("consumidor-final", "1");
body.put("contato", Map.of(
"email", pf.getEmail(),
"telefone", pf.getTelefone()
));
body.put("endereco", pf.getEndereco());
return MyseApi.call("POST", "/clientes", body);
}
public static JsonNode cadastrarPJ(PessoaJuridica pj) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("tipo", "J");
body.put("razao-social", pj.getRazaoSocial());
body.put("nome-fantasia", pj.getNomeFantasia());
body.put("cnpj", pj.getCnpj());
body.put("inscricao-municipal", pj.getInscricaoMunicipal());
body.put("tipo-inscricao-estadual", pj.getContribuinte() != null ? pj.getContribuinte() : "9");
body.put("inscricao-estadual", pj.getInscricaoEstadual() != null ? pj.getInscricaoEstadual() : "ISENTO");
body.put("consumidor-final", "0");
body.put("contato", Map.of(
"email", pj.getEmail(),
"telefone", pj.getTelefone()
));
body.put("endereco", pj.getEndereco());
return MyseApi.call("POST", "/clientes", body);
}
// Consultar por CPF/CNPJ
JsonNode cliente = MyseApi.call("GET", "/clientes/12345678000199", null);
// Buscar por nome
JsonNode encontrados = MyseApi.call("GET", "/clientes/busca/exemplo", null);
JsonNode top = MyseApi.call("GET", "/clientes/busca/top_clientes", null);
// Atualizar
MyseApi.call("PUT", "/clientes/12345678000199", Map.of(
"tipo", "J",
"razao-social", "Empresa Exemplo (Novo Nome) Ltda"
));
// Excluir
MyseApi.call("DELETE", "/clientes/12345678000199", null);

Produtos (CRUD completo)

public static JsonNode cadastrarProduto(Produto p) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("referencia", p.getSku());
body.put("nome", p.getNome());
body.put("valor", String.valueOf(p.getValor()));
body.put("medida", p.getMedida() != null ? p.getMedida() : "UN");
body.put("categoria", p.getCategoria());
body.put("ncm", p.getNcm());
body.put("origem", p.getOrigem() != null ? p.getOrigem() : "0");
body.put("cfop-preferencial", p.getCfop() != null ? p.getCfop() : "5102");
body.put("tipo-produto", "P");
if (p.getConfiguracoesFiscais() != null) {
body.put("configuracoes-fiscais", p.getConfiguracoesFiscais());
}
return MyseApi.call("POST", "/produtos", body);
}
public static JsonNode cadastrarServico(Servico s) throws Exception {
return MyseApi.call("POST", "/produtos", Map.of(
"referencia", s.getSku(),
"nome", s.getNome(),
"valor", String.valueOf(s.getValor()),
"medida", "H",
"tipo-produto", "S",
"codigo-servico", s.getCodigoServico()
));
}
// Consultar
JsonNode produto = MyseApi.call("GET", "/produtos/SKU-001", null);
JsonNode porNome = MyseApi.call("GET", "/produtos/nome/Camiseta", null);
// Listar paginado com busca (use _todos para não filtrar)
JsonNode todos = MyseApi.call("GET", "/produtos/paginacao/1/20/_todos", null);
JsonNode filtrados = MyseApi.call("GET", "/produtos/paginacao/1/20/Camiseta", null);
// Atualizar
MyseApi.call("PUT", "/produtos/SKU-001", Map.of(
"referencia", "SKU-001",
"nome", "Camiseta Polo M (Novo)",
"valor", "99.90"
));
// Excluir
MyseApi.call("DELETE", "/produtos/SKU-001", null);