@ominiflow/sdk
v1.0.0-rc.0
Published
Official TypeScript SDK for OmniFlow CPaaS platform
Downloads
61
Maintainers
Readme
@omniflow/sdk
SDK TypeScript oficial do OmniFlow CPaaS — envio de mensagens, gestão de conversas, contatos, caixas de entrada e webhooks com retry automático e tipagem completa.
Instalação
npm install @omniflow/sdk
# ou
bun add @omniflow/sdkQuick Start
import { OmniFlow } from '@omniflow/sdk';
const client = new OmniFlow({ apiKey: 'omf_live_...' });
// ou OAuth Client Credentials
const oauthClient = new OmniFlow({
oauth: {
clientId: 'client_123',
clientSecret: 'secret_123',
},
});
// Enviar uma mensagem de texto
const message = await client.messages.send({
to: '+5511999999999',
channel: 'whatsapp_official',
content: { type: 'text', text: 'Olá! Como posso ajudar?' },
});
console.log(message.id, message.conversationId);Configuração
const client = new OmniFlow({
apiKey: 'omf_live_...', // obrigatório
baseUrl: 'https://api.sua-instancia.com', // opcional — padrão: https://api.omniflow.com.br
timeout: 30_000, // ms — padrão: 30000
maxRetries: 3, // padrão: 3
});
const oauthClient = new OmniFlow({
oauth: {
clientId: 'client_123',
clientSecret: 'secret_123',
tokenPath: '/v1/oauth/token', // opcional
},
});Recursos
client.messages
// Enviar mensagem de texto
await client.messages.send({ to, channel, content: { type: 'text', text } });
// Enviar imagem
await client.messages.send({ to, channel, content: { type: 'image', url, caption } });
// Listar mensagens de uma conversa
const { data, nextCursor } = await client.messages.list(conversationId, { limit: 50 });
// Iterar por todas as mensagens via cursor
for await (const message of client.messages.listAll(conversationId, { limit: 100 })) {
console.log(message.id);
}client.conversations
// Listar conversas
const { data } = await client.conversations.list({ status: 'open', inboxId, limit: 25 });
// Iterar por todas as conversas abertas
for await (const conversation of client.conversations.listAll({ status: 'open', limit: 100 })) {
console.log(conversation.id);
}
// Buscar por ID
const conv = await client.conversations.get(id);
// Marcar como resolvida
await client.conversations.resolve(id);
// Atribuir a um agente
await client.conversations.assign(id, { agentId: 'agent-uuid' });
// Reabrir conversa resolvida
await client.conversations.reopen(id);client.contacts
// Criar contato
const contact = await client.contacts.create({ phoneNumber: '+5511999999999', name: 'Maria' });
// Buscar por ID
const contact = await client.contacts.get(id);
// Buscar por telefone
const contact = await client.contacts.findByPhone('+5511999999999'); // null se não encontradoclient.inboxes
// Listar caixas de entrada
const inboxes = await client.inboxes.list();client.templates
// Listar templates aprovados
const templates = await client.templates.list({ channel: 'whatsapp_official' });
// Enviar mensagem via template
await client.templates.send({
to: '+5511999999999',
channel: 'whatsapp_official',
templateId: 'boas_vindas_v1',
params: { nome: 'João', empresa: 'Acme' },
});client.webhooks
CRUD de endpoints
// Listar webhooks cadastrados
const webhooks = await client.webhooks.list();
// Criar webhook
const wh = await client.webhooks.create({
url: 'https://sua-api.com/omniflow/webhook',
events: ['message.received', 'conversation.created'],
secret: 'seu-segredo-aqui',
});
// Remover webhook
await client.webhooks.delete(wh.id);
// Histórico de entregas
const { data } = await client.webhooks.listDeliveries(wh.id, { limit: 20 });Verificação de assinatura
import { verifyWebhookSignature } from '@omniflow/sdk';
// Em seu servidor Express/Hono/Fastify:
app.post('/omniflow/webhook', async (req, res) => {
const rawBody = await req.text(); // leia o body como string bruta
const sig = req.headers['x-omniflow-signature-256'] ?? '';
const valid = await verifyWebhookSignature({
payload: rawBody,
signature: sig,
secret: process.env.WEBHOOK_SECRET!,
});
if (!valid) return res.status(401).send('Unauthorized');
const event = client.webhooks.parse(rawBody);
// event.type, event.tenantId, event.payload, event.timestamp
});Tratamento de Erros
import { OmniFlow, OmniFlowApiError } from '@omniflow/sdk';
try {
await client.messages.send({ ... });
} catch (err) {
if (err instanceof OmniFlowApiError) {
console.error(err.status); // HTTP status code (ex: 422, 429)
console.error(err.code); // código de erro da API (ex: "quota_exceeded")
console.error(err.requestId); // X-Request-Id para abertura de suporte
}
throw err;
}Retry automático
O SDK faz até 3 tentativas (configurável via maxRetries) com backoff exponencial:
| Situação | Comportamento |
|---|---|
| 429 Too Many Requests | Aguarda Retry-After (máx. 60s) e retenta |
| 5xx Server Error | Exponential backoff com jitter até o teto de 1s → 2s → 4s |
| 4xx Client Error | Lança OmniFlowApiError imediatamente (sem retry) |
| Timeout / rede | Exponential backoff com jitter até maxRetries |
Tipos Exportados
import type {
Channel,
ContactDto,
ConversationDto,
InboxDto,
MessageDto,
OmniFlowOpenApiPaths,
TemplateDto,
VerifyWebhookSignatureParams,
WebhookDto,
WebhookDeliveryDto,
WebhookEvent,
WebhookEventType,
// params
SendMessageParams,
SendTemplateParams,
CreateContactParams,
CreateWebhookParams,
AssignConversationParams,
// paginação
PaginatedResult,
} from '@omniflow/sdk';Eventos de Webhook
| Tipo | Payload |
|---|---|
| message.received | { messageId, conversationId, channel, direction } |
| conversation.created | { conversationId, contactId, inboxId } |
| conversation.resolved | { conversationId, resolvedBy } |
| contact.opted_out | { contactId, phoneNumber } |
Licença
MIT © OmniFlow Team
