跳过导航
OTP24h
基于 HTTPS 的 JSON Bearer API 密钥 无需 SDK

API v1 文档

面向集成 OTP 号码租用的卖家。所有响应均为 JSON。

API 密钥 Webhook

基础 URL

https://otp24h.com/api/v1

所有调用均使用 JSON。所有操作都在此 URL 之下。


Authorization 请求头

Authorization: Bearer otp_live_EXAMPLE_NOT_A_REAL_KEY

Replace the example with your own key from API 密钥.

格式

JSON
请求与响应

身份验证

Bearer
请求头中的 API 密钥

默认限制

60 次请求/分钟
按每个 API 密钥计算

快速开始

购买号码、读取验证码、关闭订单。全程仅四步。

1

获取您的 API 密钥

Your account already has one API key at /account/api. It is shown once, so store it safely. Send it as a Bearer token on every call.

2

选择服务和国家

从 /api/v1/services 和 /api/v1/countries 读取代码,然后用 /api/v1/offers 查看价格和库存。

3

创建租用订单

使用渠道、服务和国家调用 POST /api/v1/rentals。添加 Idempotency-Key,重试时就不会重复扣费。

4

读取验证码,然后关闭订单

Poll GET /api/v1/rentals/{public_id} until otp_code appears, then call finish. No code in time means an automatic refund.

1简介与 Base URL

API v1 的请求和响应均使用 JSON。所有成功的响应格式为 {"success": true, "data": …};每个错误响应的格式为 {"success": false, "error": {"code": …, "message": …}}.

基础 URL:

https://otp24h.com/api/v1

本文档只描述 API 实际返回的内容。内部字段(提供商、成本价、利润、路由)永远不会出现在响应中。

2身份验证

所有端点都需要 API 密钥,请通过请求头发送:

http
Authorization: Bearer otp_live_EXAMPLE_NOT_A_REAL_KEY
  • Mỗi tài khoản có đúng một khóa API, có sẵn tại /account/api.
  • 密钥仅显示 一次 khi cấp (hoặc khi tạo lại). Hãy lưu ngay.
  • Khóa có đầy đủ quyền của API khách (đặt/hủy/kết thúc/xin mã, xem đơn, catalog, số dư).
  • 密钥可按以下方式限制 IP 白名单;来自其他 IP 的调用将被拒绝。
  • Muốn đổi khóa (lộ/ quên), bấm Tạo lại khóa — khóa cũ bị thu hồi ngay.
代码HTTP时间
UNAUTHORIZED401密钥缺失、错误、已被撤销或已过期。
ACCOUNT_BANNED403该密钥所属账户已被锁定。
EMAIL_NOT_VERIFIED403邮箱未验证的账户(当系统强制要求时)暂时无法创建订单。

3速率限制

限制计算依据 每个 API 密钥 在窗口内 60 秒:默认套餐 60 次请求/分钟,高级套餐 300 次请求/分钟。超出限制将返回 429 代码为 rate_limited.

目前 API 不会发送描述剩余额度的 header;收到 429. 时请自行放慢调用节奏

json
{"success": false, "error": {"code": "RATE_LIMITED", "message": "Too many requests. Please slow down."}}

4端点

以下所有路径均位于 /api/v1. Header Authorization 在所有端点上都是必需的。

GET/api/v1/meta

Thông tin phiên bản, định danh bản cài và những năng lực đang bật. Không tham số.

json
{"success": true, "data": {
  "protocol": "otp-aggregator",
  "api_version": "v1",
  "instance_id": "…",
  "capabilities": {"balance": true, "catalog": true, "services": true,
                   "countries": true, "domains": true, "offers": true,
                   "pricing": true, "availability": true, "rentals": true},
  "capability_list": ["sms", "email", "balance", "catalog", "cancel",
                      "finish", "next_code", "rentals"],
  "api": {"name": "OTP Aggregator Public API", "version": "v1", "major_version": 1},
  "instance": {"id": "…"},
  "capability_flags": {"balance": true, "catalog": true, "services": true,
                       "countries": true, "domains": true, "offers": true,
                       "pricing": true, "availability": true, "rentals": true},
  "server_time": "2026-11-10T09:14:53Z",
  "supported_channels": ["sms", "email"],
  "default_currency": "VND"
}}

capabilities là OBJECT cờ boolean như bản v1 đã công bố từ trước — giữ nguyên kiểu, không đổi thành danh sách. Trong đó rentals nay là true vì các route thuê số thật sự đang phục vụ. capability_list là DANH SÁCH năng lực bản cài này thật sự phục vụ, đọc từ chính các route đang chạy: sms/email (email chỉ xuất hiện khi catalogue có offer email còn hạn), balance, catalog, cancel, finish, next_code, rentals. Đây là trường mà adapter liên kết (OtpAggregatorAdapter) đọc để quyết định bật/tắt nút thao tác; adapter vẫn đọc được cả dạng danh sách cũ nếu gặp bạn liên kết chưa nâng cấp. capability_flags là bản sao của capabilities, giữ lại cho client đã cấu hình trước đây; instance_id 和 instance.id luôn bằng nhau. server_time 是服务器的 UTC 时间,后缀 Z.

GET/api/v1/balance

当前钱包余额。无参数。

json
{"success": true, "data": {"balance": "250000.0000", "currency": "VND"}}
GET/api/v1/services

服务列表。可选查询参数: channel (sms | email).

json
{"success": true, "data": {"services": [
    {"code": "telegram", "name": "Telegram", "channel": "sms"}
  ], "total": 1}}
GET/api/v1/countries

国家列表。无参数。

json
{"success": true, "data": {"countries": [
    {"code": "US", "iso2": "US", "name": "United States", "dial_code": "+1"}
  ], "total": 1}}

dial_code 可以是 null 如果该国家尚无拨号代码。 total 是下列字段中的元素数量 countries.

GET/api/v1/offers

按服务/国家的售价和库存。查询参数(均为可选): channel (sms | email), service_id (数字), country_id (数字)。

service_id / country_id 是 目录表的内部数字 id,不是字符串代码。传入非数字的值将返回 400 validation_error.

json
{"success": true, "data": {"offers": [
    {"service_code": "telegram", "country_code": "US", "channel": "sms",
     "price": "15000.0000", "currency": "VND", "available": 42}
  ], "total": 1}}

筛选条件 service_code / country_code 使用代码字符串,而非数字 id。 country_code 可以是 null 适用于未关联国家的 offer(邮箱渠道)。 available 是按已启用路由汇总的库存。

每一行还包含 tiers:该服务/国家下仍有库存的价格档位,按从低到高排序,每个档位包含 price_vnd、price_label、available、cheapest。把准确的 price_vnd 传给 POST /api/v1/rentals 即可购买该档位——被扣除的金额始终等于您所选的金额。

POST/api/v1/rentals

创建租用订单。JSON 请求体:

字段类型必填备注
channelstring是sms 或 email
service_codestring是验证码取自 /services
country_codestring具有 smsISO2 取自 /countries
domainstring具有 email服务的域名
price数字或字符串否所选价格档位的准确 price_vnd(见 tiers)。留空 = 最低档。该档位不再出售时返回 409 PRICE_CHANGED 并附带新的档位列表,不会扣款。

请求头支持 Idempotency-Key:重复发送 相同键 + 相同内容 将返回原订单(不会创建新订单,也不会第二次扣款)。相同键但内容不同的请求会被拒绝 409 idempotency_key_reused。一个密钥只能用于一个订单。

bash
curl -X POST https://otp24h.com/api/v1/rentals \
  -H "Authorization: Bearer otp_live_EXAMPLE_NOT_A_REAL_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 8f14e45f-ceea-467a-9f0b-1c2d3e4f5a6b" \
  -d '{"channel":"sms","service_code":"telegram","country_code":"US"}'
json
{"success": true, "data": {
  "rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB",
  "channel": "sms",
  "status": "waiting_code",
  "price": "15000.0000",
  "currency": "VND",
  "allocation": "+15550000001",
  "expires_at": "2026-11-05T12:30:00+00:00",
  "created_at": "2026-11-05T12:00:00+00:00",
  "service_code": "telegram",
  "country_code": "US"
}}

allocation 是分配给订单的号码/邮箱地址(不是提供商信息)。

GET/api/v1/rentals/{public_id}

您自己某个订单的状态。订单收到验证码后,响应中会额外包含 otp_code。他人的订单返回 404.

json
{"success": true, "data": {"rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB", "status": "code_received",
  "channel": "sms", "allocation": "+15550000001", "otp_code": "483920", …}}
POST/api/v1/rentals/{public_id}/cancel

请求取消订单。无请求体。如果订单已太晚,可能会被拒绝(409 cancel_denied).

json
{"success": true, "data": {"rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB", "status": "cancelled", …}}
POST/api/v1/rentals/{public_id}/finish

将订单标记为已使用完毕。无请求体。

json
{"success": true, "data": {"rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB", "status": "completed", …}}
POST/api/v1/rentals/{public_id}/another-code

为同一号码再请求一个验证码。无请求体。

json
{"success": true, "data": {"rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB", "status": "waiting_code", …}}
GET/api/v1/rentals

调用密钥所属账户的租号历史(同一账户的所有密钥看到同一份历史)。其他账户的订单绝不会出现,也没有任何参数可以指定别的用户。最新在前,使用游标分页。

  • ?limit= — 每页行数,默认 20,最多 100。
  • ?before_id= — 下一页游标:请原样传回 data.next_before_id (上一页返回的值)。不传则取第一页。
  • 列表中不返回验证码 —— 验证码只出现在状态接口 GET /api/v1/rentals/{public_id}.
  • 与状态接口共用轮询配额,因此翻历史不会占用下单配额。
bash
curl https://otp24h.com/api/v1/rentals?limit=20 \
  -H "Authorization: Bearer otp_live_EXAMPLE_NOT_A_REAL_KEY"
json
{"success": true, "data": {
  "rentals": [
    {"rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB", "status": "completed", "channel": "sms",
     "allocation": "+15550000001", "price": "1500.0000", "currency": "VND",
     "service_code": "telegram", "country_code": "US",
     "created_at": "2026-11-05T12:00:00+00:00", "expires_at": "2026-11-05T12:30:00+00:00"}
  ],
  "count": 1, "limit": 20, "has_more": false, "next_before_id": null
}}
POST/api/v1/webhooks/test

向自己的 webhook 发送一条已签名的测试事件,用于在依赖它之前检查签名与接收端。需要 webhook.test 权限。

Webhook 在 /account/webhooks 创建与管理;这里只用 endpoint_id 指定自己的 webhook。其他账户的 webhook 返回 404 —— 与不存在的 id 完全相同。

bash
curl -X POST https://otp24h.com/api/v1/webhooks/test \
  -H "Authorization: Bearer otp_live_EXAMPLE_NOT_A_REAL_KEY" \
  -H "Content-Type: application/json" \
  -d '{"endpoint_id": 12}'
json
{"success": true, "data": {"endpoint_id": 12, "event": "webhook.test", "status": "queued"}}

202 表示事件已进入队列,将像真实事件一样投递(相同签名、相同重试机制)。每个 webhook 每小时最多 5 次测试发送,超出返回 429。指向内网的 URL 会被立即拒绝(422),不会入队。

自动化工具 API

适用于 运行自动化工具的用户 (机器人、Selenium、Puppeteer、您自己的脚本)——无需成为代理商。工具发送 服务 和 国家,系统会租用号码(或邮箱)并返回 正确的 OTP 验证码 供您立即使用。所有功能共用账户的 API 密钥和钱包。

为什么分两步? 工具必须把手机号码(或邮箱)填入目标页面,这一步发生在验证码生成 之前 。步骤 1 (number)返回号码或邮箱;步骤 2 (code)等待并只返回验证码。

收到验证码时才扣费;没有验证码则自动退款,因此一次失败的运行不会花费分文。

准备工作

  • 在以下位置创建密钥: 账户 → API 密钥 并勾选这些权限 rental.create (获取号码), rental.read (获取验证码), rental.cancel (取消), rental.request_code (请求另一个验证码)。
  • 通过请求头发送密钥 Authorization: Bearer YOUR_KEY 或 X-API-Key: YOUR_KEY (推荐)。如果您的工具无法设置请求头,则仅 /api/v1/tool/* 接口组额外接受 ?api_key=YOUR_KEY ——此时密钥会出现在 URL 中,请仅在必要时使用此方式,并且不要分享该 URL。如果两者同时存在,始终优先使用请求头。
  • 服务使用 服务代码 (例如 telegram),国家使用 2 位 ISO 代码 (VN, US…);不区分大小写。列表见 服务.
  • format=json (默认)或 format=text:对于 text,响应正文只是值(OTP 验证码或状态关键字),不含 JSON。
GET/api/v1/tool/number

租用一个手机号码或一个邮箱地址。同样接受 POST 请求,参数相同。

参数描述
service必填。服务代码(或准确名称)。
country2 位 ISO 代码(或准确名称)。SMS 必填,邮箱渠道忽略。
channelsms (默认)或 email.
domain可选,仅用于邮箱:期望的域名。
max_price可选,单位 VND。当前价格更高时将拒绝请求,并 不会创建订单.
request_id可选,最多 64 个字符。使用相同的值和相同的参数再次调用,将重新得到 原来的那个订单,不会创建第二个订单(网络不稳定时也安全)。相同的值但参数不同,或该订单已关闭(已取消/已过期/已退款),将返回 REQUEST_ID_REUSED ——请使用 request_id 新值。第一次调用仍在执行时: 409 IDEMPOTENCY_IN_PROGRESS 并附带 Retry-After。如果上一次明确失败(未扣款):再次使用相同的 request_id 将创建新订单。
formatjson 或 text.
json
{"success": true,
 "id": "TqtGANIQW0RboqpqZVN8Wfu5vM",
 "channel": "sms",
 "number": "+84901234567",
 "email": null,
 "price": "250.0000",
 "expires_in": 3600}

对于邮箱: number 是 null 和 email 是分配到的地址。 format=text 返回一行 id|number (或 id|email). price 是订单的 VND 金额; expires_in 是剩余秒数(再次使用相同的 request_id).

当系统无法确定供应商是否已分配号码时,您会收到 202 PENDING_REVIEW 并附带 id (text: PENDING_REVIEW|id)。请不要创建新订单:该订单会被人工审核,您可以用 code 或 cancel 使用 id 该 id 查询。参数可以通过 query、表单 (application/x-www-form-urlencoded、multipart)或 JSON 发送。

GET/api/v1/tool/code

等待验证码并将其返回。参数: id (来自步骤 1), wait (秒,0–120,默认 0), format.

wait=0 只查询一次。 wait>0 保持连接并在验证码到达时立即返回(通常几秒内);超过 wait 用完仍未收到验证码,则返回 202 仍无验证码则返回 202,让您再次调用。等待期间,服务器 不会发送任何字节 ,因此请将工具端的超时设置得大于 wait。默认最长等待时间为 30 秒 (大于服务器上限的 wait 值会被收回到服务器上限)。在 another, code 之后, WAITING 会一直返回等待状态,直到 新的 验证码到达——绝不会返回旧验证码。

text
# format=text, mã đã về (HTTP 200): thân phản hồi CHỈ là mã
482913

# format=json
{"success": true, "status": "code_received", "otp": "482913"}

# chưa có mã khi hết wait (HTTP 202)
{"success": false, "status": "waiting"}      # text: WAITING
HTTP响应正文 (text)含义
200482913已收到验证码。
202WAITING还没有验证码——请再次调用。
202PENDING_REVIEW订单正在人工审核中。
410EXPIRED已过期,并已(或正在)退款。
410CANCELLED订单已取消(已退款或正在退款)。
410FAILED供应商未能提供号码;不扣费。
404NOT_FOUND您的账户中没有此订单。
429RATE_LIMITED调用 code 过于频繁。请等待 Retry-After.
429TOO_MANY_WAITS同一个密钥上同时等待的请求过多(最多 10 个)。请等待 Retry-After 秒。
GET/api/v1/tool/cancel

取消订单并退款(仅在仍可取消时)。参数: id, format。同样接受 POST.

成功: {"success": true, "status": "cancelled"} (text: CANCELLED)。正在退款: 202 {"success": true, "status": "cancelled_refund_pending"} (text: CANCELLED_REFUND_PENDING)。结果不确定: 202 PENDING_REVIEW。取消期间验证码已到达,无法取消: 409 CODE_ALREADY_RECEIVED。因其他原因无法取消: 409 NOT_CANCELLABLE。对已取消或已过期的订单再次取消,将返回与之前相同的结果(网络出错后重试是安全的)。

GET/api/v1/tool/another

为同一号码请求另一个验证码(免费,且订单已收到过一个验证码时)。参数: id, format。同样接受 POST.

成功: 202 {"success": true, "status": "waiting"} ——之后再次调用 code。订单正在等待新验证码时再次调用,同样返回 202 ,不会创建额外的请求。无法申请时: 409 CANNOT_REQUEST_ANOTHER.

租号错误

HTTP代码含义
404SERVICE_NOT_FOUND没有此服务。
404COUNTRY_NOT_FOUND没有此国家。
409NO_STOCK此服务和国家的号码已用完。
402INSUFFICIENT_BALANCE余额不足。
409PRICE_TOO_HIGH当前价格超过 max_price.
409PRICE_CHANGED您选择的价格档位已不再出售(价格变动或售罄)。不会扣款;响应中附带当前价格档位供重新选择。
429LIMIT_REACHED已达到活动订单的最大数量。
422INVALID_REQUEST缺少参数或参数无效。
409REQUEST_ID_REUSEDrequest_id 已用于不同的参数,或属于已关闭的订单。
409IDEMPOTENCY_IN_PROGRESS上一次使用相同 request_id 的调用仍在执行。请等待 Retry-After 秒后再调用。
409TRY_AGAIN目前无法冻结金额;请几秒后重试。
422AMBIGUOUS_SERVICE服务名称匹配多个服务;请使用服务代码。
202PENDING_REVIEW订单正在人工审核;响应体包含订单的 id 。

对于 format=text,错误响应正文就是上表中的错误码。

完整示例

bash
# 1. thuê số, rồi nhập số vào trang đích
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://otp24h.com/api/v1/tool/number?service=telegram&country=VN&request_id=run-001"
# {"success":true,"id":"ord_7Kx2","number":"+84901234567", ...}

# 2. chờ mã: câu trả lời chỉ là mã OTP
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://otp24h.com/api/v1/tool/code?id=ord_7Kx2&wait=60&format=text"
# 482913
python
import requests

API = "https://otp24h.com/api/v1/tool"
H = {"Authorization": "Bearer YOUR_API_KEY"}

n = requests.get(API + "/number", headers=H,
                 params={"service": "telegram", "country": "VN", "request_id": "run-001"}).json()
print(n["number"])            # nhập vào trang đích

r = requests.get(API + "/code", headers=H,
                 params={"id": n["id"], "wait": 60, "format": "text"})
if r.status_code == 200:
    print(r.text)             # 482913
else:
    print(r.text)             # WAITING / EXPIRED / CANCELLED ...
javascript
const API = "https://otp24h.com/api/v1/tool";
const H = { Authorization: "Bearer YOUR_API_KEY" };

const n = await (await fetch(
  `${API}/number?service=telegram&country=VN&request_id=run-001`, { headers: H })).json();
console.log(n.number);        // nhập vào trang đích

const r = await fetch(`${API}/code?id=${n.id}&wait=60&format=text`, { headers: H });
console.log(r.status, await r.text());   // 200 482913

注意

  • 每个密钥同时最多保持 10 个等待请求(wait);超出将收到 429 TOO_MANY_WAITS。等待期间,系统会自动向供应商查询——工具无需频繁调用。
  • 为每次运行使用 request_id ,这样即使误重发也不会被重复计费。
  • 您的工具需要其他格式(例如某个软件专有的协议)?请通过页脚的支持渠道联系我们:我们可按需定制专用 API。 申请定制 API

可运行的代码示例

下面四段代码只做三件事:下单、等待验证码、结束订单。它们不是伪代码 —— tests/Api/ApiExamplesTest.php 会把每一次调用与 routes/api.php、ScopeEnforcementService 实际要求的权限、RentalInput 校验器以及已公布的响应契约逐一对照,因此偏离 API 的代码会让测试变红。

php
<?php
// POST /api/v1/rentals  ->  poll GET /api/v1/rentals/{id}  ->  POST .../finish
$base  = 'https://your-install.example';
$token = getenv('OTP_API_KEY');          // otp_live_...

function call(string $method, string $url, string $token, ?array $body = null, ?string $idem = null): array
{
    $headers = ["Authorization: Bearer {$token}", 'Accept: application/json'];

    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }

    if ($idem !== null) {
        $headers[] = "Idempotency-Key: {$idem}";
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => 30,
    ]);

    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_SLASHES));
    }

    $raw = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    return [$status, json_decode((string) $raw, true)];
}

// 1. create
[$status, $created] = call('POST', "{$base}/api/v1/rentals", $token, [
    'channel'      => 'sms',
    'service_code' => 'facebook',
    'country_code' => 'VN',
], 'order-' . bin2hex(random_bytes(8)));

if ($status !== 201) {
    exit("create failed: {$status} " . json_encode($created));
}

$id = $created['data']['rental_id'];

// 2. poll — its own rate budget, so polling never blocks the next create
for ($i = 0; $i < 60; $i++) {
    [$status, $state] = call('GET', "{$base}/api/v1/rentals/{$id}", $token);

    if ($status === 429) {
        sleep((int) ($state['retry_after'] ?? 2));
        continue;
    }

    if (($state['data']['status'] ?? '') === 'code_received') {
        echo "OTP: " . ($state['data']['otp_code'] ?? '(none)') . PHP_EOL;
        break;
    }

    sleep(2);
}

// 3. finish
[$status, $done] = call('POST', "{$base}/api/v1/rentals/{$id}/finish", $token);
echo "finish: {$status}" . PHP_EOL;
python
import os, time, json, urllib.request, urllib.error

BASE = "https://your-install.example"
TOKEN = os.environ["OTP_API_KEY"]

def call(method, path, body=None, idem=None):
    headers = {"Authorization": f"Bearer {TOKEN}", "Accept": "application/json"}
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    if idem:
        headers["Idempotency-Key"] = idem

    req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return r.status, json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b"{}")

status, created = call("POST", "/api/v1/rentals", {
    "channel": "sms", "service_code": "facebook", "country_code": "VN",
}, idem="order-" + os.urandom(8).hex())

if status != 201:
    raise SystemExit(f"create failed: {status} {created}")

rid = created["data"]["rental_id"]

for _ in range(60):
    status, state = call("GET", f"/api/v1/rentals/{rid}")
    if status == 429:
        time.sleep(int(state.get("retry_after", 2)))
        continue
    if state.get("data", {}).get("status") == "code_received":
        print("OTP:", state["data"].get("otp_code"))
        break
    time.sleep(2)

status, _ = call("POST", f"/api/v1/rentals/{rid}/finish")
print("finish:", status)
javascript
const BASE = 'https://your-install.example';
const TOKEN = process.env.OTP_API_KEY;

async function call(method, path, body, idem) {
  const headers = { Authorization: `Bearer ${TOKEN}`, Accept: 'application/json' };

  if (body !== undefined) headers['Content-Type'] = 'application/json';
  if (idem) headers['Idempotency-Key'] = idem;

  const res = await fetch(BASE + path, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
  });

  const text = await res.text();
  return [res.status, text ? JSON.parse(text) : {}];
}

const [createStatus, created] = await call('POST', '/api/v1/rentals', {
  channel: 'sms', service_code: 'facebook', country_code: 'VN',
}, 'order-' + crypto.randomUUID());

if (createStatus !== 201) throw new Error(`create failed: ${createStatus}`);

const id = created.data.rental_id;

for (let i = 0; i < 60; i++) {
  const [status, state] = await call('GET', `/api/v1/rentals/${id}`);

  if (status === 429) {
    await new Promise((r) => setTimeout(r, (state.retry_after ?? 2) * 1000));
    continue;
  }

  if (state.data?.status === 'code_received') {
    console.log('OTP:', state.data.otp_code);
    break;
  }

  await new Promise((r) => setTimeout(r, 2000));
}

const [finishStatus] = await call('POST', `/api/v1/rentals/${id}/finish`);
console.log('finish:', finishStatus);
bash
BASE="https://your-install.example"
TOKEN="$OTP_API_KEY"

# 1. create — the Idempotency-Key makes a retry safe
CREATE=$(curl -sS -X POST "$BASE/api/v1/rentals" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-$(openssl rand -hex 8)" \
  -d '{"channel":"sms","service_code":"facebook","country_code":"VN"}')

echo "$CREATE"

ID=$(echo "$CREATE" | sed -n 's/.*"rental_id":"\([^"]*\)".*/\1/p')

# 2. poll (own rate budget: 240/min by default)
curl -sS "$BASE/api/v1/rentals/$ID" -H "Authorization: Bearer $TOKEN"

# 3. finish
curl -sS -X POST "$BASE/api/v1/rentals/$ID/finish" -H "Authorization: Bearer $TOKEN"

# 4. history of THIS key, newest first, 20 per page
curl -sS "$BASE/api/v1/rentals?limit=20" -H "Authorization: Bearer $TOKEN"

创建步骤返回 201 是正确的(不是 200)。等待过程中,429 只表示"慢一点" —— 读取 Retry-After 后重新调用,不要新建订单。

5租用订单生命周期

API 实际返回的状态(没有其他内部状态):

状态含义已结束?
已创建订单刚创建,尚未分配号码。否
保留中正在冻结资金并申请号码。否
waiting_code已分配号码,正在等待验证码。否
code_received已收到验证码(见 otp_code).否
已完成订单已使用完毕。是
已取消已取消(如有则附带退款)。是
expired已过期,未收到验证码。是
失败无法在供应商一侧创建订单。是
refund_pending等待退款。否
manual_review正在人工处理。否
轮询建议: 调用 GET /api/v1/rentals/{public_id} 每 5 秒 前 2 分钟内,之后每 15 秒。当状态为 completed, cancelled, expired 或 failed (或当已有 otp_code)。轮询间隔请勿短于 1 秒/次,否则会触发速率限制。

6错误代码

所有错误均返回 {"success": false, "error": {"code": …, "message": …}}。下表列出了 API 可能返回的全部公开错误码,没有其他错误码。

错误结构可能附带另外两个字段 可选: error.field (被拒绝的字段名,仅当错误由提交的数据引起时才有)和 error.incident_id (服务器端错误时的查询码——请将此码提供给客服)。它们绝不包含内部细节。

代码HTTP消息
validation_error 422 The submitted data is invalid.
account_banned 403 Access denied.
email_not_verified 403 Please verify your email address before continuing.
unauthorized 401 Not authenticated.
forbidden 403 Access denied.
csrf_token_mismatch 403 Your session expired. Please reload the page and try again.
service_unavailable 503 The service is temporarily unavailable. Please try again later.
insufficient_balance 402 Insufficient balance. Please top up your wallet.
insufficient_funds 402 Insufficient balance. Please top up your wallet.
no_numbers_available 503 目前没有可用号码。请稍后再试或选择其他价格档位。
all_providers_failed 503 目前没有可用号码。请稍后再试或选择其他价格档位。
no_route 503 目前没有可用号码。请稍后再试或选择其他价格档位。
provider_unavailable 503 Service temporarily unavailable. Please try again later.
routing_unavailable 503 Service temporarily unavailable. Please try again later.
rental_not_found 404 Rental not found.
not_found 404 The requested resource was not found.
method_not_allowed 405 This method is not allowed for the requested resource.
provider_unknown 409 The request is being confirmed. Please check again shortly.
invalid_state 409 Cannot perform this action in the current state.
state_conflict 409 The rental changed state. Please refresh and try again.
cancel_denied 409 Cannot cancel — too late or already processing.
already_finished 409 该号码已结束,无法再获取验证码。订单已标记为完成。
provider_rejected 409 该号码无法再获取验证码。
request_failed 503 暂时无法请求新的验证码,请稍后再试。
cancel_ambiguous 409 The cancellation is being confirmed. Please check again shortly.
refund_pending 409 Cancellation confirmed. The refund is being processed.
rate_limited 429 Too many requests. Please slow down.
too_many_active_orders 429 You already have too many rentals in progress. Finish or cancel some before renting again.
idempotency_key_reused 409 This idempotency key was already used with a different request.
idempotency_in_progress 409 A request with this idempotency key is still being processed.
payment_method_disabled 503 This payment method is currently unavailable.
payment_not_configured 503 This payment method is currently unavailable.
payment_already_pending 409 You already have an invoice waiting for payment.
amount_out_of_range 422 The submitted amount is not accepted.
amount_decimals 422 Enter an amount with at most 2 decimals.
invalid_request 422 The request is invalid.
request_id_reused 409 This request_id cannot be reused: it was used with different parameters or belongs to a closed order.
service_not_found 404 The requested service was not found.
country_not_found 404 The requested country was not found.
domain_unavailable 404 The requested email domain is not available.
no_stock 409 No numbers are available for this request right now.
price_too_high 409 The current price exceeds the requested maximum.
price_changed 409 您选择的价格已不可用,请重新选择。
limit_reached 429 Too many rentals are already in progress.
not_cancellable 409 This rental cannot be cancelled in its current state.
expired 410 This rental has expired.
cancelled 410 This rental was cancelled.
pending_review 202 This rental is being reviewed manually.
cannot_request_another 409 Another code cannot be requested in the current state.
too_many_waits 429 Too many code waits are already running for this key.
waiting 202 The code is not ready yet.
try_again 409 Could not reserve the amount, try again.
code_already_received 409 The code already arrived, so the rental cannot be cancelled.
failed 410 This rental failed.
ambiguous_service 422 More than one service matches that name; use its code instead.
too_many_pending_same_amount 422 您已达到此金额待处理充值的最大数量。
too_many_pending 422 您已有 3 张未支付发票。请先支付一张或等待其过期后再创建新发票。
pending_exists 409 您有一张未支付的 Binance Pay 发票。请先支付或等待其过期。
name_in_use 409 该 Binance 名称正被另一张未支付的发票使用。请几分钟后重试,或使用其他 Binance 名称。
payment_busy 503 Too many requests right now. Please try again in a moment.
routing_loop 409 This request cannot be routed: it would return to a server it already visited.
max_upstream_hops 409 This request cannot be routed: it has passed too many servers.
federation_error 409 This request cannot be routed between servers.
internal_error 500 An internal error occurred. Please try again later.

too_many_active_orders 表示你同时有太多未结束的订单。此限制由运营方为每个账户设定;请在你的账户页面查看当前数值或咨询支持人员。请等待部分订单完成/取消后再重试。

7卖家 Webhook

注册并管理于 /account/webhooks:添加接收地址、选择事件、启用/停用、轮换密钥、发送测试以及重新发送失败的投递。

事件

  • rental.created — 当订单转入相应状态时。
  • rental.code_received — 当订单转入相应状态时。
  • rental.completed — 当订单转入相应状态时。
  • rental.cancelled — 当订单转入相应状态时。
  • rental.expired — 当订单转入相应状态时。
  • rental.failed — 当订单转入相应状态时。
  • webhook.test — 测试投递,仅包含 {"event":"webhook.test","created_at":…}.

Payload 结构

json
{"event": "rental.completed",
 "id": "rental.completed:12345",
 "timestamp": 1793906237,
 "data": {"rental_id": "01HZX8K4Q7Y2V5N6M3P8R9T0AB", "channel": "sms",
          "status": "completed", "completed_at": "2026-11-05T12:00:00Z"}}

data 仅包含订单的公开信息(订单号、渠道、状态、售价、货币、时间、部分隐藏的号码/邮箱)。不含任何内部信息。

发出的请求头

http
Content-Type: application/json
X-Webhook-Signature: <timestamp>.<base64(HMAC-SHA256)>

签名 = base64(hmac_sha256(timestamp + "." + raw body, secret)),使用确切的密钥 whsec_… 你在创建 webhook 时获得的(仅显示一次)。时间戳为 Unix 秒;如果偏差超过 300 秒 以防止重放。

验证签名

php
<?php
$secret  = 'whsec_EXAMPLE';                 // your webhook secret
$header  = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$rawBody = file_get_contents('php://input');

[$ts, $sig] = array_pad(explode('.', $header, 2), 2, '');
if (abs(time() - (int) $ts) > 300) { http_response_code(400); exit; }

$expected = base64_encode(hash_hmac('sha256', $ts . '.' . $rawBody, $secret, true));
if (!hash_equals($expected, $sig)) { http_response_code(401); exit; }

http_response_code(200);
python
import base64, hashlib, hmac, time

secret = b"whsec_EXAMPLE"
header = request.headers.get("X-Webhook-Signature", "")
raw_body = request.get_data()                      # bytes THÔ, chưa parse JSON
ts, sig = (header.split(".", 1) + ["", ""])[:2]

if abs(time.time() - int(ts)) > 300:
    return "", 400

expected = base64.b64encode(
    hmac.new(secret, ts.encode() + b"." + raw_body, hashlib.sha256).digest()
).decode()

if not hmac.compare_digest(expected, sig):
    return "", 401

return "", 200
node
const crypto = require('crypto');

const secret = 'whsec_EXAMPLE';
const header = req.headers['x-webhook-signature'] || '';
const rawBody = req.rawBody;                       // chuỗi THÔ, chưa parse JSON
const [ts, sig] = header.split('.');

if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) return res.sendStatus(400);

const expected = crypto.createHmac('sha256', secret).update(ts + '.' + rawBody).digest('base64');

const a = Buffer.from(expected);
const b = Buffer.from(sig || '');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return res.sendStatus(401);

res.sendStatus(200);

重试、超时和手动重发

  • 每次投递最多尝试 5 次,间隔 1 分钟、5 分钟、15 分钟、1 小时、6 小时.
  • 每次调用的超时时间为 10 秒.
  • 响应 2xx = 已发送完成。临时错误(超时、429, 5xx)会重试;永久错误(400/401/403/404/409/422)将立即标记为失败。
  • 5 次仍失败后,投递将转为 failed。修复你的服务器后,请前往 /account/webhooks 点击 重新发送 (每个 webhook 每小时最多 10 次)。
  • 如果响应带有响应头 Retry-After (收到 429 时),系统会遵循该值(最长 1 小时)。

按 event_id 幂等

id 在 payload 中是事件的稳定代码(例如 rental.completed:12345)。网络可能导致同一事件到达 两次:请保存 id 已处理,再次遇到时跳过,避免重复记账。

接收地址的技术要求

  • 仅接受 https://;请勿使用 http://.
  • 不要使用内部地址, localhost,或私有 IP —— 系统会拦截以保护服务器。
  • 不要嵌入登录凭据 (user:pass@)或符号 # 在 URL 中。
  • 每个账户最多 5 webhook。

订单事件每约 15 秒批量扫描一次,发送有独立周期:一个 Webhook 最多可能延迟 约 45 秒 相对于事件发生的时间。在你创建 webhook 之前发生的事件不会被重新发送。

8变更日志

每次更改 外部可见 都在此有一行记录,按日期降序排列。变更类型: added (新增), changed (行为变更), fixed (修复), deprecated (即将弃用), removed (已移除)。

透明 v1 我们不会重命名或移除已公布的字段。新增字段属于兼容性变更——仍会记录在此,方便您了解并读取。

日期版本类型变更
2026-11-29v1added GET /api/v1/countries: mỗi quốc gia có thêm trường code — đúng giá trị tham số country= chấp nhận (mã ISO nếu có, nếu không là mã tên quốc gia). iso2 giữ nguyên, có thể là null với quốc gia chưa có mã ISO.
2026-11-26v1added GET /api/v1/domains — danh sách miền email đang còn hàng, mỗi mục chỉ có trường domain. Không lộ nguồn cấp hay giá vốn. Dùng làm nguồn cho ô chọn miền ở kênh email.
2026-11-26v1added POST /api/v1/rentals: trường domain trên kênh email giờ là TUỲ CHỌN. Bỏ trống nghĩa là "miền rẻ nhất còn hàng"; chỉ định thì lọc cứng, và miền không có hàng trả 404 DOMAIN_UNAVAILABLE (không trừ tiền, không gọi hệ thống bên ngoài).
2026-11-25v1added POST /api/v1/webhooks/test —— 向调用密钥所属账户的 webhook 发送一条已签名的 webhook.test 事件。请求体 {"endpoint_id": 12}(或表单形式 endpoint_id)。返回 202 及 data.endpoint_id、data.event、data.status(queued)—— 事件已入队,由 worker 像真实事件一样投递。需要新权限 webhook.test;每个 webhook 每小时最多 5 次。越权访问返回 404,webhook 已停用返回 409,内网 URL 返回 422。
2026-11-25v1added GET /api/v1/rentals —— 调用密钥所属账户的租号历史,游标分页。返回 data.rentals[],DTO 形状与状态接口一致(无内部字段、无成本价、无路由评分),并带 data.count、data.limit、data.has_more 与 data.next_before_id(下一页游标;结束时为 null)。参数:?limit=(默认 20,最多 100)与 ?before_id=。需要 rental.read 权限。此接口不返回验证码 —— 验证码只在状态接口返回。
2026-11-25v1changed 轮询限流。GET /api/v1/rentals/{id} 与 GET /api/v1/rentals 使用独立配额(默认每密钥每分钟 240 次,可在 Admin → 安全 → API 调整),因此每秒轮询的工具不再耗尽写入接口每分钟 60 次的额度。超过阈值返回 429 并带 Retry-After。
2026-11-23v1fixed GET /api/v1/meta trả đúng hợp đồng liên kết: thêm protocol, api_version, instance_id 和 capability_list — DANH SÁCH năng lực thật của bản cài (cancel/finish/next_code/rentals nay bật đúng, không còn cứng rentals=false). capabilities GIỮ NGUYÊN kiểu object cờ boolean như bản v1 đã công bố (chỉ giá trị rentals đổi thành true); capability_flags vẫn là bản sao của object đó. Không xoá trường nào, không đổi kiểu trường nào.
2026-11-16v1added 租号时可选择价格档位:/api/v1/offers 新增 tiers 数组,POST /api/v1/rentals 新增可选字段 price。所选档位不再出售时返回 409 PRICE_CHANGED,且不会扣款。原有字段保持不变。
2026-11-15v1added 自动化工具 API(number、code、cancel、another):与现有 API 密钥及 rental.* 权限共用;另可在 URL 中使用 api_key、format=text、用于防重复创建的 request_id 以及 max_price。
2026-11-10v1fixed 此前系统发放的部分订单号短于 26 个字符;现在 所有验证码均可使用。此前在你读取状态、取消、完成或请求另一个验证码时,这些验证码会被判定为“无效”,尽管正是系统把它们发给了你。新发放的验证码始终为 26 个字符。
2026-11-10v1added 锁定当前响应契约:全部 42 个响应分支(10 个端点,含错误分支)的结构已被抓取并由测试锁定。此后任何字段名称 / 类型 / 出现顺序的变更,都必须在此表中附上一行记录。
2026-11-10v1fixed expires_at 和 created_at 在租用订单响应中始终是 UTC 时间,采用 ISO-8601 格式并带有后缀 +00:00,即使服务器设置了其他时区也是如此。此前这些值按错误的时区读取,导致时间偏差。
2026-11-09v1fixed 资金链路和订单链路中途发生的错误(包括 PHP 系统错误,而不仅是异常)现在始终返回符合约定的 JSON 错误结构,不再出现空白页或堆栈跟踪。返回的状态码仍为 internal_error.
2026-11-06v1added 每个账户未结束订单数上限:超出上限将返回 429 too_many_active_orders (独立代码,不合并到 invalid_state)和 否 调用供应商。
2026-11-06v1added 卖家 Webhook:注册地址 /account/webhooks,签名 X-Webhook-Signature,重新发送失败的投递。详情见第 7. 节
2026-11-05v1changed 开启“停止接收新任务”模式后, POST /api/v1/rentals 返回 503 附带 header Retry-After。订单的读取、取消、完成和获取验证码端点 已有 仍正常运行。
2026-11-03v1changed 邮箱未验证的账户(当运营方开启强制验证时)会收到 403 email_not_verified (创建订单时);所有读取操作不受限制。
2026-11-03v1changed 所有公开错误代码均使用 一个 固定的消息语句,绝不包含内部细节。完整的表格在第 6 节,那里列出了 API 可能返回的全部错误码。

合约锁定版本: 2026-11-10。本页面与锁定版本必须是同一天 —— 不一致时测试会失败。

9变更 / 版本

当前版本为 v1 (/api/v1)。在整个 v1, 期间,我们 不重命名或移除字段 已发布;变更只会新增字段。任何破坏兼容性的变更都将在下一个大版本中发布。

更多问题:请直接联系你的支持人员。密钥和 webhook:请参见 /account/api 和 /account/webhooks.

客服支持