本指南會為 Next.js App Router 應用程式打造手機 OTP 登入:使用者輸入手機號碼,在 KakaoTalk 收到 6 位數驗證碼,輸入後即完成登入。秘密金鑰由您的伺服器保管,並透過 Server Actions 與 K-OTP 溝通,因此瀏覽器永遠看不到金鑰,您的後端也能信任驗證結果。
整個流程都可以用測試金鑰開發與測試:不會傳送任何訊息,也不會使用點數。
事前準備
- 使用 App Router 的 Next.js 15 或以上版本應用程式(範例已針對 Next.js 16 做過型別檢查)。
- 一個 K-OTP 帳號。在主控台開啟您的應用程式,前往 API keys,切換到 Test 分頁並建立測試金鑰。請使用
sk_test_秘密金鑰。 @k-otp/sdk2.1.0 與server-only:
npm install @k-otp/sdk server-only
將金鑰放進 .env.local。它沒有 NEXT_PUBLIC_ 前綴,因此只會留在伺服器上:
K_OTP_SECRET_KEY=sk_test_...
流程如何運作
sendCode(phoneNumber)以用途("login")與冪等鍵呼叫issue。K-OTP 會產生驗證碼,並透過 KakaoTalk AlimTalk 傳送。- 您的伺服器儲存待完成的登入資訊:電話號碼、冪等鍵,以及
issue回傳的issueId。 verifyCode(code)以該issueId呼叫verify。驗證碼錯誤屬於正常結果(附帶reasonCode的verified: false),而不是例外。預設情況下,驗證碼的有效期限為 3 分鐘,最多可嘗試 5 次。
1. 伺服器用戶端
// lib/otp.ts
import "server-only";
import { createOtpServerClient } from "@k-otp/sdk/server";
// The key is read when a request is made, so a missing variable fails that request, not the build.
export const otp = createOtpServerClient({
apiKey: () => process.env.K_OTP_SECRET_KEY ?? "",
});
createOtpServerClient 只接受 sk_ 金鑰。請只從伺服器端程式碼匯入它:若有用戶端元件匯入此檔案,server-only 會讓建置失敗。
2. 待完成的登入資訊存放在哪裡
只有當驗證結果與驗證碼所傳送到的電話號碼綁定時,結果才有意義。請將這個綁定關係保存在伺服器上,而不是存在瀏覽器可以竄改的 Cookie 中。此範例使用以 session id 為鍵的記憶體內 map;請換成您的 session 儲存區或資料庫(Map 在重新啟動後就會遺失,也不會在多個執行個體之間共用)。
// lib/pending-otp.ts
import "server-only";
export type PendingOtp = {
phoneNumber: string;
/** Saved before calling issue and reused when the same send is retried. */
idempotencyKey: string;
/** Set once issue succeeded. */
issueId?: string;
/** When the last code was sent (epoch ms), for the resend cooldown. */
sentAt?: number;
};
// Example only: one process, lost on restart. Use your session store or database instead.
const store = new Map<string, PendingOtp>();
export const pendingOtp = {
get: async (sessionId: string) => store.get(sessionId),
set: async (sessionId: string, value: PendingOtp) => {
store.set(sessionId, value);
},
delete: async (sessionId: string) => {
store.delete(sessionId);
},
};
3. Server Actions:傳送與驗證
// app/login/actions.ts
"use server";
import { randomUUID } from "node:crypto";
import { isAmbiguousIssueError } from "@k-otp/sdk";
import { createIdempotencyKey, getIssueRequestErrorCode, isOtpApiError } from "@k-otp/sdk/server";
import { parseOtpPhoneNumber } from "@k-otp/sdk/ui";
import { cookies } from "next/headers";
import { otp } from "@/lib/otp";
import { type PendingOtp, pendingOtp } from "@/lib/pending-otp";
import { signIn } from "@/lib/session"; // your own session code
const RESEND_COOLDOWN_MS = 30_000;
export type SendCodeResult =
| { ok: true; expiresAt: string; resendInMs: number }
| {
ok: false;
error: "INVALID_PHONE" | "COOLDOWN" | "RATE_LIMITED" | "RETRY" | "UNAVAILABLE";
retryInMs?: number;
};
export type VerifyCodeResult =
| { ok: true }
| {
ok: false;
error: "NO_CODE" | "MISMATCH" | "NEW_CODE_NEEDED" | "RATE_LIMITED" | "RETRY";
attemptsRemaining?: number;
retryInMs?: number;
};
async function getSessionId() {
const jar = await cookies();
const existing = jar.get("otp_sid")?.value;
if (existing) return existing;
const sessionId = randomUUID();
jar.set("otp_sid", sessionId, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
return sessionId;
}
export async function sendCode(input: string): Promise<SendCodeResult> {
// Korean mobile numbers only: "010-1234-5678" -> "01012345678", anything else -> undefined.
const phoneNumber = parseOtpPhoneNumber(input).value;
if (!phoneNumber) return { ok: false, error: "INVALID_PHONE" };
// Add your own abuse checks here (CAPTCHA, limits per user or IP).
const sessionId = await getSessionId();
const previous = await pendingOtp.get(sessionId);
if (previous?.sentAt && previous.phoneNumber === phoneNumber) {
const waitMs = previous.sentAt + RESEND_COOLDOWN_MS - Date.now();
if (waitMs > 0) return { ok: false, error: "COOLDOWN", retryInMs: waitMs };
}
// Retrying a send that never got an answer (same number, no issueId yet): reuse its key.
// Anything else is a new attempt with a new key.
const pending: PendingOtp =
previous && !previous.issueId && previous.phoneNumber === phoneNumber
? previous
: { phoneNumber, idempotencyKey: createIdempotencyKey("login") };
await pendingOtp.set(sessionId, pending); // save the key BEFORE calling issue
try {
const result = await otp.issue({
phoneNumber: pending.phoneNumber,
purpose: "login",
idempotencyKey: pending.idempotencyKey,
});
await pendingOtp.set(sessionId, { ...pending, issueId: result.issueId, sentAt: Date.now() });
return { ok: true, expiresAt: result.expiresAt, resendInMs: RESEND_COOLDOWN_MS };
} catch (error) {
if (!isOtpApiError(error)) throw error;
if (isAmbiguousIssueError(error)) {
// The code may already be on its way. Keep the key: a retry is replayed, not sent again.
if (error.code === "TOO_MANY_REQUESTS") {
return { ok: false, error: "RATE_LIMITED", retryInMs: error.retryAfterMs ?? 30_000 };
}
return { ok: false, error: "RETRY" };
}
// A definite rejection: nothing was sent, and the next send gets a new key.
await pendingOtp.delete(sessionId);
const requestError = getIssueRequestErrorCode(error); // e.g. TEMPLATE_NOT_AVAILABLE
if (!requestError && error.code === "BAD_REQUEST") return { ok: false, error: "INVALID_PHONE" };
// PAYMENT_REQUIRED (out of credit), UNAUTHORIZED, FORBIDDEN, ...: your problem, not the user's.
console.error("K-OTP issue failed", requestError ?? error.code, error.requestId);
return { ok: false, error: "UNAVAILABLE" };
}
}
export async function verifyCode(code: string): Promise<VerifyCodeResult> {
const sessionId = await getSessionId();
const pending = await pendingOtp.get(sessionId);
if (!pending?.issueId) return { ok: false, error: "NO_CODE" };
if (!/^\d{6}$/.test(code)) return { ok: false, error: "MISMATCH" };
try {
const result = await otp.verify({ issueId: pending.issueId, code });
// ALREADY_VERIFIED: an earlier verify of this session succeeded but its answer was lost.
if (result.verified || result.reasonCode === "ALREADY_VERIFIED") {
await pendingOtp.delete(sessionId);
await signIn(pending.phoneNumber);
return { ok: true };
}
if (result.reasonCode === "MISMATCH") {
return { ok: false, error: "MISMATCH", attemptsRemaining: result.attemptsRemaining };
}
return { ok: false, error: "NEW_CODE_NEEDED" }; // EXPIRED, MAX_ATTEMPTS, REPLACED, NOT_FOUND
} catch (error) {
if (!isOtpApiError(error)) throw error;
if (error.code === "TOO_MANY_REQUESTS") {
return { ok: false, error: "RATE_LIMITED", retryInMs: error.retryAfterMs ?? 30_000 };
}
console.error("K-OTP verify failed", error.code, error.requestId);
return { ok: false, error: "RETRY" }; // verify is safe to retry
}
}
signIn 代表您自己的 session 程式碼:請在那裡為通過驗證的電話號碼建立 session。
冪等鍵,逐步說明
issue 會傳送真實的訊息並使用點數,因此 SDK 要求每次呼叫都必須帶有冪等鍵。sendCode 中的規則如下:
- 每次發送嘗試一個鍵。 由
createIdempotencyKey("login")產生,並在呼叫issue之前先儲存。 - 結果不明,沿用同一個鍵。 在逾時、網路錯誤、
503或429之後,驗證碼可能已經在路上了。isAmbiguousIssueError(error)正好在這些情況下回傳true。待完成的登入資訊會保留它的鍵,因此當使用者再次按下按鈕時,K-OTP 會重播第一次的結果,而不會傳送第二則訊息或重複收費。 - 結果明確,換一個新鍵。 在成功或被拒絕(
400、401、402、403、409)之後,下一次發送就是新的嘗試。電話號碼變更也算是新的嘗試:以不同的內容重複使用同一個鍵,會被以409 CONFLICT拒絕。
請留意匯入來源:isAmbiguousIssueError 來自 @k-otp/sdk;伺服器用戶端與其他輔助函式則來自 @k-otp/sdk/server。
使用者能自行處理的錯誤
TOO_MANY_REQUESTS(429):觸發了頻率限制。error.retryAfterMs會告訴您需要等待多久;表單會把它轉換成倒數計時。BAD_REQUEST(400):通常是號碼有問題。getIssueRequestErrorCode(error)可以區分出請求層級的代碼(CHANNEL_NOT_SUPPORTED、TEMPLATE_NOT_AVAILABLE、WEB_OTP_NOT_SUPPORTED),這些是您請求本身的錯誤,而不是使用者輸入的問題。PAYMENT_REQUIRED(402):您的組織點數已用完。這不是使用者的錯:請顯示一般性的訊息,並通知您自己。
重新傳送的冷卻時間是在伺服器上強制執行的(此處為 30 秒),因此即使有人直接呼叫 action 也一樣有效。Server Actions 是公開的端點:請在註解標示的地方加入您自己的濫用防護機制。
4. 表單
表單會呼叫這兩個 action,並使用 @k-otp/sdk/ui/react 的 OtpCodeInput,這是一個 headless 的分格驗證碼輸入框,支援貼上、鍵盤導覽與 autocomplete="one-time-code"。它不需要金鑰:它只負責編輯一個值。
// app/login/login-form.tsx
"use client";
import { OtpCodeInput } from "@k-otp/sdk/ui/react";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { type SendCodeResult, type VerifyCodeResult, sendCode, verifyCode } from "./actions";
type SendError = Extract<SendCodeResult, { ok: false }>["error"];
type VerifyError = Extract<VerifyCodeResult, { ok: false }>["error"];
const SEND_ERRORS: Record<SendError, string> = {
INVALID_PHONE: "Check the mobile number.",
COOLDOWN: "Please wait before requesting another code.",
RATE_LIMITED: "Too many requests. Please wait a moment.",
RETRY: "We could not confirm the code was sent. Try again.",
UNAVAILABLE: "Sending codes is unavailable right now. Please try later.",
};
const VERIFY_ERRORS: Record<VerifyError, string> = {
NO_CODE: "Request a code first.",
MISMATCH: "Wrong code.",
NEW_CODE_NEEDED: "This code can no longer be used. Request a new one.",
RATE_LIMITED: "Too many attempts. Please wait a moment.",
RETRY: "Something went wrong. Try again.",
};
export function LoginForm() {
const router = useRouter();
const [phoneNumber, setPhoneNumber] = useState("");
const [code, setCode] = useState("");
const [codeSent, setCodeSent] = useState(false);
const [message, setMessage] = useState("");
const [waitUntil, setWaitUntil] = useState(0);
const [now, setNow] = useState(() => Date.now());
const [isPending, startTransition] = useTransition();
// Tick once a second while a cooldown runs.
useEffect(() => {
if (waitUntil <= now) return;
const timer = setTimeout(() => setNow(Date.now()), 1000);
return () => clearTimeout(timer);
}, [waitUntil, now]);
const waitSeconds = Math.max(0, Math.ceil((waitUntil - now) / 1000));
const send = () =>
startTransition(async () => {
const result = await sendCode(phoneNumber);
setNow(Date.now());
if (result.ok) {
setCodeSent(true);
setCode("");
setWaitUntil(Date.now() + result.resendInMs);
setMessage("We sent a code by KakaoTalk.");
return;
}
if (result.retryInMs) setWaitUntil(Date.now() + result.retryInMs);
setMessage(SEND_ERRORS[result.error]);
});
const verify = (value: string) =>
startTransition(async () => {
const result = await verifyCode(value);
if (result.ok) {
router.push("/");
return;
}
setCode("");
if (result.retryInMs) {
setNow(Date.now());
setWaitUntil(Date.now() + result.retryInMs);
}
const left = result.attemptsRemaining;
setMessage(`${VERIFY_ERRORS[result.error]}${left ? ` ${left} attempts left.` : ""}`);
});
return (
<form onSubmit={(event) => event.preventDefault()}>
<label htmlFor="phone">Mobile number</label>
<input
id="phone"
type="tel"
autoComplete="tel"
value={phoneNumber}
onChange={(event) => setPhoneNumber(event.target.value)}
/>
<button type="button" onClick={send} disabled={isPending || waitSeconds > 0}>
{waitSeconds > 0 ? `Resend in ${waitSeconds}s` : codeSent ? "Resend code" : "Send code"}
</button>
{codeSent && (
<OtpCodeInput
aria-label="Verification code"
locale="en"
value={code}
onValueChange={setCode}
onComplete={verify}
readOnly={isPending}
autoFocus
/>
)}
<p role="status">{message}</p>
</form>
);
}
// app/login/page.tsx
import { LoginForm } from "./login-form";
export default function LoginPage() {
return (
<main>
<h1>Log in</h1>
<LoginForm />
</main>
);
}
這個元件沒有任何樣式。如需預設外觀,請匯入 @k-otp/sdk/ui/theme.css,或自行為 data-k-otp 屬性設定樣式;請參閱 UI 元件。
在測試模式中試用
使用 sk_test_ 金鑰時,K-OTP 不會傳送任何訊息,也不會使用點數。它只接受測試號碼,號碼的最後兩位數會決定情境,而所有測試驗證碼都是 000000。
010-0000-0000:驗證碼視為已送達,輸入000000即可登入。010-0000-0005:每組驗證碼都是錯的,因此您會看到剩餘次數逐漸減少。010-0000-0006:回傳429,因此按鈕會顯示 60 秒倒數。010-0000-0007:回傳402,因此使用者會看到一般性的「Sending codes is unavailable right now. Please try later.」訊息,而您的伺服器日誌會記錄這個錯誤。010-0000-0009:回傳503,因此使用者會看到「We could not confirm the code was sent. Try again.」。再次按下傳送時,會以相同的鍵重試,而不是開始一次新的發送。
以測試金鑰搭配真實號碼時,會被以 400(TEST_NUMBER_REQUIRED)拒絕,表單會將其顯示為「Check the mobile number.」。主控台的 Test inbox 會列出您的測試發送紀錄。所有情境都收錄在測試模式指南中。
正式上線前
- 在正式環境中,將
sk_test_換成正式的sk_金鑰。正式金鑰會拒絕測試號碼。 - 傳送幾組真實的驗證碼到團隊成員的手機上。每次正式發送使用 1 點;驗證呼叫免費。
- 將待完成的登入狀態移到您的 session 儲存區或資料庫。
- 在
sendCode前面保留您自己的濫用防護機制。
想用現成的表單?
@k-otp/sdk/ui/react 的 OtpForm 會呈現完整的流程(電話號碼欄位、傳送與重新傳送、驗證碼輸入框、倒數計時、訊息),並以 pk_ 公開金鑰直接從瀏覽器呼叫 K-OTP。這樣設定起來更快,但瀏覽器端的驗證只會告訴瀏覽器驗證碼相符。如果您的伺服器要依此授予存取權限,請在伺服器上以 getStatus({ issueId }) 與 sk_ 金鑰再確認一次。上述由伺服器主導的流程則可以省去這個步驟。