Add DOCUMENTATION.md

This commit is contained in:
andri 2025-09-23 19:34:42 +00:00
parent 87ca24ea46
commit 147cdbe1c5
1 changed files with 792 additions and 0 deletions

792
DOCUMENTATION.md Normal file
View File

@ -0,0 +1,792 @@
# WhatsApp Gateway API Documentation
## Overview
**WhatsApp Gateway API** adalah REST API lengkap untuk mengirim berbagai jenis pesan WhatsApp menggunakan library Baileys. API ini menyediakan endpoints untuk mengirim text, gambar, dokumen, audio, video, dan sticker melalui WhatsApp.
### API Information
- **Base URL**: `http://your-server:5000`
- **Version**: 2.0.0
- **Protocol**: HTTP/HTTPS
- **Format**: JSON
- **Authentication**: Optional (API Key)
---
## Table of Contents
1. [Authentication](#authentication)
2. [Base Endpoints](#base-endpoints)
3. [Message Endpoints](#message-endpoints)
4. [File Upload Guidelines](#file-upload-guidelines)
5. [Error Handling](#error-handling)
6. [Rate Limiting](#rate-limiting)
7. [Examples](#examples)
8. [Response Codes](#response-codes)
---
## Authentication
API authentication bersifat opsional dan dikonfigurasi melalui environment variables.
### API Key (Optional)
Jika enabled, sertakan API key di header request:
```http
X-API-Key: your-api-key-here
```
Atau menggunakan Authorization header:
```http
Authorization: Bearer your-api-key-here
```
---
## Base Endpoints
### 1. Health Check / API Information
**Endpoint:** `GET /`
**Description:** Mendapatkan informasi lengkap tentang API, status bot, dan fitur yang tersedia.
**Request:**
```http
GET / HTTP/1.1
Host: localhost:5000
```
**Response:**
```json
{
"service": "WhatsApp Gateway Production",
"status": "running",
"bot_connected": true,
"version": "2.0.0",
"environment": "production",
"features": {
"text_messages": "✅ Working",
"image_messages": "✅ Working",
"document_messages": "✅ Working",
"audio_messages": "✅ Available",
"video_messages": "✅ Available",
"sticker_messages": "✅ Available",
"webhooks": "❌ Disabled",
"analytics": "✅ Enabled",
"rate_limiting": "✅ Enabled",
"api_auth": "❌ Disabled"
},
"supported_formats": {
"images": ["jpg", "jpeg", "png", "gif", "webp"],
"documents": ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "zip", "rar", "7z"],
"audio": ["mp3", "wav", "ogg", "m4a", "aac", "flac"],
"video": ["mp4", "avi", "mov", "mkv", "webm", "3gp", "flv"],
"stickers": ["webp"]
},
"file_size_limits": {
"images": "16MB",
"documents": "32MB",
"audio": "16MB",
"video": "64MB",
"stickers": "1MB"
},
"endpoints": [
"POST /api/send-message - Send text message",
"POST /api/send-image - Send image with caption",
"POST /api/send-document - Send document with caption",
"POST /api/send-audio - Send audio file",
"POST /api/send-video - Send video with caption",
"POST /api/send-sticker - Send WebP sticker",
"GET /api/status - Bot status",
"GET /api/health - Health check"
],
"limits": {
"max_requests": 100,
"time_window": "3600s"
},
"uptime": 1234.56,
"memory": {
"used": 85,
"total": 128
}
}
```
### 2. Bot Status
**Endpoint:** `GET /api/status`
**Description:** Mendapatkan status detail bot WhatsApp dan sistem.
**Request:**
```http
GET /api/status HTTP/1.1
Host: localhost:5000
```
**Response:**
```json
{
"bot_connected": true,
"connection_attempts": 0,
"max_attempts": 5,
"thread_alive": true,
"upload_folder": "./uploads",
"session_folder": "./session",
"environment": "production",
"features": {
"webhooks": false,
"analytics": true,
"rate_limiting": true,
"api_authentication": false
},
"supported_formats": {
"images": ["jpg", "jpeg", "png", "gif", "webp"],
"documents": ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "zip", "rar", "7z"],
"audio": ["mp3", "wav", "ogg", "m4a", "aac", "flac"],
"video": ["mp4", "avi", "mov", "mkv", "webm", "3gp", "flv"],
"stickers": ["webp"]
},
"system": {
"uptime": 1234.56,
"memory_usage_mb": 85,
"node_version": "v20.11.0",
"platform": "linux"
},
"message": "Bot status retrieved"
}
```
### 3. Health Check
**Endpoint:** `GET /api/health`
**Description:** Simple health check untuk monitoring.
**Request:**
```http
GET /api/health HTTP/1.1
Host: localhost:5000
```
**Response (Bot Connected):**
```json
{
"status": "ok",
"timestamp": "2025-09-23T13:45:30.123Z",
"uptime": 1234.56,
"environment": "production",
"services": {
"whatsapp_bot": "connected",
"api_server": "running"
}
}
```
**Response (Bot Disconnected):**
```json
{
"status": "ok",
"timestamp": "2025-09-23T13:45:30.123Z",
"uptime": 1234.56,
"environment": "production",
"services": {
"whatsapp_bot": "disconnected",
"api_server": "running"
}
}
```
### 4. QR Code
**Endpoint:** `GET /api/qr`
**Description:** Mendapatkan QR code untuk koneksi WhatsApp (jika tersedia).
**Request:**
```http
GET /api/qr HTTP/1.1
Host: localhost:5000
```
**Response (QR Available):**
```json
{
"status": "success",
"qr": "2@8QJwrEjN8hKDGkjgh...",
"message": "QR code available for scanning"
}
```
**Response (Already Connected):**
```json
{
"status": "success",
"message": "Bot already connected, no QR needed"
}
```
---
## Message Endpoints
### 1. Send Text Message
**Endpoint:** `POST /api/send-message`
**Description:** Mengirim pesan text ke nomor WhatsApp.
**Request:**
```http
POST /api/send-message HTTP/1.1
Host: localhost:5000
Content-Type: application/json
{
"phone": "6281234567890",
"message": "Hello from WhatsApp Gateway API!"
}
```
**Response (Success):**
```json
{
"status": "success",
"message": "Text message sent successfully",
"data": {
"phone": "6281234567890",
"message": "Hello from WhatsApp Gateway API!",
"type": "text",
"timestamp": "2025-09-23 13:45:30"
}
}
```
### 2. Send Image
**Endpoint:** `POST /api/send-image`
**Description:** Mengirim gambar dengan caption opsional.
**Request:**
```http
POST /api/send-image HTTP/1.1
Host: localhost:5000
Content-Type: multipart/form-data
--boundary
Content-Disposition: form-data; name="phone"
6281234567890
--boundary
Content-Disposition: form-data; name="caption"
Beautiful sunset photo!
--boundary
Content-Disposition: form-data; name="file"; filename="sunset.jpg"
Content-Type: image/jpeg
[binary image data]
--boundary--
```
**cURL Example:**
```bash
curl -X POST http://localhost:5000/api/send-image \
-F "phone=6281234567890" \
-F "caption=Beautiful sunset photo!" \
-F "file=@sunset.jpg"
```
**Response (Success):**
```json
{
"status": "success",
"message": "Image sent successfully",
"data": {
"phone": "6281234567890",
"filename": "sunset.jpg",
"caption": "Beautiful sunset photo!",
"type": "image",
"file_size_kb": 245.67,
"timestamp": "2025-09-23 13:45:30"
}
}
```
### 3. Send Document
**Endpoint:** `POST /api/send-document`
**Description:** Mengirim dokumen dengan caption opsional.
**Request (Form Data):**
- `phone` (required): Nomor WhatsApp tujuan
- `file` (required): File dokumen
- `caption` (optional): Caption untuk dokumen
**cURL Example:**
```bash
curl -X POST http://localhost:5000/api/send-document \
-F "phone=6281234567890" \
-F "caption=Important document" \
-F "file=@report.pdf"
```
**Response (Success):**
```json
{
"status": "success",
"message": "Document sent successfully",
"data": {
"phone": "6281234567890",
"filename": "report.pdf",
"caption": "Important document",
"type": "document",
"file_size_kb": 1024.50,
"timestamp": "2025-09-23 13:45:30"
}
}
```
### 4. Send Audio
**Endpoint:** `POST /api/send-audio`
**Description:** Mengirim file audio sebagai voice note.
**Request (Form Data):**
- `phone` (required): Nomor WhatsApp tujuan
- `file` (required): File audio
**cURL Example:**
```bash
curl -X POST http://localhost:5000/api/send-audio \
-F "phone=6281234567890" \
-F "file=@voice_message.mp3"
```
**Response (Success):**
```json
{
"status": "success",
"message": "Audio sent successfully",
"data": {
"phone": "6281234567890",
"filename": "voice_message.mp3",
"type": "audio",
"file_size_kb": 512.25,
"timestamp": "2025-09-23 13:45:30"
}
}
```
### 5. Send Video
**Endpoint:** `POST /api/send-video`
**Description:** Mengirim video dengan caption opsional.
**Request (Form Data):**
- `phone` (required): Nomor WhatsApp tujuan
- `file` (required): File video
- `caption` (optional): Caption untuk video
**cURL Example:**
```bash
curl -X POST http://localhost:5000/api/send-video \
-F "phone=6281234567890" \
-F "caption=Amazing video!" \
-F "file=@demo.mp4"
```
**Response (Success):**
```json
{
"status": "success",
"message": "Video sent successfully",
"data": {
"phone": "6281234567890",
"filename": "demo.mp4",
"caption": "Amazing video!",
"type": "video",
"file_size_kb": 2048.75,
"timestamp": "2025-09-23 13:45:30"
}
}
```
### 6. Send Sticker
**Endpoint:** `POST /api/send-sticker`
**Description:** Mengirim sticker dalam format WebP.
**Request (Form Data):**
- `phone` (required): Nomor WhatsApp tujuan
- `file` (required): File sticker (WebP)
**cURL Example:**
```bash
curl -X POST http://localhost:5000/api/send-sticker \
-F "phone=6281234567890" \
-F "file=@funny_sticker.webp"
```
**Response (Success):**
```json
{
"status": "success",
"message": "Sticker sent successfully",
"data": {
"phone": "6281234567890",
"filename": "funny_sticker.webp",
"type": "sticker",
"file_size_kb": 23.45,
"timestamp": "2025-09-23 13:45:30"
}
}
```
---
## File Upload Guidelines
### Supported File Types
| Media Type | Extensions | Max Size | Caption Support |
|------------|------------|----------|-----------------|
| **Images** | jpg, jpeg, png, gif, webp | 16MB | ✅ Yes |
| **Documents** | pdf, doc, docx, xls, xlsx, ppt, pptx, txt, zip, rar, 7z | 32MB | ✅ Yes |
| **Audio** | mp3, wav, ogg, m4a, aac, flac | 16MB | ❌ No |
| **Video** | mp4, avi, mov, mkv, webm, 3gp, flv | 64MB | ✅ Yes |
| **Stickers** | webp | 1MB | ❌ No |
### Phone Number Format
API mendukung berbagai format nomor telepon:
- `6281234567890` (format internasional Indonesia)
- `+6281234567890` (dengan tanda plus)
- `081234567890` (format lokal, otomatis dikonversi)
Semua format akan dikonversi ke format WhatsApp: `6281234567890@s.whatsapp.net`
---
## Error Handling
Semua error menggunakan format JSON yang konsisten:
### Error Response Format
```json
{
"status": "error",
"message": "Error description here",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
### Common Errors
#### 400 - Bad Request
```json
{
"status": "error",
"message": "Phone number required",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
```json
{
"status": "error",
"message": "Invalid file type. Allowed: [\"jpg\",\"jpeg\",\"png\",\"gif\",\"webp\"]",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
#### 401 - Unauthorized (jika API key enabled)
```json
{
"status": "error",
"message": "Unauthorized: Invalid or missing API key",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
#### 404 - Not Found
```json
{
"status": "error",
"message": "Endpoint not found",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
#### 429 - Rate Limit Exceeded
```json
{
"status": "error",
"message": "Too many requests. Please try again later.",
"timestamp": "2025-09-23T13:45:30.123Z",
"limit": 100,
"window": 3600
}
```
#### 500 - Internal Server Error
```json
{
"status": "error",
"message": "Failed to send message: connection timeout",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
#### 503 - Service Unavailable
```json
{
"status": "error",
"message": "Bot not connected",
"timestamp": "2025-09-23T13:45:30.123Z"
}
```
---
## Rate Limiting
Rate limiting dapat dikonfigurasi melalui environment variables:
- **Default Limit**: 100 requests per hour
- **Time Window**: 3600 seconds (1 hour)
- **Headers**: Response tidak include rate limit headers
- **Scope**: Per IP address
Ketika limit tercapai, API akan mengembalikan HTTP 429 dengan pesan error.
---
## Examples
### JavaScript (Node.js)
```javascript
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const API_BASE = 'http://localhost:5000';
// Send text message
async function sendText(phone, message) {
try {
const response = await axios.post(`${API_BASE}/api/send-message`, {
phone: phone,
message: message
});
console.log('Success:', response.data);
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
// Send image
async function sendImage(phone, imagePath, caption) {
try {
const form = new FormData();
form.append('phone', phone);
form.append('caption', caption);
form.append('file', fs.createReadStream(imagePath));
const response = await axios.post(`${API_BASE}/api/send-image`, form, {
headers: form.getHeaders()
});
console.log('Success:', response.data);
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
// Usage
sendText('6281234567890', 'Hello from Node.js!');
sendImage('6281234567890', './image.jpg', 'Sample image');
```
### Python
```python
import requests
API_BASE = 'http://localhost:5000'
# Send text message
def send_text(phone, message):
response = requests.post(f'{API_BASE}/api/send-message', json={
'phone': phone,
'message': message
})
return response.json()
# Send image
def send_image(phone, image_path, caption=None):
with open(image_path, 'rb') as f:
files = {'file': f}
data = {'phone': phone}
if caption:
data['caption'] = caption
response = requests.post(f'{API_BASE}/api/send-image',
files=files, data=data)
return response.json()
# Usage
result = send_text('6281234567890', 'Hello from Python!')
print(result)
result = send_image('6281234567890', './image.jpg', 'Sample image')
print(result)
```
### PHP
```php
<?php
$apiBase = 'http://localhost:5000';
// Send text message
function sendText($phone, $message) {
global $apiBase;
$data = json_encode([
'phone' => $phone,
'message' => $message
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiBase/api/send-message");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// Send image
function sendImage($phone, $imagePath, $caption = null) {
global $apiBase;
$postData = [
'phone' => $phone,
'file' => new CURLFile($imagePath)
];
if ($caption) {
$postData['caption'] = $caption;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiBase/api/send-image");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// Usage
$result = sendText('6281234567890', 'Hello from PHP!');
print_r($result);
?>
```
### cURL Commands
```bash
# Send text message
curl -X POST http://localhost:5000/api/send-message \
-H "Content-Type: application/json" \
-d '{"phone":"6281234567890","message":"Hello from cURL!"}'
# Send image
curl -X POST http://localhost:5000/api/send-image \
-F "phone=6281234567890" \
-F "caption=Sample image" \
-F "file=@image.jpg"
# Send document
curl -X POST http://localhost:5000/api/send-document \
-F "phone=6281234567890" \
-F "caption=Important document" \
-F "file=@document.pdf"
# Check status
curl http://localhost:5000/api/status
# Health check
curl http://localhost:5000/api/health
```
---
## Response Codes
| Code | Description | Meaning |
|------|-------------|---------|
| 200 | OK | Request successful |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Invalid or missing API key |
| 404 | Not Found | Endpoint not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error occurred |
| 503 | Service Unavailable | Bot not connected |
---
## Troubleshooting
### Common Issues
1. **Bot Not Connected**
- Check `/api/status` endpoint
- Look for QR code in server logs
- Scan QR code with WhatsApp
2. **File Upload Fails**
- Check file size limits
- Verify file extension is supported
- Ensure proper Content-Type header
3. **Rate Limit Hit**
- Wait for time window to reset
- Reduce request frequency
- Contact admin to adjust limits
4. **Authentication Error**
- Check if API key is required
- Verify API key in headers
- Ensure correct header format
### Support
For technical support or questions:
- Check server logs: `sudo journalctl -u wa -f`
- Verify bot connection: `curl http://localhost:5000/api/status`
- Test basic connectivity: `curl http://localhost:5000/api/health`
---
**API Version**: 2.0.0
**Last Updated**: September 23, 2025
**Status**: Production Ready