npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@thyagodantas/whatsapp-cloud-api

v1.0.2

Published

Biblioteca Node.js para facilitar o uso da WhatsApp Cloud API

Readme

WhatsApp Cloud API - Biblioteca Node.js

Biblioteca Node.js para facilitar o uso da WhatsApp Cloud API da Meta.

📋 Características

  • ✅ Envio de mensagens de texto
  • ✅ Envio de imagens (com ou sem legenda)
  • ✅ Envio de vídeos (com ou sem legenda)
  • ✅ Envio de documentos (com ou sem legenda)
  • ✅ Envio de botões interativos (Reply Buttons)
  • ✅ Suporte a arquivos até 16MB
  • ✅ Webhook para receber mensagens
  • ✅ TypeScript definitions incluídas
  • ✅ Fácil configuração e uso

📦 Instalação

npm install @thyagodantas/whatsapp-cloud-api

🚀 Uso Rápido

Configuração Inicial

const { WhatsAppClient } = require('@thyagodantas/whatsapp-cloud-api');

const client = new WhatsAppClient({
  phoneNumberId: 'SEU_PHONE_NUMBER_ID',
  accessToken: 'SEU_ACCESS_TOKEN'
});

Enviar Mensagem de Texto

await client.sendText({
  to: '5511999999999',
  text: 'Olá! Esta é uma mensagem de teste.'
});

Enviar Imagem

// Com URL
await client.sendImage({
  to: '5511999999999',
  imageUrl: 'https://exemplo.com/imagem.jpg',
  caption: 'Legenda da imagem'
});

// Com arquivo local
await client.sendImage({
  to: '5511999999999',
  imagePath: './caminho/para/imagem.jpg',
  caption: 'Legenda da imagem'
});

Enviar Vídeo

// Com URL
await client.sendVideo({
  to: '5511999999999',
  videoUrl: 'https://exemplo.com/video.mp4',
  caption: 'Legenda do vídeo'
});

// Com arquivo local
await client.sendVideo({
  to: '5511999999999',
  videoPath: './caminho/para/video.mp4',
  caption: 'Legenda do vídeo'
});

Enviar Documento

// Com URL
await client.sendDocument({
  to: '5511999999999',
  documentUrl: 'https://exemplo.com/documento.pdf',
  caption: 'Documento importante',
  filename: 'documento.pdf'
});

// Com arquivo local
await client.sendDocument({
  to: '5511999999999',
  documentPath: './caminho/para/documento.pdf',
  caption: 'Documento importante',
  filename: 'documento.pdf'
});

Enviar Botões Interativos

// Botões simples
await client.sendButtons({
  to: '5511999999999',
  body: 'Escolha uma opção abaixo:',
  buttons: [
    { id: 'btn_sim', title: 'Sim' },
    { id: 'btn_nao', title: 'Não' },
    { id: 'btn_talvez', title: 'Talvez' }
  ]
});

// Botões com header e footer
await client.sendButtons({
  to: '5511999999999',
  header: '🎉 Promoção Especial',
  body: 'Gostaria de aproveitar nossa oferta exclusiva?',
  buttons: [
    { id: 'btn_aceitar', title: 'Aceitar Oferta' },
    { id: 'btn_recusar', title: 'Não, obrigado' }
  ],
  footer: 'Oferta válida por tempo limitado'
});

🔔 Webhook para Receber Mensagens

Configuração com Express

const express = require('express');
const { WebhookHandler } = require('@thyagodantas/whatsapp-cloud-api');

const app = express();

const webhookHandler = new WebhookHandler({
  verifyToken: 'SEU_VERIFY_TOKEN'
});

// Rota de verificação do webhook
app.get('/webhook', (req, res) => {
  webhookHandler.verify(req, res);
});

// Rota para receber mensagens
app.post('/webhook', express.json(), (req, res) => {
  webhookHandler.handle(req, res, (message) => {
    console.log('Mensagem recebida:', message);
    
    // Processar a mensagem aqui
    if (message.type === 'text') {
      console.log('Texto:', message.text.body);
    } else if (message.type === 'image') {
      console.log('Imagem ID:', message.image.id);
    }
  });
});

app.listen(3000, () => {
  console.log('Webhook rodando na porta 3000');
});

📚 API Reference

WhatsAppClient

Constructor

new WhatsAppClient(config)

Parâmetros:

  • config.phoneNumberId (string): ID do número de telefone do WhatsApp Business
  • config.accessToken (string): Token de acesso da API
  • config.apiVersion (string, opcional): Versão da API (padrão: 'v18.0')

Métodos

sendText(options)

Envia uma mensagem de texto.

Parâmetros:

  • options.to (string): Número do destinatário (formato internacional)
  • options.text (string): Texto da mensagem

Retorna: Promise

sendImage(options)

Envia uma imagem.

Parâmetros:

  • options.to (string): Número do destinatário
  • options.imageUrl (string, opcional): URL da imagem
  • options.imagePath (string, opcional): Caminho local da imagem
  • options.caption (string, opcional): Legenda da imagem

Retorna: Promise

sendVideo(options)

Envia um vídeo.

Parâmetros:

  • options.to (string): Número do destinatário
  • options.videoUrl (string, opcional): URL do vídeo
  • options.videoPath (string, opcional): Caminho local do vídeo
  • options.caption (string, opcional): Legenda do vídeo

Retorna: Promise

sendDocument(options)

Envia um documento.

Parâmetros:

  • options.to (string): Número do destinatário
  • options.documentUrl (string, opcional): URL do documento
  • options.documentPath (string, opcional): Caminho local do documento
  • options.caption (string, opcional): Legenda do documento
  • options.filename (string, opcional): Nome do arquivo

Retorna: Promise

sendButtons(options)

Envia botões interativos (Reply Buttons).

Parâmetros:

  • options.to (string): Número do destinatário
  • options.body (string): Texto principal da mensagem
  • options.buttons (Array): Array de botões (máximo 3)
    • buttons[].id (string): ID único do botão (máx 256 caracteres)
    • buttons[].title (string): Título do botão (máx 20 caracteres)
  • options.header (string, opcional): Texto do cabeçalho (máx 60 caracteres)
  • options.footer (string, opcional): Texto do rodapé (máx 60 caracteres)

Retorna: Promise

WebhookHandler

Constructor

new WebhookHandler(config)

Parâmetros:

  • config.verifyToken (string): Token de verificação do webhook

Métodos

verify(req, res)

Verifica o webhook durante a configuração.

handle(req, res, callback)

Processa mensagens recebidas.

Parâmetros:

  • req: Request do Express
  • res: Response do Express
  • callback: Função que recebe o objeto da mensagem

🔑 Obtendo Credenciais

  1. Acesse Facebook Developers
  2. Crie um app e adicione o produto WhatsApp
  3. Obtenha o Phone Number ID e o Access Token
  4. Configure o webhook com seu Verify Token

📝 Limitações

  • Tamanho máximo de arquivo: 16MB
  • Formatos suportados variam por tipo de mídia (consulte a documentação oficial)

🔗 Links Úteis

📄 Licença

MIT