用 Python 接收短信验证码
本指南提供一份可直接复制的 Python 示例,跑通 Turonay 短信验证的完整流程:购买号码,等待短信验证码,打印出来,然后完成激活,或在超时时取消。Turonay 使用 handler_api 协议,因此同样的代码也适用于按该协议编写的机器人和库。
本页按步骤展开:前提条件、余额查询、完整流程、JSON (V2) 接口、第二条短信、带签名验证的 Webhook,以及错误代码。一般介绍请见短信 API,各个接口的详细说明请见API 参考。
开始之前
运行示例需要三样东西:
- Turonay 账户和 API 密钥:注册后,从个人资料中的 API 部分复制您的密钥。请把它放在服务器的环境变量中,切勿放进浏览器或移动应用里。
- 余额:调用
getNumber会从您的余额中预留号码的价格。所有金额均以土耳其里拉 (TRY) 计。 - Python 3.8 或更高版本,以及
requests库。
EARLY_CANCEL_DENIED)。安装:virtualenv 和 requests
创建虚拟环境并安装唯一的依赖。Flask 只在后面的 Webhook 接收端才需要,如果您只调用 API,可以跳过。示例从 TURONAY_API_KEY 环境变量读取您的 API 密钥。
python3 -m venv .venv && source .venv/bin/activate
pip install requests # HTTP client used for every API call
pip install flask # 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。请始终对响应正文执行 strip(),因为它可能以换行符结尾。
import os
import requests
API = "https://turonay.com/stubs/handler_api.php"
resp = requests.get(
API,
params={"api_key": os.environ["TURONAY_API_KEY"], "action": "getBalance"},
timeout=20,
)
text = resp.text.strip() # plain text, not JSON: "ACCESS_BALANCE:125.4000"
if text.startswith("ACCESS_BALANCE:"):
print("Balance (TRY):", text.split(":", 1)[1])
else:
print("Error:", text) # e.g. BAD_KEYPython 完整流程:获取号码,等待短信验证码
下面的脚本跑通整个生命周期。get_number 带价格上限 (maxPrice) 购买号码,wait_for_code 每 5 秒调用一次 getStatus,最长 20 分钟,并根据结果调用 finish 或 cancel。函数名与 Turonay 的 Python 参考客户端一致,因此以后把示例放进您自己的类里很容易。
#!/usr/bin/env python3
"""sms_flow.py - buy a number, wait for the SMS code, finish or cancel. pip install requests"""
import os
import sys
import time
from decimal import Decimal
import requests
API = "https://turonay.com/stubs/handler_api.php"
API_KEY = os.environ["TURONAY_API_KEY"]
class ApiError(Exception):
"""The API answered with a plain-text error code (NO_BALANCE, NO_NUMBERS, ...)."""
class Transient(ApiError):
"""Network trouble, HTTP 429 or 5xx, NO_CONNECTION: safe to retry later."""
def call(action, **params):
query = {k: v for k, v in params.items() if v is not None}
query.update(api_key=API_KEY, action=action)
try:
resp = requests.get(API, params=query, timeout=20)
except requests.RequestException as exc:
# Do not chain the original error: its message contains your api_key.
raise Transient("network error: " + type(exc).__name__) from None
if resp.status_code != 200:
raise Transient("HTTP %d" % resp.status_code)
text = resp.text.strip() # always strip: bodies are plain text
if text == "NO_CONNECTION":
raise Transient(text)
return text
def get_balance():
text = call("getBalance")
if not text.startswith("ACCESS_BALANCE:"):
raise ApiError(text)
return Decimal(text.split(":", 1)[1])
def get_number(service, country, max_price=None):
"""Returns (activation_id, phone). The price is only RESERVED here, not charged."""
text = call("getNumber", service=service, country=country,
maxPrice=None if max_price is None else "%.2f" % max_price)
parts = text.split(":")
if parts[0] == "ACCESS_NUMBER" and len(parts) >= 3 and parts[1] and parts[2]:
return parts[1], parts[2]
raise ApiError(text) # NO_BALANCE, NO_NUMBERS, BAD_SERVICE, WRONG_MAX_PRICE:<price> ...
def get_status(activation_id):
"""Returns ("wait" | "ok" | "cancel", code_or_None)."""
text = call("getStatus", id=activation_id)
if text.startswith("STATUS_OK:"):
return "ok", text.split(":", 1)[1]
if text == "STATUS_CANCEL":
return "cancel", None
if text in ("STATUS_WAIT_CODE", "STATUS_WAIT_RESEND") or text.startswith("STATUS_WAIT_RETRY:"):
return "wait", None # WAIT_RETRY carries the OLD code: still waiting for the new one
raise ApiError(text) # NO_ACTIVATION, BAD_KEY ...
def set_status(activation_id, status):
return call("setStatus", id=activation_id, status=status)
def request_another_sms(activation_id):
return set_status(activation_id, 3) # free, ACCESS_RETRY_GET
def finish(activation_id):
return set_status(activation_id, 6) # ACCESS_ACTIVATION, only valid after a code
def cancel(activation_id):
return set_status(activation_id, 8) # ACCESS_CANCEL, or EARLY_CANCEL_DENIED after a code
def wait_for_code(activation_id, timeout=1200, interval=5):
"""Poll every `interval` seconds for at most `timeout` seconds (20 minutes)."""
deadline = time.monotonic() + timeout
delay = interval
while time.monotonic() < deadline:
try:
state, code = get_status(activation_id)
delay = interval
if state == "ok":
return code
if state == "cancel":
raise ApiError("STATUS_CANCEL")
except Transient:
delay = min(delay * 2, 60) # back off on HTTP 429 / network trouble
time.sleep(max(0, min(delay, deadline - time.monotonic())))
raise TimeoutError("no SMS within %d seconds" % timeout)
def main():
service, country = "wa", "62" # WhatsApp, Turkey (see getPrices / getCountries)
try:
print("Balance (TRY):", get_balance())
activation_id, phone = get_number(service, country, max_price=15.00)
except Transient as exc:
sys.exit("Temporary problem, try again later: %s" % exc)
except ApiError as exc:
reason = str(exc)
if reason.startswith("WRONG_MAX_PRICE"):
print("Current price is above your limit:", reason.partition(":")[2] or "?")
elif reason == "NO_NUMBERS":
print("No numbers in stock right now, try again in a minute")
elif reason == "NO_BALANCE":
print("Not enough balance, top up first")
else:
print("API error:", reason)
sys.exit(1)
print("Use this number: %s (activation %s)" % (phone, activation_id))
try:
code = wait_for_code(activation_id)
except TimeoutError:
reply = cancel(activation_id) # nothing is charged when no code arrived
if reply != "EARLY_CANCEL_DENIED":
sys.exit("Timed out, activation cancelled: %s" % reply)
code = get_status(activation_id)[1] # the code arrived in the last second
except ApiError as exc: # STATUS_CANCEL: the supplier cancelled, nothing charged
sys.exit("Activation cancelled: %s" % exc)
print("SMS code:", code)
print(finish(activation_id)) # ACCESS_ACTIVATION
if __name__ == "__main__":
main()脚本做出的判断如下:
- 您通过
maxPrice设置价格上限。如果当前价格更高,不会购买号码,并返回WRONG_MAX_PRICE:<current price>,您可以用新的上限重试。 NO_NUMBERS(无库存)是暂时的,请几分钟后重试;NO_BALANCE表示您需要充值。STATUS_WAIT_CODE和STATUS_WAIT_RETRY:<old code>都表示“仍在等待”。后者带有上一条短信的验证码,不要把它误认为新验证码。- 时间用尽时,脚本通过
setStatus发送8。如果验证码恰好在最后一秒到达,API 会返回EARLY_CANCEL_DENIED,脚本会再读取一次验证码并完成任务。收到验证码后,用6结束该激活。
JSON 响应:getNumberV2 和 getStatusV2
如果您不想解析纯文本,getNumberV2 会以 JSON 返回号码,包含 activationId、phoneNumber、activationCost、currency 和 activationEndTime。验证码到达后,getStatusV2 会返回包含 sms.code 和 sms.text 的 JSON。有两个细节很重要:V2 接口上的错误仍是纯文本;在验证码出现之前,getStatusV2 返回的纯文本与 getStatus 相同。最稳妥的做法是先尝试 json.loads,失败再回退到文本。activationEndTime 采用服务器时间(Europe/Istanbul,UTC+3),格式为 Y-m-d H:i:s,不含时区。
import json
def get_number_v2(service, country, max_price=None):
text = call("getNumberV2", service=service, country=country,
maxPrice=None if max_price is None else "%.2f" % max_price)
try:
data = json.loads(text)
except ValueError:
raise ApiError(text) # errors stay plain text, even in V2
return data # activationId, phoneNumber, activationCost, activationEndTime ...
def get_status_v2(activation_id):
"""dict with the SMS once it arrived, otherwise the plain-text status (a str)."""
text = call("getStatusV2", id=activation_id)
try:
data = json.loads(text)
except ValueError:
return text # STATUS_WAIT_CODE, STATUS_WAIT_RETRY:<old>, STATUS_CANCEL ...
sms = (data or {}).get("sms") or {}
return {"code": sms.get("code"), "text": sms.get("text")}
order = get_number_v2("wa", "62", max_price=15.00)
print(order["activationId"], order["phoneNumber"], order["activationCost"], "until", order["activationEndTime"])在同一号码上再请求一条短信
如果第一条短信没有帮上忙,或服务要求再次验证,您可以在同一号码上请求新的短信。通过 setStatus 发送 3:这是免费的,每次激活只需付费一次。响应为 ACCESS_RETRY_GET,在新短信到达之前,getStatus 会返回 STATUS_WAIT_RETRY 以及旧验证码。只有拿到最后一个验证码之后,才用 6 结束激活。
# The first code has arrived and you need a second SMS on the same number (free).
first_code = wait_for_code(activation_id)
reply = request_another_sms(activation_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 wait_for_code() treats as "still waiting".
second_code = wait_for_code(activation_id)
print("First:", first_code, "Second:", second_code)
finish(activation_id) # close only after the LAST codeWebhook 接收端:Flask 与签名验证
您不必持续轮询,而可以让 Turonay 在验证码到达时通知您。在个人资料中的 API 部分中填写一个 HTTPS 地址(必须使用域名,端口为 443 或 8443);之后,当验证码到达 (code_received) 或激活被取消 (cancelled) 时,Turonay 会发送一条带签名的 JSON POST。请求头为 X-Turonay-Event、X-Turonay-Timestamp、X-Turonay-Signature 和 X-Turonay-Delivery。签名是对 timestamp + "." + 原始正文计算的 HMAC-SHA256,并带有 sha256= 前缀发送。
# webhook_app.py pip install flask | flask --app webhook_app run --port 8080
import hashlib
import hmac
import os
import time
from flask import Flask, request
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 # events are tiny
SECRET = os.environ["TURONAY_WEBHOOK_SECRET"] # whsec_... from your profile page
SEEN = set() # demo only: use Redis/DB with a TTL
def verify_webhook_signature(secret, timestamp, raw_body, signature, tolerance=300):
"""sha256=HMAC_SHA256(secret, timestamp + "." + raw body), 5 minute replay window."""
try:
age = abs(time.time() - int(timestamp))
except (TypeError, ValueError):
return False
if age > tolerance:
return False
mac = hmac.new(secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256)
expected = ("sha256=" + mac.hexdigest()).encode()
return hmac.compare_digest(expected, (signature or "").strip().encode()) # constant time
@app.post("/turonay/webhook")
def turonay_webhook():
raw = request.get_data() # the exact bytes, before any JSON parsing
if not verify_webhook_signature(
SECRET,
request.headers.get("X-Turonay-Timestamp", ""),
raw,
request.headers.get("X-Turonay-Signature", ""),
):
return "", 401
event = request.get_json(force=True, silent=True)
if not isinstance(event, dict):
return "", 400
if event.get("id") in SEEN: # retries repeat the same delivery id
return "", 200
SEEN.add(event.get("id"))
if event.get("event") == "code_received":
print("code", event["code"], "for activation", event["activationId"], event["phone"])
elif event.get("event") == "cancelled":
print("activation", event["activationId"], "cancelled, nothing charged")
return "", 200 # answer 2xx within 5 seconds; do slow work elsewhere三条安全规则:在解析 JSON 之前,先对原始字节验证签名;使用 hmac.compare_digest 进行恒定时间比较;拒绝早于 5 分钟的时间戳。如果您没有在 5 秒内返回 2xx,Turonay 会重试推送(最多 8 次),因此同一事件可能到达两次;请使用 id 字段忽略重复项。各事件字段请见Webhook。万一漏收了 Webhook,wait_for_code 循环仍会作为后备继续工作。
错误代码及处理方式
API 以 HTTP 200 的纯文本返回应用层错误,而网络和频率限制问题则以 HTTP 状态码形式出现。在示例中,Transient 类标记可重试的情况(网络错误、429、5xx、NO_CONNECTION),ApiError 则承载永久性错误。下表汇总了您最常遇到的代码。
| 代码 | 含义 | 处理方式 |
|---|---|---|
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 协议编写的机器人或库,可能无需重写:在大多数对接中,只需把基础(API)URL 改成以 /stubs/handler_api.php 结尾的 Turonay 地址,并把密钥换成您的 Turonay API 密钥。在 Python 中,使用环境变量是最干净的做法。
import os
# Before: BASE_URL = "https://provider.example.com/stubs/handler_api.php"
BASE_URL = os.environ.get("SMS_API_URL", "https://turonay.com/stubs/handler_api.php")
API_KEY = os.environ["SMS_API_KEY"] # your Turonay API key
# Libraries and bots with a base-URL option need only these two values, e.g.:
# client = SomeHandlerApiClient(api_key=API_KEY, base_url=BASE_URL)切换之前请检查两件事:金额以土耳其里拉计,并且服务代码和国家/地区 ID 必须与 getPrices 和 getCountries 的输出一致。价格请见API 价格。
常见问题
在 Python 中使用兼容 handler_api 的 API,应该用哪个 URL?
Turonay 使用 handler_api 协议,因此您向 Turonay 的 handler_api 地址发送 GET 请求,并带上 api_key 和 action 参数。在现有的 Python 代码中,您只需更改基础 URL 和密钥;地址见上面的示例。
如果短信始终没到,会扣费吗?
不会。getNumber 调用只预留价格。短信验证码到达的那一刻才会扣费;如果您在验证码到达前取消、供应方取消或超过 20 分钟,预留会被释放。
在 Python 中应该多久轮询一次?
每 5 秒调用一次 getStatus 就足够了;不要低于 3 秒。如果收到 HTTP 429,请把间隔加倍。Webhook 更高效,此时循环只作为后备保留。
可以使用 asyncio 或 aiohttp 吗?
可以。该协议就是普通的 GET 请求,因此 aiohttp 或 httpx 都可以代替 requests。逻辑保持不变:解析纯文本,把 STATUS_WAIT_RETRY 视为仍在等待,并把等待时间上限设为 20 分钟。
可以在同一号码上再收一条短信吗?
可以。通过 setStatus 发送 status=3,即可在同一号码上请求新的短信。这是免费的,每次激活只需付费一次。收到最后一个验证码后,用 status=6 结束该激活。