用 Node.js 接收短信验证码
下面是使用 Node.js 18 及更高版本内置的 fetch 调用 Turonay 短信验证 API 的完整示例:购买号码,轮询短信验证码,然后完成或取消激活。Turonay 使用 handler_api 协议,因此这段代码也兼容使用同一协议的机器人和库。
不需要任何 HTTP 包;我们只为 Webhook 接收端安装 Express。本页从余额查询开始,然后依次讲解用 async/await 写成的完整流程、JSON 接口、再请求一条短信、带签名验证的 Webhook,以及错误表。概览请见短信 API,参数详情请见API 参考。
前提条件
开始之前需要准备好三样东西:
- API 密钥:注册后可在个人资料中的 API 部分中找到。该密钥可以花费您的余额,因此只能在服务器端的 Node.js 代码中使用,从
process.env读取,切勿发送到浏览器。 - 余额:
getNumber会预留价格;金额以土耳其里拉 (TRY) 计。 - Node.js 18 或更高版本:
fetch和AbortSignal.timeout已内置。
EARLY_CANCEL_DENIED。设置:无需依赖
检查您的版本,并把密钥放入环境变量。只有在要运行 Webhook 接收端时才需要安装 express;API 调用不需要任何包。示例使用 CommonJS,因此也无需额外配置。
node --version # v18 or newer: fetch() is built in, no HTTP package needed
npm install express # only needed for the webhook receiver below
export TURONAY_API_KEY="paste-your-api-key-here"第一个请求:读取余额
最短的可运行示例是一次 getBalance 请求。该 API 使用 GET,并以纯文本而非 JSON 响应:成功为 ACCESS_BALANCE:125.4000,密钥错误则返回 BAD_KEY。不要调用 res.json();先读取 res.text() 并对其 trim()。
// balance.js - run with: node balance.js
const API = "https://turonay.com/stubs/handler_api.php";
async function main() {
const query = new URLSearchParams({
api_key: process.env.TURONAY_API_KEY,
action: "getBalance",
});
const res = await fetch(`${API}?${query}`, { signal: AbortSignal.timeout(20_000) });
const text = (await res.text()).trim(); // plain text, not JSON: "ACCESS_BALANCE:125.4000"
if (text.startsWith("ACCESS_BALANCE:")) {
console.log("Balance (TRY):", text.split(":")[1]);
} else {
console.log("Error:", text); // e.g. BAD_KEY
}
}
main();Node.js 完整流程:获取号码,等待验证码,结束
下面的脚本用 async/await 跑通整个生命周期。getNumber() 带价格上限 (maxPrice) 购买,waitForCode() 每 5 秒调用一次 getStatus,最长 20 分钟,并根据结果运行 finish() 或 cancel()。函数名与 Turonay 的 Node 参考客户端一致。请用 node sms-flow.js 运行。
// sms-flow.js - buy a number, wait for the SMS code, finish or cancel. Node 18+, no packages.
const API = "https://turonay.com/stubs/handler_api.php";
const API_KEY = process.env.TURONAY_API_KEY;
// The API answered with a plain-text error code (NO_BALANCE, NO_NUMBERS, ...).
class ApiError extends Error {}
// Network trouble, HTTP 429 or 5xx, NO_CONNECTION: safe to retry later.
class Transient extends ApiError {}
class CodeTimeout extends Error {}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function call(action, params = {}) {
const query = new URLSearchParams({ api_key: API_KEY, action });
for (const [key, value] of Object.entries(params)) {
if (value != null) query.set(key, String(value));
}
let res;
try {
res = await fetch(`${API}?${query}`, { signal: AbortSignal.timeout(20_000) });
} catch (err) {
throw new Transient(`network error: ${err.name}`); // never log the URL: it holds your api_key
}
if (res.status !== 200) throw new Transient(`HTTP ${res.status}`);
const text = (await res.text()).trim(); // always trim: bodies are plain text
if (text === "NO_CONNECTION") throw new Transient(text);
return text;
}
async function getBalance() {
const text = await call("getBalance");
if (!text.startsWith("ACCESS_BALANCE:")) throw new ApiError(text);
return text.split(":")[1];
}
// Returns [activationId, phone]. The price is only RESERVED here, not charged.
async function getNumber(service, country, maxPrice = null) {
const text = await call("getNumber", {
service,
country,
maxPrice: maxPrice == null ? null : maxPrice.toFixed(2),
});
const [tag, id, phone] = text.split(":");
if (tag === "ACCESS_NUMBER" && id && phone) return [id, phone];
throw new ApiError(text); // NO_BALANCE, NO_NUMBERS, BAD_SERVICE, WRONG_MAX_PRICE:<price> ...
}
// Returns ["wait" | "ok" | "cancel", code | null].
async function getStatus(id) {
const text = await call("getStatus", { id });
if (text.startsWith("STATUS_OK:")) return ["ok", text.slice("STATUS_OK:".length)];
if (text === "STATUS_CANCEL") return ["cancel", null];
if (text === "STATUS_WAIT_CODE" || text === "STATUS_WAIT_RESEND" || text.startsWith("STATUS_WAIT_RETRY:")) {
return ["wait", null]; // WAIT_RETRY carries the OLD code: still waiting for the new one
}
throw new ApiError(text); // NO_ACTIVATION, BAD_KEY ...
}
const setStatus = (id, status) => call("setStatus", { id, status });
const requestAnotherSms = (id) => setStatus(id, 3); // free, ACCESS_RETRY_GET
const finish = (id) => setStatus(id, 6); // ACCESS_ACTIVATION, only after a code
const cancel = (id) => setStatus(id, 8); // ACCESS_CANCEL / EARLY_CANCEL_DENIED
// Poll every `interval` seconds for at most `timeout` seconds (20 minutes).
async function waitForCode(id, { timeout = 1200, interval = 5 } = {}) {
const deadline = Date.now() + timeout * 1000;
let delay = interval;
while (Date.now() < deadline) {
try {
const [state, code] = await getStatus(id);
delay = interval;
if (state === "ok") return code;
if (state === "cancel") throw new ApiError("STATUS_CANCEL");
} catch (err) {
if (!(err instanceof Transient)) throw err;
delay = Math.min(delay * 2, 60); // back off on HTTP 429 / network trouble
}
await sleep(Math.max(0, Math.min(delay * 1000, deadline - Date.now())));
}
throw new CodeTimeout(`no SMS within ${timeout} seconds`);
}
async function main() {
const [service, country] = ["wa", "62"]; // WhatsApp, Turkey (see getPrices / getCountries)
let id;
let phone;
try {
console.log("Balance (TRY):", await getBalance());
[id, phone] = await getNumber(service, country, 15.0);
} catch (err) {
if (!(err instanceof ApiError)) throw err;
if (err instanceof Transient) console.error("Temporary problem, try again later:", err.message);
else if (err.message.startsWith("WRONG_MAX_PRICE")) console.error("Current price is above your limit:", err.message.split(":")[1] ?? "?");
else if (err.message === "NO_NUMBERS") console.error("No numbers in stock right now, try again in a minute");
else if (err.message === "NO_BALANCE") console.error("Not enough balance, top up first");
else console.error("API error:", err.message);
return 1;
}
console.log(`Use this number: ${phone} (activation ${id})`);
let code;
try {
code = await waitForCode(id);
} catch (err) {
if (err instanceof CodeTimeout) {
const reply = await cancel(id); // nothing is charged when no code arrived
if (reply !== "EARLY_CANCEL_DENIED") {
console.error("Timed out, activation cancelled:", reply);
return 1;
}
code = (await getStatus(id))[1]; // the code arrived in the last second
} else if (err instanceof ApiError) {
console.error("Activation cancelled:", err.message); // STATUS_CANCEL: nothing charged
return 1;
} else {
throw err;
}
}
console.log("SMS code:", code);
console.log(await finish(id)); // ACCESS_ACTIVATION
return 0;
}
main().then((status) => { process.exitCode = status; });脚本处理的情形:
- 如果当前价格超过
maxPrice,不会购买号码,并返回WRONG_MAX_PRICE:<price>;您可以从错误信息中读取当前价格。 NO_NUMBERS是暂时缺货,NO_BALANCE需要充值。网络错误、HTTP 429 和 5xx 会被标记为Transient,并在轮询循环内以加倍的间隔(最长 60 秒)重试。STATUS_WAIT_CODE和STATUS_WAIT_RETRY:<old code>都表示“继续等待”;后者带有上一条短信的验证码。- 20 分钟后,用 8 取消激活;如果验证码在最后一秒到达,会返回
EARLY_CANCEL_DENIED,并再次读取验证码。收到验证码后,用 6 结束该激活。
JSON 接口:getNumberV2 和 getStatusV2
如果想使用对象,getNumberV2 返回的 JSON 可用 JSON.parse 读取:activationId、phoneNumber、activationCost、currency、activationEndTime。验证码到达后,getStatusV2 返回包含 sms.code 和 sms.text 的 JSON。但 V2 上的错误代码同样是纯文本,并且在验证码出现之前,getStatusV2 返回的是纯文本状态,因此在 JSON.parse 失败时回退到文本的 try/catch 必不可少。activationEndTime 采用服务器时间(Europe/Istanbul,UTC+3),格式为 Y-m-d H:i:s,不含时区。
async function getNumberV2(service, country, maxPrice = null) {
const text = await call("getNumberV2", {
service,
country,
maxPrice: maxPrice == null ? null : maxPrice.toFixed(2),
});
try {
return JSON.parse(text); // activationId, phoneNumber, activationCost, activationEndTime ...
} catch {
throw new ApiError(text); // errors stay plain text, even in V2
}
}
// Object with the SMS once it arrived, otherwise the plain-text status (a string).
async function getStatusV2(id) {
const text = await call("getStatusV2", { id });
let data;
try {
data = JSON.parse(text);
} catch {
return text; // STATUS_WAIT_CODE, STATUS_WAIT_RETRY:<old>, STATUS_CANCEL ...
}
return { code: data?.sms?.code ?? null, text: data?.sms?.text ?? null };
}
(async () => {
const order = await getNumberV2("wa", "62", 15.0);
console.log(order.activationId, order.phoneNumber, order.activationCost, "until", order.activationEndTime);
})();再请求一条短信 (setStatus 3)
当您需要在同一号码上收一条新短信时,通过 setStatus 发送 3。这是免费的,每次激活只需付费一次。响应为 ACCESS_RETRY_GET,在新短信到达之前,getStatus 会返回 STATUS_WAIT_RETRY 以及旧验证码;waitForCode() 会把它视为等待。只有在最后一个验证码之后,才用 6 结束激活。下面的代码片段在 async 函数内运行。
// Inside an async function: you have a first code and need a second SMS on the same number (free).
const firstCode = await waitForCode(id);
const reply = await requestAnotherSms(id); // setStatus status=3 -> ACCESS_RETRY_GET
if (reply === "ACCESS_RETRY_GET") {
// While the new SMS is on its way getStatus answers STATUS_WAIT_RETRY:<first code>,
// which waitForCode() treats as "still waiting".
const secondCode = await waitForCode(id);
console.log("First:", firstCode, "Second:", secondCode);
}
await finish(id); // close only after the LAST codeWebhook 接收端:Express 与签名验证
如果您想要通知而不是轮询,请在个人资料中的 API 部分中设置一个 HTTPS Webhook 地址(域名,端口 443 或 8443)。当验证码到达 (code_received) 或激活被取消 (cancelled) 时,您会收到一条带签名的 JSON POST。请求头为 X-Turonay-Event、X-Turonay-Timestamp、X-Turonay-Signature 和 X-Turonay-Delivery,签名为 sha256= + HMAC-SHA256(secret, timestamp + "." + 原始正文)。
// webhook.js npm install express | TURONAY_WEBHOOK_SECRET=whsec_... node webhook.js
const crypto = require("node:crypto");
const express = require("express");
const SECRET = process.env.TURONAY_WEBHOOK_SECRET; // whsec_... from your profile page
const seen = new Set(); // demo only: use Redis/DB with a TTL
// sha256=HMAC_SHA256(secret, timestamp + "." + raw body), 5 minute replay window.
function verifyWebhookSignature(secret, timestamp, rawBody, signature, toleranceSec = 300) {
if (!/^[0-9]{1,12}$/.test(timestamp ?? "")) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSec) return false;
const expected = "sha256=" + crypto.createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from((signature ?? "").trim());
return a.length === b.length && crypto.timingSafeEqual(a, b); // constant time
}
const app = express();
// express.raw keeps the exact bytes; express.json() would re-serialise them.
app.post("/turonay/webhook", express.raw({ type: "*/*", limit: "64kb" }), (req, res) => {
if (!SECRET) return res.sendStatus(500);
const raw = req.body;
if (!Buffer.isBuffer(raw)) return res.sendStatus(400);
if (!verifyWebhookSignature(SECRET, req.get("X-Turonay-Timestamp"), raw, req.get("X-Turonay-Signature"))) {
return res.sendStatus(401);
}
let event;
try {
event = JSON.parse(raw.toString("utf8"));
} catch {
return res.sendStatus(400);
}
if (!seen.has(event.id)) { // retries repeat the same delivery id
seen.add(event.id);
if (event.event === "code_received") {
console.log("code", event.code, "for activation", event.activationId, event.phone);
} else if (event.event === "cancelled") {
console.log("activation", event.activationId, "cancelled, nothing charged");
}
}
res.sendStatus(200); // answer 2xx within 5 seconds
});
app.listen(8080, () => console.log("listening on :8080 (put HTTPS in front)"));在 Express 中最常见的错误是使用 express.json():正文一旦被解析并重新序列化,签名就不再匹配。请使用 express.raw() 获取原始的 Buffer。如果两个缓冲区长度不同,crypto.timingSafeEqual 会抛出异常,所以请先比较长度。拒绝早于 5 分钟的时间戳,在 5 秒内返回 2xx,并跳过您已经见过的 id(最多会重试 8 次)。详情请见Webhook。
错误代码
应用层错误以 HTTP 200 的纯文本形式到达;网络错误、429 和 5xx 在示例中会被转换为 Transient 类。下表列出了您可能在响应正文中看到的代码和建议的处理方式。
| 代码 | 含义 | 处理方式 |
|---|---|---|
BAD_KEY | API 密钥为空、错误或已被封锁。 | 请重新从个人资料中复制密钥,并确认两端没有残留空白字符。 |
NO_BALANCE | 您的可用余额低于号码的价格。 | 请为余额充值。已预留的金额会从可用余额中扣除。 |
NO_NUMBERS | 该服务和国家/地区目前没有库存(维护期间也会返回此结果)。 | 请几分钟后重试,或选择其他国家/地区。 |
BAD_SERVICE | 服务代码或国家/地区 ID 无效,或未开售。 | 请用 getPrices 和 getCountries 核对有效的代码。 |
WRONG_MAX_PRICE:<price> | 当前价格高于您的 maxPrice 限制(或该限制格式有误)。不会购买号码,也不会预留任何金额。 | 请读取冒号后面的当前价格;如果您接受,请提高上限后重试。 |
NO_ACTIVATION | 该激活 ID 不存在,或不属于您的账户。 | 请原样使用 getNumber 响应中返回的 ID。 |
BAD_STATUS | 状态无效,或在验证码到达之前就发送了 status=6。 | 请先等待验证码,并且只发送 1、3、6 或 8。 |
EARLY_CANCEL_DENIED | 取消被拒绝,因为验证码已经到达。 | 请用 getStatus 读取验证码,并用 6 结束该激活;扣费已最终确定。 |
NO_CONNECTION / HTTP 429 | 临时问题或触发请求频率限制。 | 请以逐渐增加的间隔(最长 60 秒)重试,并降低轮询频率。 |
STATUS_CANCEL | 该激活已被取消(由您或由供应方取消)。 | 请停止等待;不会扣费。如果仍需要号码,请重新购买。 |
把现有的 handler_api 客户端指向 Turonay
如果您有使用 handler_api 结构的 Node.js 机器人或库,可能无需重写:在大多数对接中,只需把基础 URL 设为 Turonay 的 /stubs/handler_api.php 地址,并把密钥设为您的 Turonay API 密钥。从 .env 文件或环境变量读取地址,可以让切换变成一行改动。
// Before: const BASE_URL = "https://provider.example.com/stubs/handler_api.php";
const BASE_URL = process.env.SMS_API_URL ?? "https://turonay.com/stubs/handler_api.php";
const API_KEY = process.env.SMS_API_KEY; // your Turonay API key
// Libraries and bots with a base-URL option need only these two values, e.g.:
// const client = new SomeHandlerApiClient({ apiKey: API_KEY, baseUrl: BASE_URL });请记住,价格以土耳其里拉计,并且服务代码和国家/地区 ID 必须与 getPrices 和 getCountries 的输出一致。价格请见API 价格。
常见问题
如何在 Node.js 中使用兼容 handler_api 的 API?
Turonay 使用 handler_api 协议。借助内置的 fetch,您向 API 地址发送带有 api_key 和 action 参数的 GET 请求,并解析纯文本响应。如果您已在使用某个库,只需更改基础 URL 和密钥。
我需要 axios 或 node-fetch 吗?
不需要。fetch 已内置于 Node.js 18 及更高版本。如果您更喜欢 axios,逻辑保持不变;只需记得把响应当作纯文本而不是 JSON 来读取。
如果短信没到,会扣费吗?
不会。getNumber 只预留价格,扣费发生在短信验证码到达时。如果您在验证码到达前取消,或超过 20 分钟,预留会被释放。
为什么 Webhook 需要 express.raw?
签名是针对请求正文的确切字节计算的。当 express.json() 解析并重新序列化正文时,空白和字段顺序可能发生变化,导致签名验证失败。请先验证原始正文,再把它转换为 JSON。
可以在同一号码上再收一条短信吗?
可以。通过 setStatus 发送 status=3,即可在同一号码上请求新的短信。这是免费的,每次激活只需付费一次。收到最后一个验证码后,用 status=6 结束该激活。