const axios = require(‘axios’);
const fs = require(‘fs’);
const path = require(‘path’);
const CLIENT_ID = ‘…’;
const CLIENT_SECRET = ‘…’;
const TOKEN_URL = ‘https://auth.nuvemfiscal.com.br/oauth/token’;
const BASE_URL = ‘https://api.nuvemfiscal.com.br’;
async function obterToken() {
try {
const response = await axios.post(
TOKEN_URL,
new URLSearchParams({
grant_type: ‘client_credentials’,
scope: ‘conta empresa nfse’
}),
{
auth: {
username: CLIENT_ID,
password: CLIENT_SECRET
},
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’
}
}
);
return response.data.access_token;
} catch (error) {
console.error(‘Erro ao obter token:’, error.response ? error.response.data : error.message);
throw new Error(‘Falha na autenticação’);
}
}
async function emitirNFe() {
try {
const token = await obterToken();
console.log(“Token obtido:”, token);
const response = await axios.post(
`${BASE_URL}/nfse/dps`,
{
"provedor": "padrao",
"ambiente": "homologacao",
"referencia": "NF-20250227-001",
"infDPS": {
"tpAmb": 2,
"dhEmi": "2025-02-27T12:00:00Z",
"verAplic": "1.0",
"dCompet": "2025-02-01",
"subst": {
"chSubstda": "12345678901234567890123456789012345678901234567890",
"cMotivo": "01",
"xMotivo": "Motivo explicativo da substituição"
},
"prest": {
"CNPJ": "54067133000104",
},
"toma": {
"orgaoPublico": false,
"CNPJ": "01141158000144",
"NIF": "12345",
"cNaoNIF": 0,
"CAEPF": "12345678901234",
"IM": "654321",
"xNome": "Cliente Exemplo LTDA",
"end": {
"endNac": {
"cMun": "3548807",
"CEP": "01001000"
},
"xLgr": "Rua Exemplo",
"nro": "500",
"xCpl": "Apto 202",
"xBairro": "Centro"
},
"fone": "11988888888",
"email": "financeiro@clienteexemplo.com"
},
"serv": {
"locPrest": {
"cLocPrestacao": "3548807",
"cPaisPrestacao": "BR"
},
"cServ": {
"cTribNac": "130500",
"cTribMun": "1305",
"CNAE": "1813-0/01",
"xDescServ": "Serviços gráficos e acabamentos",
"cNBS": "123456789"
}
},
"valores": {
"vServPrest": {
"vReceb": 4750,
"vServ": 5000
},
"trib": {
"tribMun": {
"tribISSQN": 1, // Ajustado para 1, 2, 3 ou 4
"cLocIncid": "3548807",
"cPaisResult": "BR",
"vBC": 5000,
"pAliq": 5,
"vISSQN": 250,
"tpRetISSQN": 1,
"vLiq": 4750
}
}
}
}
},
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json; charset=utf-8'
}
}
);
console.log('NFS-e emitida com sucesso:', response.data);
return response.data.id;
} catch (error) {
if (error.response) {
console.error('Erro ao emitir NFS-e:', error.response.status, JSON.stringify(error.response.data, null, 2));
} else {
console.error('Erro inesperado:', error.message);
}
}
}
async function baixarNFe(chave) {
if (!chave) {
console.error(‘Erro: ID da NFS-e não foi informado.’);
return;
}
try {
const token = await obterToken();
const response = await axios.get(${BASE_URL}/nfse/${chave}/pdf
, {
headers: {
‘Authorization’: Bearer ${token}
,
‘Content-Type’: ‘application/json; charset=utf-8’
},
responseType: ‘arraybuffer’ // Garante que o arquivo seja tratado corretamente
});
// Diretório onde o PDF será salvo
const pastaDestino = path.join(__dirname, 'nfse_pdfs');
// Criar a pasta se ela não existir
if (!fs.existsSync(pastaDestino)) {
fs.mkdirSync(pastaDestino, { recursive: true });
}
// Caminho do arquivo
const caminhoArquivo = path.join(pastaDestino, `${chave}.pdf`);
// Salvar o arquivo
fs.writeFileSync(caminhoArquivo, response.data);
console.log(`✅ NF-e baixada com sucesso: ${caminhoArquivo}`);
} catch (error) {
console.error('Erro ao baixar NF-e:', error.response ? error.response.data : error.message);
}
}
emitirNFe().then(id => {
if (id) {
setTimeout(() => baixarNFe(id), 5000); // Aguarda 5 segundos antes de baixar
}
});