# Panduan POST-Only Receiver

## Pengenalan

POST-Only Receiver adalah fitur baru yang memungkinkan sistem menerima data hanya melalui metode POST dengan integrasi penuh ke API Token Management. Fitur ini dirancang khusus untuk webhook, form submission, dan data collection yang memerlukan keamanan tinggi.

## Fitur Utama

### 🔒 Keamanan Terintegrasi
- **Token Authentication**: Validasi token melalui API Token Management
- **Rate Limiting**: Pembatasan request per IP address
- **IP Whitelist**: Kontrol akses berdasarkan IP (opsional)
- **Validasi Data**: Validasi otomatis berdasarkan rules yang dikonfigurasi

### 📊 Data Processing
- **Auto-Create Table**: Membuat tabel target otomatis dari sample data
- **Field Mapping**: Mapping field dari request ke database
- **Validation Rules**: Aturan validasi yang fleksibel
- **Error Handling**: Penanganan error yang komprehensif

### 📈 Monitoring & Logging
- **Real-time Statistics**: Total received, success, failed, success rate
- **Detailed Logging**: Log setiap request dengan detail lengkap
- **Performance Metrics**: Response time dan payload size tracking

## Cara Menggunakan

### 1. Setup API Client & Token

Sebelum membuat POST-Only Receiver, pastikan Anda sudah memiliki:

1. **API Client**: Buat di menu `API Management > API Clients`
2. **API Token**: Generate token untuk client di menu `Client Management > Token Management`

### 2. Membuat POST-Only Receiver

1. Akses menu `API Management > POST-Only Receivers`
2. Klik "Buat Receiver Baru"
3. Isi konfigurasi:
   - **Nama**: Nama deskriptif untuk receiver
   - **Endpoint**: URL path (contoh: `webhook-data`)
   - **Target Table**: Tabel database tujuan
   - **API Client**: Pilih client yang sudah dibuat
   - **Require Token**: Centang jika memerlukan autentikasi
   - **Sample Data**: JSON contoh untuk auto-create table

### 3. Konfigurasi Lanjutan

#### Validation Rules
Atur aturan validasi untuk data yang diterima:

```json
{
  "field1": {
    "required": true,
    "type": "string",
    "max_length": 100
  },
  "field2": {
    "required": true,
    "type": "numeric"
  }
}
```

#### Field Mapping
Mapping field dari request ke database:

```json
{
  "source_field": "target_column",
  "user_id": "customer_id",
  "amount": "total_amount"
}
```

### 4. Mengirim Data ke Endpoint

#### Dengan Token (Recommended)
```bash
curl -X POST https://yoursite.com/api/post/webhook-data \
  -H "Authorization: Bearer your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "event_type": "user_created",
    "data": {
      "user_id": 123,
      "email": "user@example.com"
    },
    "timestamp": "2025-01-23T10:30:00Z"
  }'
```

#### Tanpa Token (Public Endpoint)
```bash
curl -X POST https://yoursite.com/api/post/form-submit \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "message": "Hello World"
  }'
```

## Response Format

### Success Response
```json
{
  "success": true,
  "message": "Data berhasil diterima dan disimpan",
  "endpoint": "webhook-data",
  "received_at": "2025-01-23T10:30:00.000Z",
  "records_count": 1
}
```

### Error Response
```json
{
  "success": false,
  "error": "Token tidak valid atau telah expired",
  "code": 401,
  "timestamp": "2025-01-23T10:30:00.000Z"
}
```

## Monitoring & Analytics

### Dashboard Overview
- Total receivers aktif
- Request statistics (hari ini, minggu ini, bulan ini)
- Success rate per receiver
- Top endpoints berdasarkan traffic

### Detail Receiver
- Real-time statistics
- Recent activity logs
- Performance metrics
- Error analysis

### Logs
Setiap request dicatat dengan detail:
- Timestamp
- IP address
- User agent
- Request headers & body
- Response status & message
- Processing time
- Validation results
- Save status

## Best Practices

### 1. Keamanan
- **Selalu gunakan token** untuk endpoint sensitif
- **Set rate limiting** sesuai kebutuhan
- **Gunakan IP whitelist** untuk sistem internal
- **Monitor logs** secara berkala

### 2. Performance
- **Optimasi validation rules** - hindari rules yang terlalu kompleks
- **Set rate limit** yang realistis
- **Monitor response time** dan optimasi jika diperlukan
- **Cleanup logs** secara berkala

### 3. Data Management
- **Gunakan field mapping** untuk normalisasi data
- **Set validation rules** yang ketat untuk data quality
- **Monitor target table** size dan performance
- **Backup data** secara berkala

## Troubleshooting

### Error 401: Unauthorized
- Periksa Bearer token di header
- Pastikan token belum expired
- Verifikasi API client masih aktif

### Error 429: Rate Limit Exceeded
- Tunggu sampai rate limit reset (1 jam)
- Hubungi admin untuk meningkatkan limit
- Implementasi retry mechanism dengan backoff

### Error 400: Validation Failed
- Periksa format data sesuai validation rules
- Pastikan required fields tersedia
- Cek tipe data sesuai yang diharapkan

### Error 500: Internal Server Error
- Periksa logs untuk detail error
- Pastikan target table exists atau auto-create enabled
- Verifikasi database connection

## API Endpoints

### Management Endpoints
- `GET /post-only-receivers` - List receivers
- `POST /post-only-receivers` - Create receiver
- `GET /post-only-receivers/{id}` - Show receiver
- `PUT /post-only-receivers/{id}` - Update receiver
- `DELETE /post-only-receivers/{id}` - Delete receiver
- `GET /post-only-receivers/{id}/logs` - View logs
- `GET /post-only-receivers/{id}/stats` - Get statistics

### Data Reception Endpoints
- `POST /api/post/{endpoint}` - Receive data

## Contoh Use Cases

### 1. Webhook dari Payment Gateway
```json
{
  "transaction_id": "TRX123456",
  "amount": 100000,
  "status": "completed",
  "customer_email": "customer@example.com",
  "payment_method": "credit_card"
}
```

### 2. IoT Sensor Data
```json
{
  "device_id": "SENSOR_001",
  "temperature": 25.5,
  "humidity": 60.2,
  "battery_level": 85,
  "timestamp": "2025-01-23T10:30:00Z"
}
```

### 3. Form Submission
```json
{
  "name": "Jane Doe",
  "email": "jane@example.com",
  "phone": "+62812345678",
  "message": "Inquiry about your services",
  "source": "contact_form"
}
```

### 4. Event Tracking
```json
{
  "event_type": "page_view",
  "user_id": "user123",
  "page_url": "/products/item-1",
  "referrer": "https://google.com",
  "user_agent": "Mozilla/5.0...",
  "timestamp": "2025-01-23T10:30:00Z"
}
```

## Integrasi dengan Sistem Lain

### Laravel Application
```php
<?php

use Illuminate\Support\Facades\Http;

$response = Http::withToken('your_api_token')
    ->post('https://yoursite.com/api/post/webhook-data', [
        'event_type' => 'order_created',
        'order_id' => 12345,
        'customer_id' => 67890,
        'amount' => 250000
    ]);

if ($response->successful()) {
    $data = $response->json();
    // Handle success
} else {
    // Handle error
}
```

### JavaScript/Node.js
```javascript
const axios = require('axios');

async function sendData(endpoint, data, token) {
    try {
        const response = await axios.post(
            `https://yoursite.com/api/post/${endpoint}`,
            data,
            {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            }
        );
        
        console.log('Data sent successfully:', response.data);
        return response.data;
    } catch (error) {
        console.error('Error sending data:', error.response?.data || error.message);
        throw error;
    }
}

// Usage
sendData('webhook-data', {
    event_type: 'user_action',
    user_id: 123,
    action: 'login',
    timestamp: new Date().toISOString()
}, 'your_api_token');
```

### Python
```python
import requests
import json
from datetime import datetime

def send_data(endpoint, data, token=None):
    url = f"https://yoursite.com/api/post/{endpoint}"
    headers = {'Content-Type': 'application/json'}
    
    if token:
        headers['Authorization'] = f'Bearer {token}'
    
    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error sending data: {e}")
        raise

# Usage
data = {
    'sensor_id': 'TEMP_001',
    'temperature': 23.5,
    'humidity': 65.0,
    'timestamp': datetime.now().isoformat()
}

result = send_data('iot-sensor', data, 'your_api_token')
print(f"Data sent: {result}")
```

## FAQ

**Q: Apakah bisa menggunakan metode selain POST?**
A: Tidak, POST-Only Receiver hanya menerima metode POST untuk keamanan dan konsistensi.

**Q: Berapa batas maksimal size data yang bisa dikirim?**
A: Default Laravel adalah 2MB, bisa dikonfigurasi di php.ini atau server config.

**Q: Apakah bisa auto-create table dengan relasi?**
A: Saat ini hanya support table sederhana. Untuk relasi kompleks, buat table manual.

**Q: Bagaimana cara backup data yang masuk?**
A: Data disimpan di database biasa, gunakan backup database reguler.

**Q: Apakah ada limit jumlah receiver yang bisa dibuat?**
A: Tidak ada limit hard-coded, tergantung kapasitas server dan database.

---

**Dibuat:** 23 Januari 2025  
**Versi:** 1.0  
**Tim:** API Management System Development 