/** * Cliente da Central de Números WhatsApp (IAMAI) para TypeScript/JavaScript. * Funciona em Supabase Edge Functions (Deno), Node 18+, Bun, Cloudflare Workers e no backend do Lovable. * Só usa fetch e Web Crypto. Copie este arquivo para o projeto. * * Baixar/atualizar: curl -fsSL https://central-whatsapp.iamai.ia.br/sdk/typescript -o central-whatsapp-client.ts * Documentação: https://central-whatsapp.iamai.ia.br/llms.txt * * import { CentralWhatsApp, CentralErro, verificarAssinatura, interpretarWebhook } from "./central-whatsapp-client.ts"; * * const central = new CentralWhatsApp({ * urlBase: "https://central-whatsapp.iamai.ia.br", * chave: Deno.env.get("CENTRAL_API_KEY")!, * telefone: "+5511987650000", // número padrão que envia (ou numeroId) * }); * await central.enviarTexto("5511988887777", "Olá! Seu pedido saiu."); * await central.enviarTemplate("5511988887777", "pesquisa_satisfacao", { variaveis: ["Ana", "Pizzaria Bella"] }); * * // webhook recebido da Central (use o corpo BRUTO): * const corpo = await req.text(); * const ok = await verificarAssinatura(SEGREDO, corpo, req.headers.get("x-central-timestamp"), req.headers.get("x-central-signature")); * for (const evento of interpretarWebhook(corpo)) { ... } */ export const VERSAO = "1.0.0"; export class CentralErro extends Error { statusHttp: number; detalhe: string; codigoMeta: number | null; dados: unknown; constructor(statusHttp: number, detalhe: string, codigoMeta: number | null = null, dados: unknown = null) { super(`[${statusHttp}] ${detalhe}`); this.name = "CentralErro"; this.statusHttp = statusHttp; this.detalhe = detalhe; this.codigoMeta = codigoMeta; this.dados = dados; } /** A Meta recusou por estar fora da janela de 24 h: use um template. */ get foraDaJanela(): boolean { return this.codigoMeta === 131047; } } export interface OpcoesCentral { urlBase: string; chave: string; telefone?: string; numeroId?: string; timeoutMs?: number; fetch?: typeof fetch; } export interface Numero { numeroId?: string; telefone?: string; } type Json = Record; export class CentralWhatsApp { urlBase: string; chave: string; telefone?: string; numeroId?: string; timeoutMs: number; private fetcher: typeof fetch; constructor(opcoes: OpcoesCentral) { if (!opcoes.chave) throw new Error("Informe a chave do projeto (X-Internal-Api-Key)."); this.urlBase = opcoes.urlBase.replace(/\/+$/, ""); this.chave = opcoes.chave; this.telefone = opcoes.telefone; this.numeroId = opcoes.numeroId; this.timeoutMs = opcoes.timeoutMs ?? 30000; this.fetcher = opcoes.fetch ?? fetch; } // ------------------------------------------------------------------ infraestrutura private async requisitar(metodo: string, caminho: string, corpo?: unknown, params?: Record): Promise { const url = new URL(this.urlBase + caminho); for (const [k, v] of Object.entries(params ?? {})) if (v !== undefined && v !== null) url.searchParams.set(k, String(v)); const headers: Record = { "X-Internal-Api-Key": this.chave, Accept: "application/json" }; if (corpo !== undefined) headers["Content-Type"] = "application/json"; const controle = new AbortController(); const timer = setTimeout(() => controle.abort(), this.timeoutMs); let resp: Response; try { resp = await this.fetcher(url.toString(), { method: metodo, headers, body: corpo === undefined ? undefined : JSON.stringify(corpo), signal: controle.signal, }); } catch (erro) { throw new CentralErro(0, `Não consegui falar com a Central: ${(erro as Error).message}`); } finally { clearTimeout(timer); } const texto = await resp.text(); let dados: any = null; try { dados = texto ? JSON.parse(texto) : null; } catch { dados = { detail: texto.slice(0, 300) }; } if (!resp.ok) { let detalhe = dados?.detail ?? `HTTP ${resp.status}`; if (Array.isArray(detalhe)) detalhe = detalhe.map((d: any) => String(d.msg ?? d).replace("Value error, ", "")).join("; "); throw new CentralErro(resp.status, String(detalhe), dados?.meta?.codigo ?? null, dados); } return dados; } private numero(n?: Numero): Json { const numeroId = n?.numeroId ?? (n?.telefone ? undefined : this.numeroId); const telefone = n?.telefone ?? (numeroId ? undefined : this.telefone); if (!numeroId && !telefone) throw new Error("Informe numeroId ou telefone (ou um padrão no construtor)."); return numeroId ? { numero_id: numeroId } : { telefone }; } private ident(numero?: string): string { const valor = numero ?? this.numeroId ?? this.telefone; if (!valor) throw new Error("Informe o número (id ou telefone)."); return encodeURIComponent(valor); } // ------------------------------------------------------------------ identidade e números quemSouEu() { return this.requisitar("GET", "/api/eu"); } async listarNumeros(filtro: { status?: string; clienteId?: string } = {}) { return (await this.requisitar("GET", "/api/numeros", undefined, { status: filtro.status, cliente_id: filtro.clienteId })).conexoes; } obterNumero(numero?: string) { return this.requisitar("GET", `/api/numeros/${this.ident(numero)}`); } solicitarNumero(dados: { origem?: "salvy_api" | "chip_proprio"; clienteId?: string; telefone?: string; ddd?: number; webhookDestinoUrl?: string; clienteNome?: string; clienteEmail?: string }) { return this.requisitar("POST", "/api/numeros/solicitar", { origem_linha: dados.origem ?? "salvy_api", cliente_id: dados.clienteId ?? "interno", telefone: dados.telefone, ddd: dados.ddd, webhook_destino_url: dados.webhookDestinoUrl, cliente_nome: dados.clienteNome, cliente_email: dados.clienteEmail, }); } acompanharConexao(numero: string) { return this.requisitar("GET", `/api/numeros/${this.ident(numero)}/sms`); } linkConexao(numero: string, reaproveitar = true) { return this.requisitar("POST", `/api/numeros/${this.ident(numero)}/link-conexao`, undefined, { reaproveitar }); } reconectar(numero?: string, modo: "reconectar" | "conectar" = "reconectar") { return this.requisitar("POST", `/api/numeros/${this.ident(numero)}/reconectar`, { modo }); } pausar(numero: string) { return this.requisitar("POST", `/api/numeros/${this.ident(numero)}/pausar`); } reativar(numero: string) { return this.requisitar("POST", `/api/numeros/${this.ident(numero)}/reativar`); } cancelar(numero: string, opcoes: { cancelarLinhaSalvy?: boolean; desativarHookcloud?: boolean } = {}) { return this.requisitar("POST", `/api/numeros/${this.ident(numero)}/cancelar`, { cancelar_linha_salvy: !!opcoes.cancelarLinhaSalvy, desativar_hookcloud: !!opcoes.desativarHookcloud, }); } // ------------------------------------------------------------------ mensagens enviar(para: string, tipo: string, campos: Json = {}, numero?: Numero) { return this.requisitar("POST", "/api/mensagens/enviar", { ...this.numero(numero), para, tipo, ...campos }); } enviarTexto(para: string, texto: string, numero?: Numero) { return this.enviar(para, "texto", { texto }, numero); } enviarTemplate(para: string, nome: string, opcoes: { idioma?: string; variaveis?: string[]; variaveisCabecalho?: string[]; cabecalhoMidia?: { tipo: "imagem" | "video" | "documento"; url: string; nome_arquivo?: string }; botoes?: { indice: number; tipo?: "url" | "quick_reply" | "copy_code"; valor: string }[] } = {}, numero?: Numero) { return this.enviar(para, "template", { template: { nome, idioma: opcoes.idioma ?? "pt_BR", variaveis: opcoes.variaveis ?? [], variaveis_cabecalho: opcoes.variaveisCabecalho ?? [], cabecalho_midia: opcoes.cabecalhoMidia, botoes: opcoes.botoes ?? [], } }, numero); } enviarBotoes(para: string, texto: string, botoes: (string | { id?: string; titulo: string })[], extras: { cabecalho?: string; rodape?: string } = {}, numero?: Numero) { return this.enviar(para, "botoes", { texto, ...extras, botoes: botoes.map((b) => (typeof b === "string" ? { titulo: b } : b)) }, numero); } enviarLista(para: string, texto: string, opcoes: (string | { id?: string; titulo: string; descricao?: string })[], botao = "Ver opções", numero?: Numero) { const linhas = opcoes.map((o) => (typeof o === "string" ? { titulo: o } : o)); return this.enviar(para, "lista", { texto, lista: { botao, secoes: [{ linhas }] } }, numero); } enviarMidia(para: string, url: string, tipo: "imagem" | "video" | "documento" | "audio" | "figurinha" = "imagem", legenda?: string, numero?: Numero) { return this.enviar(para, tipo, { midia: { url, legenda } }, numero); } enviarReacao(para: string, mensagemId: string, emoji: string, numero?: Numero) { return this.enviar(para, "reacao", { mensagem_id: mensagemId, emoji }, numero); } marcarLida(mensagemId: string, digitando = false, numero?: Numero) { return this.requisitar("POST", "/api/mensagens/marcar-lida", { ...this.numero(numero), mensagem_id: mensagemId, digitando }); } async baixarMidia(mediaId: string, numero?: Numero): Promise<{ dados: ArrayBuffer; tipo: string }> { const url = new URL(`${this.urlBase}/api/midia/${encodeURIComponent(mediaId)}`); url.searchParams.set("baixar", "true"); if (numero?.numeroId) url.searchParams.set("numero_id", numero.numeroId); if (numero?.telefone) url.searchParams.set("telefone", numero.telefone); const resp = await this.fetcher(url.toString(), { headers: { "X-Internal-Api-Key": this.chave } }); if (!resp.ok) { const dados: any = await resp.json().catch(() => ({})); throw new CentralErro(resp.status, String(dados?.detail ?? `HTTP ${resp.status}`), dados?.meta?.codigo ?? null, dados); } return { dados: await resp.arrayBuffer(), tipo: resp.headers.get("content-type") ?? "application/octet-stream" }; } historico(numero?: string, contato?: string, limite = 50) { return this.requisitar("GET", `/api/numeros/${this.ident(numero)}/mensagens`, undefined, { contato, limite }); } async conversas(numero?: string, busca?: string) { return (await this.requisitar("GET", `/api/numeros/${this.ident(numero)}/conversas`, undefined, { busca })).conversas; } // ------------------------------------------------------------------ templates, perfil e saúde async listarTemplates(numero?: string) { return (await this.requisitar("GET", `/api/numeros/${this.ident(numero)}/templates`)).templates; } criarTemplate(dados: { nome: string; corpo: string; categoria?: string; idioma?: string; exemplos?: string[]; cabecalho?: string; rodape?: string; respostasRapidas?: string[] }, numero?: string) { return this.requisitar("POST", `/api/numeros/${this.ident(numero)}/templates`, { nome: dados.nome, corpo: dados.corpo, categoria: dados.categoria ?? "UTILITY", idioma: dados.idioma ?? "pt_BR", exemplos: dados.exemplos ?? [], cabecalho: dados.cabecalho, rodape: dados.rodape, botoes: (dados.respostasRapidas ?? []).map((texto) => ({ tipo: "QUICK_REPLY", texto })), }); } apagarTemplate(nome: string, numero?: string) { return this.requisitar("DELETE", `/api/numeros/${this.ident(numero)}/templates/${nome}`); } perfil(numero?: string) { return this.requisitar("GET", `/api/numeros/${this.ident(numero)}/perfil`); } atualizarPerfil(campos: { sobre?: string; descricao?: string; endereco?: string; email?: string; sites?: string[]; categoria?: string }, numero?: string) { return this.requisitar("PATCH", `/api/numeros/${this.ident(numero)}/perfil`, campos); } saude(numero?: string, sincronizar = false) { return this.requisitar("GET", `/api/numeros/${this.ident(numero)}/saude`, undefined, sincronizar ? { sincronizar: true } : undefined); } } // ============================================================================ webhook /** Confere X-Central-Signature = sha256=HMAC(segredo, "{timestamp}.{corpo}") e o relógio (±5 min). */ export async function verificarAssinatura(segredo: string, corpo: string, timestamp: string | null, assinatura: string | null, toleranciaSeg = 300): Promise { if (!segredo || !timestamp || !assinatura || !/^\d+$/.test(timestamp)) return false; if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranciaSeg) return false; const codificador = new TextEncoder(); const chave = await crypto.subtle.importKey("raw", codificador.encode(segredo), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const bytes = new Uint8Array(await crypto.subtle.sign("HMAC", chave, codificador.encode(`${timestamp}.${corpo}`))); const esperado = "sha256=" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); const recebido = assinatura.trim().toLowerCase(); if (recebido.length !== esperado.length) return false; let diferenca = 0; for (let i = 0; i < esperado.length; i++) diferenca |= recebido.charCodeAt(i) ^ esperado.charCodeAt(i); return diferenca === 0; } /** Lista simples de eventos: mensagem | status | meta | evento_admin (mesma regra do cliente Python). */ export function interpretarWebhook(corpo: string | Json): Json[] { const dados: any = typeof corpo === "string" ? JSON.parse(corpo) : corpo; if (!dados || typeof dados !== "object") return []; if (dados.object === "central_whatsapp") { const c = dados.conexao ?? {}; return [{ tipo: "evento_admin", evento: dados.evento, status: c.status, status_detalhe: c.status_detalhe, qualidade: c.qualidade, limite_mensagens: c.limite_mensagens, conexao: c, dados: dados.dados }]; } const eventos: Json[] = []; for (const entry of dados.entry ?? []) { for (const change of entry.changes ?? []) { const valor = change.value ?? {}; if (change.field !== "messages") { eventos.push({ tipo: "meta", campo: change.field, valor, waba_id: entry.id }); continue; } const pnid = valor.metadata?.phone_number_id; const nomes: Record = {}; for (const c of valor.contacts ?? []) nomes[c.wa_id] = c.profile?.name; for (const m of valor.messages ?? []) { const conteudo = typeof m[m.type] === "object" ? m[m.type] : {}; const resposta = m.interactive?.button_reply ?? m.interactive?.list_reply ?? {}; eventos.push({ tipo: "mensagem", phone_number_id: pnid, de: m.from, nome: nomes[m.from], wamid: m.id, tipo_mensagem: m.type, texto: m.text?.body ?? conteudo.caption ?? resposta.title ?? m.button?.text, midia_id: conteudo.id, resposta_id: resposta.id ?? m.button?.payload, bruto: m }); } for (const s of valor.statuses ?? []) { eventos.push({ tipo: "status", phone_number_id: pnid, wamid: s.id, status: s.status, para: s.recipient_id, erro: s.errors?.[0]?.title ?? null, bruto: s }); } } } return eventos; }