Skip to content

yllumi/wasender-bailey

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WhatsApp Multi-Session API with Baileys

WhatsApp API dengan dukungan multi-session menggunakan Hono framework dan Baileys library untuk mengirim pesan WhatsApp melalui HTTP endpoint.

contoh-dashboard-wasender.png

πŸš€ Fitur

  • βœ… Multi-session support - Kelola banyak akun WhatsApp dalam satu aplikasi
  • βœ… Web Management Interface - Dashboard untuk create, view, dan delete sessions
  • βœ… Koneksi WhatsApp via QR Code dengan tampilan web
  • βœ… Kirim pesan WhatsApp via API
  • βœ… Auto-reconnect jika koneksi terputus
  • βœ… Session persistence (tidak perlu scan QR berulang)
  • βœ… API Key authentication
  • βœ… HTTP Basic Auth untuk management endpoints
  • βœ… Auto-format nomor telepon Indonesia
  • βœ… Health monitoring (memory, uptime, sessions)
  • βœ… Session limits untuk resource management

πŸ“‹ Prerequisites

  • Bun runtime
  • WhatsApp account untuk di-link

πŸ› οΈ Instalasi

  1. Clone atau download project ini

  2. Install dependencies:

bun install
  1. Buat file .env:
PORT=8990

# App Key untuk autentikasi API
APP_KEY=your-secret-app-key-here

# HTTP Basic Auth untuk akses management endpoints
HTTP_AUTH_USERNAME=admin
HTTP_AUTH_PASSWORD=your-secure-password

# Session Limits (sesuaikan dengan RAM server)
MAX_SESSIONS=15

Rekomendasi MAX_SESSIONS berdasarkan RAM:

  • 1 GB RAM: 10-15 sessions
  • 2 GB RAM: 30-40 sessions
  • 4 GB RAM: 80-100 sessions

πŸš€ Menjalankan Aplikasi

bun run src/index.ts

Server akan berjalan di http://localhost:8990 (atau port yang Anda set di .env)

🌐 Web Management Interface

Buka browser dan akses: http://localhost:8990

Interface ini memungkinkan Anda untuk:

  • βœ… Melihat semua sessions yang aktif
  • βœ… Monitor status koneksi setiap session
  • βœ… Create session baru
  • βœ… Hapus session yang tidak digunakan
  • βœ… Akses QR code untuk setiap session
  • βœ… Monitor health status (memory, uptime, sessions)
  • βœ… Lihat dokumentasi API dengan contoh kode

Authentication: Masukkan username dan password dari .env saat diminta.

πŸ“± Menghubungkan WhatsApp

Cara 1: Melalui Web Interface

  1. Buka http://localhost:8990
  2. Login dengan credentials dari .env
  3. Buat session baru (misal: akun1, customer01)
  4. Klik tombol "πŸ“± QR Code" pada session yang dibuat
  5. Scan QR code dengan WhatsApp di ponsel Anda
  6. Tunggu hingga status berubah menjadi "Connected"

Cara 2: Langsung ke URL QR

  1. Buat session terlebih dahulu (lihat API Endpoints)
  2. Akses: http://localhost:8990/{session_name}/qr
  3. Scan QR code yang muncul dengan WhatsApp:
    • Buka WhatsApp β†’ Settings β†’ Linked Devices β†’ Link a Device
  4. Tunggu hingga status berubah menjadi "WhatsApp Connected"

Note: Session akan tersimpan di folder auth_info_baileys/sessions/{session_name}, jadi Anda tidak perlu scan QR code setiap kali restart aplikasi.

🎯 Session Names

Session name harus memenuhi kriteria:

  • βœ… Hanya lowercase letters (a-z)
  • βœ… Hanya angka (0-9)
  • ❌ Tidak boleh ada spasi, underscore, atau karakter spesial
  • βœ… Contoh valid: akun1, customer01, tokoofficial
  • ❌ Contoh invalid: Akun1, toko_official, akun-1

πŸ”‘ Setup App Key

Generate App Key Baru

curl http://localhost:8990/generate-appkey

Response:

{
  "success": true,
  "message": "App key generated successfully. Save it to .env file.",
  "app_key": "b5a4e372a4ec0c15683ff08e132e7042ebd5b363d338cfd864ba6f826d95dd90"
}

Simpan App Key tersebut ke file .env:

APP_KEY=b5a4e372a4ec0c15683ff08e132e7042ebd5b363d338cfd864ba6f826d95dd90

Cek App Key yang Terdaftar

Jika lupa app key, Anda bisa cek dengan HTTP Basic Auth:

curl http://localhost:8990/appkey \
  -u admin:your-secure-password

Response:

{
  "success": true,
  "message": "Your current app key:",
  "app_key": "b5a4e372a4ec0c15683ff08e132e7042ebd5b363d338cfd864ba6f826d95dd90"
}

πŸ“‘ API Endpoints

1. GET /

Web Management Interface untuk kelola sessions.

Authentication: HTTP Basic Auth

Response: HTML dashboard


2. GET /health

Health check dan monitoring aplikasi.

Request:

curl http://localhost:8990/health

Response:

{
  "success": true,
  "status": "running",
  "uptime": 3600.5,
  "memory": {
    "rss_mb": 145,
    "heap_used_mb": 78,
    "heap_total_mb": 120,
    "external_mb": 5
  },
  "sessions": {
    "total": 3,
    "connected": 2,
    "disconnected": 1,
    "reconnecting": 0,
    "max_sessions": 15,
    "available_slots": 12
  }
}

3. GET /sessions

List semua sessions yang terdaftar.

Authentication: HTTP Basic Auth

Request:

curl http://localhost:8990/sessions \
  -u admin:password

Response:

{
  "success": true,
  "count": 2,
  "sessions": [
    {
      "name": "akun1",
      "isConnected": true,
      "phoneNumber": "628123456789",
      "createdAt": "2026-01-15T10:00:00.000Z",
      "lastActivity": "2026-01-15T11:30:00.000Z"
    },
    {
      "name": "customer01",
      "isConnected": false,
      "phoneNumber": "Not connected yet",
      "createdAt": "2026-01-15T11:00:00.000Z",
      "lastActivity": "2026-01-15T11:00:00.000Z"
    }
  ]
}

4. POST /sessions/:name

Membuat session baru.

Authentication: HTTP Basic Auth

Request:

curl -X POST http://localhost:8990/sessions/akun1 \
  -u admin:password

Response:

{
  "success": true,
  "message": "Session created successfully",
  "session": {
    "name": "akun1",
    "qr_url": "/akun1/qr"
  }
}

Error Response (Session Limit Reached):

{
  "success": false,
  "message": "Maximum sessions limit (15) reached. Please delete unused sessions first.",
  "current_sessions": 15,
  "max_sessions": 15
}

5. DELETE /:session_name

Menghapus session.

Authentication: HTTP Basic Auth

Request:

curl -X DELETE http://localhost:8990/akun1 \
  -u admin:password

Response:

{
  "success": true,
  "message": "Session \"akun1\" deleted successfully"
}

6. GET /:session_name/qr

Menampilkan QR code untuk menghubungkan WhatsApp pada session tertentu.

Response: HTML page dengan QR code

Akses via browser: http://localhost:8990/akun1/qr


7. POST /:session_name/send

Mengirim pesan WhatsApp melalui session tertentu.

Authentication: App Key (via header atau query parameter)

Body Parameters:

  • number (string, required): Nomor WhatsApp tujuan
  • message (string, required): Pesan yang akan dikirim

Headers:

  • Content-Type: application/json
  • X-App-Key: your-app-key (atau gunakan query parameter)

Request Example:

curl -X POST "http://localhost:8990/akun1/send?app_key=YOUR_APP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "number": "628986818780",
    "message": "Hello from WhatsApp API!"
  }'

Response Success:

{
  "success": true,
  "message": "Message sent successfully",
  "session": "akun1",
  "to": "628986818780"
}

Response Error:

{
  "success": false,
  "message": "Session \"akun1\" is not connected. Please scan QR code first at /akun1/qr or wait for reconnection."
}

8. GET /generate-appkey

Generate app key baru.

Request:

curl http://localhost:8990/generate-appkey

Response:

{
  "success": true,
  "message": "App key generated successfully. Save it to .env file.",
  "app_key": "b5a4e372a4ec0c15683ff08e132e7042ebd5b363d338cfd864ba6f826d95dd90"
}

9. GET /appkey

Cek app key yang terdaftar.

Authentication: HTTP Basic Auth

Request:

curl http://localhost:8990/appkey \
  -u admin:password

Response:

{
  "success": true,
  "message": "Your current app key:",
  "app_key": "b5a4e372a4ec0c15683ff08e132e7042ebd5b363d338cfd864ba6f826d95dd90"
}

πŸ“ Format Nomor Telepon

API otomatis memformat nomor telepon Indonesia:

  • 081234567890 β†’ 628123456890
  • 628123456890 β†’ 628123456890 (sudah benar)
  • 8123456890 β†’ 628123456890

Untuk nomor internasional, gunakan format lengkap dengan kode negara.

πŸ’» Contoh Kode Integrasi

PHP

<?php
$url = 'http://localhost:8990/akun1/send?app_key=YOUR_APP_KEY';

$data = [
    'number' => '628986818780',
    'message' => 'Hello from WhatsApp API!'
];

$options = [
    'http' => [
        'header'  => "Content-Type: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($data)
    ]
];

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) {
    die('Error sending message');
}

$response = json_decode($result, true);
print_r($response);
?>

JavaScript (Fetch API)

async function sendWhatsAppMessage(sessionName, phoneNumber, message) {
  const url = `http://localhost:8990/${sessionName}/send?app_key=YOUR_APP_KEY`;
  
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        number: phoneNumber,
        message: message
      })
    });
    
    const data = await response.json();
    
    if (data.success) {
      console.log('Message sent successfully!');
      return data;
    } else {
      console.error('Error:', data.message);
      throw new Error(data.message);
    }
  } catch (error) {
    console.error('Failed to send message:', error);
    throw error;
  }
}

// Usage example
sendWhatsAppMessage('akun1', '628986818780', 'Hello from WhatsApp API!')
  .then(result => console.log('Success:', result))
  .catch(error => console.error('Error:', error));

Python

import requests
import json

url = 'http://localhost:8990/akun1/send'
params = {'app_key': 'YOUR_APP_KEY'}
headers = {'Content-Type': 'application/json'}

data = {
    'number': '628986818780',
    'message': 'Hello from WhatsApp API!'
}

response = requests.post(url, params=params, headers=headers, json=data)
result = response.json()

if result['success']:
    print('Message sent successfully!')
    print(f"Sent to: {result['to']}")
else:
    print(f"Error: {result['message']}")

Note: Ganti YOUR_APP_KEY dengan app key dari .env dan akun1 dengan nama session Anda.

πŸ”’ Keamanan

  1. Jangan commit file .env ke repository (sudah ada di .gitignore)
  2. Backup folder auth_info_baileys - berisi kredensial WhatsApp sessions
  3. Jangan share App Key kepada orang lain
  4. Gunakan password yang kuat untuk HTTP Basic Auth
  5. Gunakan HTTPS jika deploy ke production
  6. Jangan expose .env file ke publik
  7. Monitor health endpoint untuk resource usage
  8. Set MAX_SESSIONS sesuai kapasitas server

πŸ› Troubleshooting

QR Code tidak muncul

  • Pastikan session sudah dibuat via web interface atau API
  • Pastikan aplikasi sudah running
  • Refresh halaman browser
  • Cek log di terminal untuk error

Session tidak bisa dibuat

  • Cek apakah sudah mencapai MAX_SESSIONS limit
  • Pastikan nama session valid (lowercase + numbers only)
  • Cek memory availability di /health endpoint

Pesan gagal terkirim

  • Pastikan session sudah connected (cek di web interface)
  • Pastikan App Key valid
  • Cek apakah nomor tujuan valid (gunakan format internasional)
  • Pastikan koneksi internet stabil
  • Cek status session di /sessions endpoint

Session terputus setelah restart

  • Session otomatis akan reconnect jika folder auth_info_baileys/sessions/{name} masih ada
  • Jika tidak bisa reconnect, hapus session dan buat ulang
  • Cek log untuk melihat error reconnection

Error "Invalid credentials" saat akses web interface

  • Pastikan username dan password sesuai dengan .env
  • Restart aplikasi setelah edit .env

Error "Maximum sessions limit reached"

  • Hapus session yang tidak digunakan via web interface
  • Tingkatkan MAX_SESSIONS di .env (sesuaikan dengan RAM)
  • Restart aplikasi setelah edit .env

High memory usage

  • Monitor via /health endpoint
  • Kurangi jumlah active sessions
  • Hapus session yang tidak connected
  • Restart aplikasi untuk clear memory

πŸ“„ License

MIT

🀝 Contributing

Contributions, issues, and feature requests are welcome!

⚠️ Disclaimer

Gunakan API ini dengan bijak dan sesuai dengan Terms of Service WhatsApp. Penggunaan yang berlebihan atau spam dapat menyebabkan nomor WhatsApp Anda diblokir.

About

Whatsapp Message Sender API built with Baileys

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors