Base URL & health
Semua path di bawah ditempel ke base URL. /health terbuka tanpa API key untuk monitoring.
curl https://otp.husenbot.my.id/health
{
"ok": true,
"service": "otp-api",
"uptime": 123
}
Autentikasi
Setiap request ke /v1/* wajib membawa API key, dan harus datang dari IP web server yang terdaftar di ALLOWED_IPS.
X-API-Key: <API_KEY>
# atau
Authorization: Bearer <API_KEY>
Simpan key di environment variable server (OTP_API_KEY). Jangan pernah taruh di kode browser.
HMAC signature (opsional, disarankan)
Kalau server OTP diberi API_SECRET, setiap request juga wajib membawa X-Timestamp dan X-Signature. Signature mencegah request diubah atau diputar ulang.
bodyHash = SHA256_HEX(raw_body)
canonical = <timestamp>.<METHOD>.<PATH>.<bodyHash>
signature = HMAC_SHA256_HEX(API_SECRET, canonical)
X-Timestamp: <unix detik>
X-Signature: sha256=<signature>
Kirim OTP
Membuat kode baru, membatalkan kode lama untuk nomor yang sama, lalu mengirimnya ke WhatsApp user.
| Field | Tipe | Wajib | Keterangan |
|---|---|---|---|
phone | string | ya | Nomor HP Indonesia: 08xx, 628xx atau +628xx |
purpose | string | tidak | Default verification. Huruf, angka, _ atau -, maks 32 |
curl -X POST https://otp.husenbot.my.id/v1/otp/send \
-H "Content-Type: application/json" \
-H "X-API-Key: $OTP_API_KEY" \
-d '{"phone":"081234567890","purpose":"verification"}'
const res = await fetch(`${process.env.OTP_API_URL}/v1/otp/send`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": process.env.OTP_API_KEY,
},
body: JSON.stringify({ phone: "081234567890" }),
});
const data = await res.json();
{
"ok": true,
"requestId": "b7a1c0e2-...",
"phone": "+6281234567890",
"purpose": "verification",
"expiresIn": 300,
"resendAfter": 60,
"provider": "fonnte"
}
Verifikasi OTP
Mencocokkan kode dengan OTP terakhir yang masih berlaku untuk nomor dan purpose itu. Kode yang benar langsung hangus setelah dipakai.
| Field | Tipe | Wajib | Keterangan |
|---|---|---|---|
phone | string | ya | Sama dengan nomor saat kirim |
code | string | ya | 4–10 digit angka |
purpose | string | tidak | Harus sama dengan saat kirim |
curl -X POST https://otp.husenbot.my.id/v1/otp/verify \
-H "Content-Type: application/json" \
-H "X-API-Key: $OTP_API_KEY" \
-d '{"phone":"081234567890","code":"123456"}'
const res = await fetch(`${process.env.OTP_API_URL}/v1/otp/verify`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": process.env.OTP_API_KEY,
},
body: JSON.stringify({ phone: "081234567890", code: "123456" }),
});
const data = await res.json(); // data.verified === true jika benar
200 Benar
verified: true, plus requestId dan phone.
400 Salah
INVALID_CODE dengan sisa attemptsRemaining.
410 Kedaluwarsa
OTP_EXPIRED. Minta kode baru.
429 Habis percobaan
TOO_MANY_ATTEMPTS. Minta kode baru.
Format & kode error
Semua error memakai bentuk yang sama. Tampilkan error.message ke user, pakai error.code untuk logika.
{
"ok": false,
"error": {
"code": "INVALID_CODE",
"message": "Kode OTP salah atau sudah tidak berlaku",
"attemptsRemaining": 4
}
}
| HTTP | Code | Artinya |
|---|
Error 429 dari /send membawa retryAfter (detik). Tampilkan hitung mundur ke user, jangan retry otomatis.
Integrasi Next.js
Dua route handler di server (App Router) meneruskan request ke OTP API. Browser hanya memanggil route kamu sendiri.
1. Environment
OTP_API_URL=https://otp.husenbot.my.id
OTP_API_KEY=isi-api-key-dari-server
2. app/api/otp/send/route.ts
import { NextResponse } from "next/server";
const BASE = process.env.OTP_API_URL!;
const KEY = process.env.OTP_API_KEY!;
export async function POST(request: Request) {
const { phone } = await request.json();
const res = await fetch(`${BASE}/v1/otp/send`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": KEY,
},
body: JSON.stringify({ phone }),
cache: "no-store",
});
const data = await res.json();
return NextResponse.json(data, { status: res.status });
}
3. app/api/otp/verify/route.ts
import { NextResponse } from "next/server";
const BASE = process.env.OTP_API_URL!;
const KEY = process.env.OTP_API_KEY!;
export async function POST(request: Request) {
const { phone, code } = await request.json();
const res = await fetch(`${BASE}/v1/otp/verify`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": KEY,
},
body: JSON.stringify({ phone, code }),
cache: "no-store",
});
const data = await res.json();
// Verifikasi sukses -> buat session/login di sini.
return NextResponse.json(data, { status: res.status });
}
4. Komponen client
"use client";
import { useState } from "react";
export default function OtpForm() {
const [phone, setPhone] = useState("");
const [code, setCode] = useState("");
const [step, setStep] = useState<"phone" | "code">("phone");
const [msg, setMsg] = useState("");
async function sendOtp() {
const res = await fetch("/api/otp/send", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ phone }),
});
const data = await res.json();
if (res.ok) {
setStep("code");
setMsg("Kode dikirim. Cek WhatsApp kamu.");
} else {
setMsg(data.error?.message ?? "Gagal mengirim OTP");
}
}
async function verifyOtp() {
const res = await fetch("/api/otp/verify", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ phone, code }),
});
const data = await res.json();
if (res.ok && data.verified) {
setMsg("Nomor terverifikasi");
// redirect / simpan status verifikasi di server
} else {
setMsg(data.error?.message ?? "Kode salah");
}
}
return (
<div>
{step === "phone" ? (
<>
<input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="08xxxxxxxxxx" />
<button onClick={sendOtp}>Kirim OTP</button>
</>
) : (
<>
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="123456" />
<button onClick={verifyOtp}>Verifikasi</button>
</>
)}
<p>{msg}</p>
</div>
);
}
Node.js + HMAC signature
Satu helper untuk kedua endpoint. Signature otomatis ditambahkan kalau OTP_API_SECRET diisi.
import { createHash, createHmac } from "node:crypto";
const BASE = process.env.OTP_API_URL;
const API_KEY = process.env.OTP_API_KEY;
const API_SECRET = process.env.OTP_API_SECRET; // kosongkan jika tidak dipakai
async function callOtp(path, body) {
const rawBody = JSON.stringify(body);
const timestamp = Math.floor(Date.now() / 1000);
const headers = {
"content-type": "application/json",
"x-api-key": API_KEY,
};
if (API_SECRET) {
const bodyHash = createHash("sha256").update(rawBody).digest("hex");
const canonical = `${timestamp}.POST.${path}.${bodyHash}`;
const signature = createHmac("sha256", API_SECRET).update(canonical).digest("hex");
headers["x-timestamp"] = String(timestamp);
headers["x-signature"] = `sha256=${signature}`;
}
const res = await fetch(`${BASE}${path}`, {
method: "POST",
headers,
body: rawBody,
});
return { status: res.status, data: await res.json() };
}
// Kirim
await callOtp("/v1/otp/send", { phone: "081234567890" });
// Verifikasi
await callOtp("/v1/otp/verify", { phone: "081234567890", code: "123456" });
Batas & keamanan
Batas ini melindungi user dari spam dan kamu dari tagihan pesan yang membengkak.
| Aturan | Default | Env |
|---|---|---|
| Masa berlaku OTP | 300 detik | OTP_TTL_SECONDS |
| Percobaan verifikasi | 5× | OTP_MAX_ATTEMPTS |
| Jeda kirim ulang | 60 detik | OTP_RESEND_COOLDOWN_SECONDS |
| Kirim per nomor / jam | 3× | OTP_MAX_SENDS_PER_HOUR |
| Kirim per nomor / hari | 10× | OTP_MAX_SENDS_PER_DAY |
| Kuota harian service | 500 | DAILY_SEND_LIMIT |
| Kirim per IP / menit | 30 | RATE_LIMIT_IP_PER_MINUTE |
- Kode OTP disimpan sebagai HMAC-SHA256, bukan plaintext.
- Kode lama otomatis tidak berlaku saat kirim ulang.
- ALLOWED_IPS aktif: hanya IP web server terdaftar yang bisa memanggil /v1.
- Aktifkan API_SECRET (HMAC) sebelum production.
- Jangan log kode OTP di aplikasi kamu.
- Pasang HTTPS. Jangan kirim API key lewat HTTP publik.
Troubleshooting
401 UNAUTHORIZED
API key salah atau tidak terkirim. Pastikan header X-API-Key terisi tanpa spasi atau newline.
403 IP_NOT_ALLOWED
Request datang dari IP yang tidak terdaftar. Cek IP keluar web server dengan curl ifconfig.me, lalu minta admin menambahkannya.
401 INVALID_SIGNATURE
Canonical harus persis timestamp.METHOD.PATH.bodyHash, dengan raw body sama persis seperti yang dikirim. Toleransi timestamp 5 menit.
429 COOLDOWN
Pakai retryAfter dari response. Tampilkan tombol "kirim ulang dalam N detik", jangan retry otomatis.
Kode tidak masuk
- Cek provider di response dan status device di dashboard Fonnte.
- Pastikan nomor aktif dan punya WhatsApp.
- SMS_SEND_FAILED berarti masalah di provider, bukan di user.
debugCode tidak muncul
Memang benar. debugCode hanya ada saat SMS_PROVIDER=mock dan MOCK_EXPOSE_CODE=true.