Pular para o conteúdo principal

Exemplos JavaScript / Node.js

Os exemplos usam o fetch nativo do Node.js 18 ou mais novo, sem dependências.

Cliente​

// tesselys.js
const BASE_URL = process.env.TESSELYS_URL ?? 'https://erp-api.ideros.api.br/external/v1'

class TesselysClient {
constructor({ apiKey, secret }) {
this.apiKey = apiKey
this.secret = secret
this.accessToken = null
this.companyToken = null
this.expiresAt = 0
}

async authenticate() {
const res = await fetch(`${BASE_URL}/auth`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-api-key': this.apiKey },
body: JSON.stringify({ secret: this.secret }),
})
const body = await res.json()
if (!res.ok) throw new TesselysError(res.status, body)

this.accessToken = body.accessToken
this.companyToken = body.companyToken
// renova 30 segundos antes do vencimento informado
this.expiresAt = Date.now() + (body.expiresIn - 30) * 1000
}

async request(method, path, { query, body } = {}, tentativa = 0) {
if (!this.accessToken || Date.now() >= this.expiresAt) await this.authenticate()

const url = new URL(`${BASE_URL}${path}`)
for (const [key, value] of Object.entries(query ?? {})) {
url.searchParams.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value))
}

const res = await fetch(url, {
method,
headers: {
Authorization: `Bearer ${this.accessToken}`,
'x-company-token': this.companyToken,
...(body ? { 'Content-Type': 'application/json' } : {}),
},
body: body ? JSON.stringify(body) : undefined,
})

const text = await res.text()
const data = text ? JSON.parse(text) : null

// token ou sessão da empresa vencidos: autentica de novo e repete uma vez
const sessaoVencida =
res.status === 401 || (res.status === 403 && data?.code === 'COMPANY_SESSION_EXPIRED')
if (sessaoVencida && tentativa === 0) {
await this.authenticate()
return this.request(method, path, { query, body }, 1)
}

// limite de requisições: espera e tenta de novo
if (res.status === 429 && tentativa < 5) {
const retryAfter = Number(res.headers.get('retry-after'))
const espera = retryAfter > 0 ? retryAfter * 1000 : 2 ** tentativa * 1000
await new Promise((r) => setTimeout(r, espera + Math.random() * 500))
return this.request(method, path, { query, body }, tentativa + 1)
}

if (!res.ok) throw new TesselysError(res.status, data, res.headers.get('x-request-id'))
return data
}

list(resource, { page = 1, limit = 25, relations } = {}) {
return this.request('GET', `/${resource}`, {
query: { page, limit, ...(relations ? { relations } : {}) },
})
}

async *listAll(resource, { limit = 100, relations } = {}) {
let page = 1
while (true) {
const { items, meta } = await this.list(resource, { page, limit, relations })
yield* items
if (page >= meta.totalPages) return
page++
}
}

async get(resource, id) {
const data = await this.request('GET', `/${resource}/${id}`)
return data?.id ? data : null // {} significa "não encontrado"
}

create(resource, body) {
return this.request('POST', `/${resource}`, { body })
}

update(resource, id, body) {
return this.request('PUT', `/${resource}/${id}`, { body })
}
}

class TesselysError extends Error {
constructor(status, body, requestId) {
super(body?.friendlyMessage ?? `HTTP ${status}`)
this.status = status
this.code = body?.code
this.errors = body?.errors ?? []
this.requestId = requestId
}
}

module.exports = { TesselysClient, TesselysError }

Uso​

const { TesselysClient, TesselysError } = require('./tesselys')

const tesselys = new TesselysClient({
apiKey: process.env.TESSELYS_API_KEY,
secret: process.env.TESSELYS_SECRET,
})

async function main() {
// procura a pessoa pelo código do seu sistema; cria se não existir
const { items } = await tesselys.list('persons', {
relations: { where: { externalCode: 'ERP-000123' } },
})

const pessoa =
items[0] ??
(await tesselys.create('persons', {
personType: 'COMPANY',
name: 'Tech Solutions Tecnologia Ltda',
socialName: 'Tech Solutions',
documentNumber: '12345678000195',
genre: 'INDEFINITE',
classifications: ['CUSTOMER'],
externalCode: 'ERP-000123',
}))

// percorre todas as receitas do mês
for await (const lancamento of tesselys.listAll('financial-entries', {
relations: {
where: {
typeCategory: 'REVENUE',
originalDueDate: { gte: '2026-11-01', lte: '2026-11-30' },
},
},
})) {
console.log(lancamento.id, lancamento.title, lancamento.totalAmount)
}

// cria um negócio para a pessoa
const negocio = await tesselys.create('deals', {
title: 'Licença anual — Tech Solutions',
dealType: 'COMMERCIAL',
responsibleUserId: 'ID_DO_USUARIO',
customerId: pessoa.id,
isExternallyVisible: false,
isRenewal: false,
})
console.log('Negócio criado:', negocio.id)
}

main().catch((err) => {
if (err instanceof TesselysError) {
console.error(`[${err.status}] ${err.message}`, err.code ?? '', err.requestId ?? '')
} else {
console.error(err)
}
process.exit(1)
})

Recebendo webhooks​

Veja o exemplo com Express em Validação da assinatura.

Ainda com dúvida?

A nossa equipe ajuda você a configurar e usar esse recurso.