WhatsApp API untuk Node.js: Tutorial Lengkap
Tutorial WhatsApp API dengan Node.js. Baileys, whatsapp-web.js, dan Cloud API. Contoh kode kirim pesan, terima pesan, auto-reply!
Node.js + WhatsApp API = Powerful combination!
JavaScript developer? Artikel ini untuk kamu.
Saya akan tunjukkan cara implementasi WhatsApp API dengan Node.js — dari setup sampai bot yang fully functional.
Library Options
Unofficial Libraries:
| Library | Stars | Multi-Device | Status |
|---|---|---|---|
| @whiskeysockets/baileys | 7k+ | ✅ | Aktif |
| whatsapp-web.js | 13k+ | ✅ | Aktif |
| venom-bot | 5k+ | ✅ | Aktif |
Official (Cloud API):
Tidak ada library khusus — gunakan axios atau node-fetch untuk HTTP requests.
Tutorial 1: Baileys (Unofficial)
Step 1: Setup Project
bash
mkdir wa-bot
cd wa-bot
npm init -y
npm install @whiskeysockets/baileys qrcode-terminalStep 2: Basic Connection
index.js:
javascript
const { default: makeWASocket,
DisconnectReason,
useMultiFileAuthState } = require('@whiskeysockets/baileys');
const qrcode = require('qrcode-terminal');
async function connectToWhatsApp() {
// Load saved session (if exists)
const { state, saveCreds } = await useMultiFileAuthState('auth_info');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
// Save credentials when updated
sock.ev.on('creds.update', saveCreds);
// Handle connection updates
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect, qr } = update;
if (qr) {
// Display QR code
qrcode.generate(qr, { small: true });
}
if (connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) {
connectToWhatsApp(); // Reconnect
}
} else if (connection === 'open') {
console.log('✅ Connected to WhatsApp!');
}
});
return sock;
}
connectToWhatsApp();Step 3: Send Message
javascript
async function sendMessage(sock, to, message) {
// Format nomor: [email protected]
const jid = to.includes('@') ? to : `${to}@s.whatsapp.net`;
await sock.sendMessage(jid, { text: message });
console.log(`✅ Sent to ${to}: ${message}`);
}
// Usage
const sock = await connectToWhatsApp();
await sendMessage(sock, '6281234567890', 'Hello from Node.js!');Step 4: Send Media
javascript
const fs = require('fs');
// Send Image
async function sendImage(sock, to, imagePath, caption = '') {
const jid = `${to}@s.whatsapp.net`;
await sock.sendMessage(jid, {
image: fs.readFileSync(imagePath),
caption: caption
});
}
// Send Document
async function sendDocument(sock, to, filePath, filename) {
const jid = `${to}@s.whatsapp.net`;
await sock.sendMessage(jid, {
document: fs.readFileSync(filePath),
fileName: filename,
mimetype: 'application/pdf' // adjust based on file type
});
}
// Send from URL
async function sendImageFromUrl(sock, to, url, caption = '') {
const jid = `${to}@s.whatsapp.net`;
await sock.sendMessage(jid, {
image: { url: url },
caption: caption
});
}Step 5: Receive Messages & Auto-Reply
javascript
sock.ev.on('messages.upsert', async (m) => {
const msg = m.messages[0];
// Ignore status updates
if (!msg.message) return;
// Get sender info
const sender = msg.key.remoteJid;
const isGroup = sender.endsWith('@g.us');
// Get message content
const messageContent = msg.message.conversation ||
msg.message.extendedTextMessage?.text ||
'';
console.log(`📩 From ${sender}: ${messageContent}`);
// Auto-reply logic
const lowerMsg = messageContent.toLowerCase();
if (lowerMsg === 'halo' || lowerMsg === 'hi') {
await sock.sendMessage(sender, {
text: 'Halo! 👋 Ada yang bisa dibantu?'
});
}
if (lowerMsg === 'menu') {
await sock.sendMessage(sender, {
text: `📋 MENU:
1. INFO - Informasi toko
2. PRODUK - Lihat produk
3. ORDER - Cara order
4. CS - Chat dengan admin
Ketik sesuai pilihan!`
});
}
});Step 6: Full Bot Example
javascript
const { default: makeWASocket,
DisconnectReason,
useMultiFileAuthState } = require('@whiskeysockets/baileys');
async function startBot() {
const { state, saveCreds } = await useMultiFileAuthState('auth');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) startBot();
} else if (connection === 'open') {
console.log('🤖 Bot is online!');
}
});
// Message handler
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0];
if (!msg.message || msg.key.fromMe) return;
const sender = msg.key.remoteJid;
const text = msg.message.conversation ||
msg.message.extendedTextMessage?.text || '';
await handleMessage(sock, sender, text.toLowerCase());
});
}
async function handleMessage(sock, sender, text) {
const replies = {
'halo': 'Halo! Selamat datang! Ketik MENU untuk lihat pilihan.',
'menu': `📋 MENU:\n1. KATALOG\n2. HARGA\n3. ORDER\n4. CS`,
'katalog': '📦 Katalog kami:\n- Produk A: Rp 100k\n- Produk B: Rp 150k',
'harga': '💰 Daftar harga:\n- Produk A: Rp 100k\n- Produk B: Rp 150k',
'order': '🛒 Untuk order, kirim:\nNama:\nAlamat:\nPesanan:',
'cs': '📞 Admin akan segera membalas!'
};
const reply = replies[text];
if (reply) {
await sock.sendMessage(sender, { text: reply });
} else {
await sock.sendMessage(sender, {
text: 'Maaf, saya tidak mengerti. Ketik MENU untuk bantuan.'
});
}
}
startBot();Tutorial 2: Cloud API (Official)
Step 1: Setup Project
bash
mkdir wa-cloud-api
cd wa-cloud-api
npm init -y
npm install axios expressStep 2: Send Message
javascript
const axios = require('axios');
const PHONE_NUMBER_ID = 'YOUR_PHONE_NUMBER_ID';
const ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN';
async function sendMessage(to, message) {
try {
const response = await axios.post(
`https://graph.facebook.com/v17.0/${PHONE_NUMBER_ID}/messages`,
{
messaging_product: 'whatsapp',
to: to,
type: 'text',
text: { body: message }
},
{
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json'
}
}
);
console.log('✅ Message sent:', response.data);
return response.data;
} catch (error) {
console.error('❌ Error:', error.response?.data || error.message);
throw error;
}
}
// Usage
sendMessage('6281234567890', 'Hello from Cloud API!');Step 3: Send Template Message
javascript
async function sendTemplateMessage(to, templateName, languageCode = 'en_US') {
const response = await axios.post(
`https://graph.facebook.com/v17.0/${PHONE_NUMBER_ID}/messages`,
{
messaging_product: 'whatsapp',
to: to,
type: 'template',
template: {
name: templateName,
language: { code: languageCode }
}
},
{
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json'
}
}
);
return response.data;
}
// Usage
sendTemplateMessage('6281234567890', 'hello_world');Step 4: Webhook to Receive Messages
javascript
const express = require('express');
const app = express();
app.use(express.json());
const VERIFY_TOKEN = 'your_verify_token';
// Webhook verification
app.get('/webhook', (req, res) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
console.log('✅ Webhook verified!');
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
});
// Receive messages
app.post('/webhook', async (req, res) => {
const body = req.body;
if (body.object === 'whatsapp_business_account') {
for (const entry of body.entry) {
for (const change of entry.changes) {
if (change.value.messages) {
const message = change.value.messages[0];
const from = message.from;
const text = message.text?.body || '';
console.log(`📩 From ${from}: ${text}`);
// Auto-reply
if (text.toLowerCase() === 'halo') {
await sendMessage(from, 'Halo! Ada yang bisa dibantu?');
}
}
}
}
}
res.sendStatus(200);
});
app.listen(3000, () => {
console.log('🚀 Webhook server running on port 3000');
});Best Practices
1. Environment Variables
javascript
// .env
PHONE_NUMBER_ID=your_phone_id
ACCESS_TOKEN=your_token
VERIFY_TOKEN=your_verify_token
// app.js
require('dotenv').config();
const PHONE_NUMBER_ID = process.env.PHONE_NUMBER_ID;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;2. Error Handling
javascript
async function sendMessageSafe(to, message) {
try {
await sendMessage(to, message);
} catch (error) {
console.error('Failed to send message:', error);
// Log to monitoring service
// Retry logic if needed
}
}3. Rate Limiting
javascript
const rateLimiter = {
queue: [],
processing: false,
add(task) {
this.queue.push(task);
this.process();
},
async process() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
const task = this.queue.shift();
await task();
await new Promise(r => setTimeout(r, 1000)); // 1 msg/second
this.processing = false;
this.process();
}
};
// Usage
rateLimiter.add(() => sendMessage('628xxx', 'Hello'));FAQ
Library Node.js mana yang terbaik untuk WhatsApp API?
Untuk unofficial: Baileys (@whiskeysockets/baileys) paling aktif maintained dan punya multi-device support. Untuk official: gunakan axios atau node-fetch untuk Cloud API HTTP calls. Pilih berdasarkan kebutuhan — unofficial untuk testing/personal, official untuk production.
Apakah perlu server untuk menjalankan WhatsApp bot Node.js?
Ya, untuk bot yang always-on. Opsi hosting: VPS (DigitalOcean, Vultr ~$5/bulan), cloud platform (Railway, Render — free tier available), atau serverless (Vercel, AWS Lambda — untuk Cloud API webhooks). Untuk testing, bisa jalankan di local machine.
Bagaimana handle reconnection jika bot disconnect?
Baileys support auto-reconnect dan session persistence. Simpan credentials ke file/database menggunakan useMultiFileAuthState, load saat startup. Implement connection.update event handler untuk detect disconnect dan trigger reconnect otomatis.
Kesimpulan
Node.js = Platform ideal untuk WhatsApp bot!
Quick Reference:
| Task | Baileys | Cloud API |
|---|---|---|
| Send text | sock.sendMessage(jid, { text }) | POST /messages |
| Send image | sock.sendMessage(jid, { image }) | POST /messages (type: image) |
| Receive msg | messages.upsert event | Webhook POST |
| Auth | QR Code scan | Access Token |
Starter Code:
bash
# Baileys (Unofficial)
npm install @whiskeysockets/baileys qrcode-terminal
# Cloud API (Official)
npm install axios express dotenvHappy coding! 🚀
Atau Coba No-Code Solution — Gratis! →