APIMIDTRANS/API.md

258 lines
6.0 KiB
Markdown

Berikut adalah **Dokumentasi Teknis (API Documentation)** lengkap untuk integrasi **Middleware Payment Gateway** Anda.
Dokumentasi ini ditujukan untuk developer (Frontend/Backend) yang akan menghubungkan aplikasi lain (seperti Billing System, Toko Online, Aplikasi Donasi) ke gateway ini.
---
# 📚 Dokumentasi API Payment Gateway
**Version:** 1.0.0
**Base URL:** `http://ip-server-anda:5000` (Sesuaikan dengan IP/Domain VPS)
## 🔐 Autentikasi
Setiap request ke API ini **wajib** menyertakan kredensial otentikasi yang didapatkan dari **Dashboard Admin** (`Menu App Keys`).
Kredensial dikirim melalui **HTTP Headers**:
| Header Name | Value | Keterangan |
| --- | --- | --- |
| `X-App-Code` | `biling` (contoh) | Kode unik aplikasi klien |
| `X-Api-Key` | `fb93...` | Secret Key aplikasi klien |
---
## 🚀 Endpoints
### 1. Buat Transaksi (Create Transaction)
Membuat token pembayaran dan link redirect Snap Midtrans.
* **URL:** `/charge`
* **Method:** `POST`
* **Content-Type:** `application/json`
**Parameter Body (JSON):**
| Field | Tipe | Wajib? | Deskripsi |
| --- | --- | --- | --- |
| `order_id` | String | **Ya** | ID unik tagihan (misal: `INV-1001`) |
| `amount` | Integer | **Ya** | Nominal pembayaran (tanpa desimal) |
| `item_details` | Array | Tidak | Detail barang/jasa (lihat contoh) |
| `customer_details` | Object | Tidak | Data pelanggan (Nama, Email, HP) |
**Contoh Request:**
```json
{
"order_id": "INV-2025-001",
"amount": 150000,
"customer_details": {
"first_name": "Budi",
"last_name": "Santoso",
"email": "budi@example.com",
"phone": "08123456789"
},
"item_details": [
{
"id": "VPS-01",
"price": 150000,
"quantity": 1,
"name": "Cloud VPS Basic"
}
]
}
```
**Contoh Response Sukses (201 Created):**
```json
{
"redirect_url": "https://app.midtrans.com/snap/v4/redirection/0f8736b5-...",
"token": "0f8736b5-2f1f-40bd-b3ad-0ef0a06d3443"
}
```
> **Catatan:** Gunakan `redirect_url` untuk mengarahkan user ke halaman pembayaran, atau gunakan `token` jika Anda menggunakan Snap.js di frontend.
---
### 2. Cek Status Transaksi
Mengecek status pembayaran secara realtime ke Midtrans.
* **URL:** `/status/<order_id>`
* **Method:** `GET`
**Contoh Request:**
`GET /status/INV-2025-001`
**Contoh Response (200 OK):**
```json
{
"id": "e67a2012-3208-4b3e-...",
"transaction_status": "settlement",
"fraud_status": "accept",
"status_code": "200",
"status_message": "Success, transaction is found"
}
```
> **Status Penting:**
> * `settlement` / `capture`: Pembayaran Sukses.
> * `pending`: Menunggu pembayaran.
> * `expire`: Kadaluarsa.
> * `cancel` / `deny`: Gagal.
>
>
---
## 💻 Contoh Implementasi Code
Berikut adalah contoh cara menembak API ini menggunakan Python dan PHP.
### A. Python (Requests)
```python
import requests
import json
url = "http://localhost:5000/charge"
payload = {
"order_id": "TAGIHAN-001",
"amount": 50000,
"customer_details": {
"first_name": "Andri",
"email": "andri@indoweb.id",
"phone": "08123456789"
}
}
headers = {
'X-App-Code': 'biling',
'X-Api-Key': 'fb93b4e802314a189809f393d913bba6', # Ganti dengan API Key asli
'Content-Type': 'application/json'
}
try:
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 201:
data = response.json()
print("Link Bayar:", data['redirect_url'])
else:
print("Error:", response.text)
except Exception as e:
print(e)
```
### B. PHP (cURL)
Cocok untuk diintegrasikan ke WHMCS atau Billing berbasis PHP.
```php
<?php
$curl = curl_init();
$payload = [
"order_id" => "INV-" . time(),
"amount" => 100000,
"customer_details" => [
"first_name" => "Client",
"email" => "client@example.com"
]
];
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:5000/charge',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => array(
'X-App-Code: biling',
'X-Api-Key: fb93b4e802314a189809f393d913bba6',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpcode == 201) {
$data = json_decode($response, true);
echo "Silakan bayar di sini: " . $data['redirect_url'];
} else {
echo "Gagal membuat transaksi: " . $response;
}
?>
```
---
## ⚙️ Konfigurasi Server (Info Admin)
Informasi ini untuk Administrator Server Gateway.
**1. File Konfigurasi (`.env`)**
Lokasi: `/opt/midtrans_flask/.env`
Pastikan data berikut benar:
```ini
# Security App
SECRET_KEY=rahasia_negara_api_2025
# Midtrans Credentials (Dapat dari Dashboard Midtrans)
MIDTRANS_SERVER_KEY=Mid-server-YXLR8xjEkrISCXtlDvS7FDFX
MIDTRANS_CLIENT_KEY=Mid-client-j8BudqVadevtaNbQ
MIDTRANS_MERCHANT_ID=G996317131
# Mode Environment
# Ubah ke 'false' jika masih testing (Sandbox)
# Ubah ke 'true' jika sudah live (Production) - Uang Asli!
MIDTRANS_IS_PRODUCTION=true
```
**2. Cara Restart Service**
Jika Anda mengubah file `.env`, service harus direstart:
```bash
systemctl restart midtrans-gateway
```
**3. Logs**
Untuk melihat log transaksi atau error:
```bash
journalctl -u midtrans-gateway -f
# Atau jika manual:
tail -f /opt/midtrans_flask/app.log
```
---
## ⚠️ Troubleshooting Common Errors
| Status Code | Pesan Error | Penyebab & Solusi |
| --- | --- | --- |
| `401` | Unauthorized | **API Key/App Code salah.** Cek kembali header request Anda. |
| `400` | Bad Request | **Data JSON tidak valid.** Pastikan `order_id` unik dan `amount` berupa angka (integer). |
| `500` | Internal Server Error | **Masalah koneksi ke Midtrans.** Cek koneksi internet server atau Server Key Midtrans di `.env`. |
| `404` | Endpoint not found | **Salah URL.** Pastikan endpoint `/charge` atau `/status` benar. |