首页 › 短信 API › PHP 短信 API
PHP · cURL · 短信验证 API

用 PHP 接收短信验证码

下面是在 PHP 中通过 cURL 扩展使用 Turonay 短信验证 API 的完整示例,可直接复制:购买虚拟号码,读取到达的验证码,然后结束或取消激活。由于 Turonay 采用 handler_api 结构,同样的 PHP 代码也兼容了解该协议的现有脚本和软件包。

该示例不需要任何 Composer 包,可在 PHP 7.4 及更高版本上运行;有 cURL 扩展就够了。它从余额查询开始,随后加入完整流程、JSON 接口、Webhook 接收端和错误处理。一般概览请见短信 API,所有接口请见API 参考。

您需要准备什么

在尝试代码之前,请先准备好以下内容:

  • Turonay API 密钥:登录后从个人资料中的 API 部分复制。在 PHP 中用 getenv() 从环境变量读取,切勿提交到代码仓库。
  • 余额:购买号码时,其价格会从您的余额中预留。所有金额均以土耳其里拉 (TRY) 计。
  • 已启用 curl 扩展的 PHP 7.4 或更高版本(共享主机通常自带)。
何时扣费:getNumber 只预留价格,真正的扣费发生在短信验证码到达时。如果您在验证码到达前取消,或 20 分钟的时限过期,预留会被释放,您无需付费。验证码到达后,取消会被拒绝,并返回 EARLY_CANCEL_DENIED。

设置:检查 cURL 扩展

您无需安装任何软件包。请在命令行确认 PHP 版本,并确认已加载 curl 扩展,然后把 API 密钥放入环境变量。如果代码将在 Web 服务器上运行,请在 PHP-FPM 或虚拟主机配置中定义同样的变量。

bash
php -v                          # PHP 7.4 or newer (8.x recommended)
php -m | grep -i curl           # the curl extension must be listed
export TURONAY_API_KEY="paste-your-api-key-here"

第一次调用:读取余额

测试连接最快的方式是发出 getBalance 请求。响应是纯文本,而不是 JSON:成功时形如 ACCESS_BALANCE:125.4000,密钥错误则返回 BAD_KEY。正文可能以换行符结尾,请记得使用 trim()。

php
<?php
$url = 'https://turonay.com/stubs/handler_api.php?' . http_build_query([
    'api_key' => getenv('TURONAY_API_KEY'),
    'action'  => 'getBalance',
]);

$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20]);
$text = trim((string) curl_exec($ch));   // plain text, not JSON: "ACCESS_BALANCE:125.4000"

if (strpos($text, 'ACCESS_BALANCE:') === 0) {
    echo 'Balance (TRY): ', substr($text, strlen('ACCESS_BALANCE:')), PHP_EOL;
} else {
    echo 'Error: ', $text, PHP_EOL;       // e.g. BAD_KEY
}

PHP 完整流程:获取号码,轮询验证码,完成

下面的文件包含整个生命周期。getNumber() 带价格上限 (maxPrice) 购买,waitForCode() 每 5 秒调用一次 getStatus,最长 20 分钟,并根据结果运行 finish() 或 cancel()。函数名与 Turonay 的 PHP 参考客户端一致,因此以后改成类很容易。请在命令行用 php sms_flow.php 运行。

php
<?php
declare(strict_types=1);

// sms_flow.php - buy a number, wait for the SMS code, finish or cancel.  Needs ext-curl.
const API = 'https://turonay.com/stubs/handler_api.php';

/** The API answered with a plain-text error code (NO_BALANCE, NO_NUMBERS, ...). */
class ApiError extends RuntimeException {}
/** Network trouble, HTTP 429 or 5xx, NO_CONNECTION: safe to retry later. */
class Transient extends ApiError {}
class CodeTimeout extends RuntimeException {}

function apiCall(string $action, array $params = []): string
{
    $key = (string) getenv('TURONAY_API_KEY');
    $params = array_filter($params, static function ($v) { return $v !== null; });
    $query = ['api_key' => $key, 'action' => $action] + $params;

    $ch = curl_init(API . '?' . http_build_query($query));
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT        => 20,
    ]);
    $body = curl_exec($ch);
    $http = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    if ($body === false || $http !== 200) {
        throw new Transient('HTTP ' . $http);        // never print the URL: it holds your api_key
    }
    $text = trim((string) $body);                    // always trim: bodies are plain text
    if ($text === 'NO_CONNECTION') {
        throw new Transient($text);
    }
    return $text;
}

function getBalance(): string
{
    $text = apiCall('getBalance');
    if (strpos($text, 'ACCESS_BALANCE:') !== 0) {
        throw new ApiError($text);
    }
    return substr($text, strlen('ACCESS_BALANCE:'));
}

/** @return array [activationId, phone]. The price is only RESERVED here, not charged. */
function getNumber(string $service, string $country, ?float $maxPrice = null): array
{
    $text = apiCall('getNumber', [
        'service'  => $service,
        'country'  => $country,
        'maxPrice' => $maxPrice === null ? null : number_format($maxPrice, 2, '.', ''),
    ]);
    $parts = explode(':', $text);
    if ($parts[0] === 'ACCESS_NUMBER' && count($parts) >= 3 && $parts[1] !== '' && $parts[2] !== '') {
        return [$parts[1], $parts[2]];
    }
    throw new ApiError($text);   // NO_BALANCE, NO_NUMBERS, BAD_SERVICE, WRONG_MAX_PRICE:<price> ...
}

/** @return array [state, code] where state is 'wait', 'ok' or 'cancel'. */
function getStatus(string $id): array
{
    $text = apiCall('getStatus', ['id' => $id]);
    if (strpos($text, 'STATUS_OK:') === 0) {
        return ['ok', substr($text, strlen('STATUS_OK:'))];
    }
    if ($text === 'STATUS_CANCEL') {
        return ['cancel', null];
    }
    if ($text === 'STATUS_WAIT_CODE' || $text === 'STATUS_WAIT_RESEND' || strpos($text, 'STATUS_WAIT_RETRY:') === 0) {
        return ['wait', null];   // WAIT_RETRY carries the OLD code: still waiting for the new one
    }
    throw new ApiError($text);   // NO_ACTIVATION, BAD_KEY ...
}

function setStatus(string $id, int $status): string
{
    return apiCall('setStatus', ['id' => $id, 'status' => $status]);
}

function requestAnotherSms(string $id): string { return setStatus($id, 3); }  // free, ACCESS_RETRY_GET
function finish(string $id): string { return setStatus($id, 6); }              // ACCESS_ACTIVATION, only after a code
function cancel(string $id): string { return setStatus($id, 8); }              // ACCESS_CANCEL / EARLY_CANCEL_DENIED

/** Poll every $interval seconds for at most $timeout seconds (20 minutes). */
function waitForCode(string $id, int $timeout = 1200, int $interval = 5): string
{
    $deadline = microtime(true) + $timeout;
    $delay = $interval;
    while (microtime(true) < $deadline) {
        try {
            [$state, $code] = getStatus($id);
            $delay = $interval;
            if ($state === 'ok') {
                return (string) $code;
            }
            if ($state === 'cancel') {
                throw new ApiError('STATUS_CANCEL');
            }
        } catch (Transient $e) {
            $delay = min($delay * 2, 60);            // back off on HTTP 429 / network trouble
        }
        $left = $deadline - microtime(true);
        if ($left <= 0) {
            break;
        }
        sleep((int) max(1, min($delay, ceil($left))));
    }
    throw new CodeTimeout("no SMS within $timeout seconds");
}

function main(): int
{
    [$service, $country] = ['wa', '62'];             // WhatsApp, Turkey (see getPrices / getCountries)
    try {
        echo 'Balance (TRY): ', getBalance(), PHP_EOL;
        [$id, $phone] = getNumber($service, $country, 15.00);
    } catch (Transient $e) {
        echo 'Temporary problem, try again later: ', $e->getMessage(), PHP_EOL;
        return 1;
    } catch (ApiError $e) {
        $reason = $e->getMessage();
        if (strpos($reason, 'WRONG_MAX_PRICE') === 0) {
            $pos = strpos($reason, ':');
            echo 'Current price is above your limit: ', $pos === false ? '?' : substr($reason, $pos + 1), PHP_EOL;
        } elseif ($reason === 'NO_NUMBERS') {
            echo 'No numbers in stock right now, try again in a minute', PHP_EOL;
        } elseif ($reason === 'NO_BALANCE') {
            echo 'Not enough balance, top up first', PHP_EOL;
        } else {
            echo 'API error: ', $reason, PHP_EOL;
        }
        return 1;
    }

    echo "Use this number: $phone (activation $id)", PHP_EOL;
    try {
        $code = waitForCode($id);
    } catch (CodeTimeout $e) {
        $reply = cancel($id);                        // nothing is charged when no code arrived
        if ($reply !== 'EARLY_CANCEL_DENIED') {
            echo "Timed out, activation cancelled: $reply", PHP_EOL;
            return 1;
        }
        [, $code] = getStatus($id);                  // the code arrived in the last second
    } catch (ApiError $e) {                          // STATUS_CANCEL: the supplier cancelled, nothing charged
        echo 'Activation cancelled: ', $e->getMessage(), PHP_EOL;
        return 1;
    }

    echo "SMS code: $code", PHP_EOL;
    echo finish($id), PHP_EOL;                       // ACCESS_ACTIVATION
    return 0;
}

exit(main());

代码中的主要判断:

  • 如果当前价格超过您的 maxPrice,不会购买号码,并返回 WRONG_MAX_PRICE:<price>;您可以读取价格并有意识地提高上限。
  • NO_NUMBERS 是暂时的库存问题,NO_BALANCE 需要充值。两者都会作为 ApiError 被捕获,而网络和频率限制问题则作为 Transient 单独区分。
  • STATUS_WAIT_CODE 和 STATUS_WAIT_RETRY:<old code> 都表示“等待”;后者中的验证码属于上一条短信,不能当作新验证码使用。
  • 20 分钟后,通过 setStatus 发送 8 来取消激活;如果验证码在最后一刻到达,EARLY_CANCEL_DENIED 的响应会使脚本再次读取验证码。收到验证码后,用 6 结束该激活。

JSON 接口:getNumberV2 和 getStatusV2

如果您更喜欢具名字段,getNumberV2 返回的 JSON 经 json_decode 会变成数组:activationId、phoneNumber、activationCost、currency、activationEndTime。验证码到达后,getStatusV2 返回包含 sms.code 和 sms.text 的 JSON。请记住两个细节:V2 上的错误代码同样是纯文本;在验证码出现之前,getStatusV2 返回 STATUS_WAIT_CODE 等纯文本状态。因此,如果 json_decode 的结果不是数组,就把正文当作文本处理。activationEndTime 采用服务器时间(Europe/Istanbul,UTC+3),格式为 Y-m-d H:i:s,不含时区。

php
function getNumberV2(string $service, string $country, ?float $maxPrice = null): array
{
    $text = apiCall('getNumberV2', [
        'service'  => $service,
        'country'  => $country,
        'maxPrice' => $maxPrice === null ? null : number_format($maxPrice, 2, '.', ''),
    ]);
    $data = json_decode($text, true);
    if (!is_array($data)) {
        throw new ApiError($text);   // errors stay plain text, even in V2
    }
    return $data;                    // activationId, phoneNumber, activationCost, activationEndTime ...
}

/** @return array|string array with the SMS once it arrived, otherwise the plain-text status. */
function getStatusV2(string $id)
{
    $text = apiCall('getStatusV2', ['id' => $id]);
    $data = json_decode($text, true);
    if (!is_array($data)) {
        return $text;                // STATUS_WAIT_CODE, STATUS_WAIT_RETRY:<old>, STATUS_CANCEL ...
    }
    return ['code' => $data['sms']['code'] ?? null, 'text' => $data['sms']['text'] ?? null];
}

$order = getNumberV2('wa', '62', 15.00);
echo $order['activationId'], ' ', $order['phoneNumber'], ' ', $order['activationCost'],
     ' until ', $order['activationEndTime'], PHP_EOL;

再请求一条短信 (setStatus 3)

如果第一条短信没有帮上忙,或服务要求再次验证,您可以在同一号码上请求新的短信。向 setStatus 传入 3:这是免费的,每次激活只需付费一次。响应为 ACCESS_RETRY_GET;在新短信到达之前,getStatus 会返回 STATUS_WAIT_RETRY 以及旧验证码,waitForCode() 会把它视为等待。只有在最后一个验证码之后,才用 6 结束激活。

php
// The first code has arrived and you need a second SMS on the same number (free).
$firstCode = waitForCode($id);
$reply = 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".
    $secondCode = waitForCode($id);
    echo "First: $firstCode Second: $secondCode", PHP_EOL;
}
finish($id);                                   // close only after the LAST code

Webhook 接收端:原生 PHP 与签名验证

如果您希望由 Turonay 通知您,而不是轮询,请在个人资料中的 API 部分中设置一个 HTTPS Webhook 地址(域名,端口 443 或 8443)。当验证码到达 (code_received) 或激活被取消 (cancelled) 时,您的地址会收到一条带签名的 JSON POST。签名位于 X-Turonay-Signature 请求头中,等于 sha256= + HMAC-SHA256(secret, timestamp + "." + 原始正文);时间戳通过 X-Turonay-Timestamp 请求头传来。

php
<?php
declare(strict_types=1);

// turonay_webhook.php - public HTTPS endpoint on YOUR server (port 443 or 8443).
$secret = (string) getenv('TURONAY_WEBHOOK_SECRET');      // whsec_... from your profile page

/** sha256=HMAC_SHA256(secret, timestamp . "." . raw body), 5 minute replay window. */
function verifyWebhookSignature(string $secret, string $timestamp, string $rawBody, string $signature, int $tolerance = 300): bool
{
    if (!preg_match('/^[0-9]{1,12}$/', $timestamp) || abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }
    $expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    return hash_equals($expected, trim($signature));      // constant time
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405);
    exit;
}
if ($secret === '') {
    http_response_code(500);
    exit;
}

$raw = (string) file_get_contents('php://input');         // the exact bytes, before json_decode
if (strlen($raw) > 65536 || !verifyWebhookSignature(
    $secret,
    $_SERVER['HTTP_X_TURONAY_TIMESTAMP'] ?? '',
    $raw,
    $_SERVER['HTTP_X_TURONAY_SIGNATURE'] ?? ''
)) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
if (!is_array($event)) {
    http_response_code(400);
    exit;
}

// Retries repeat the same "id": store it (unique index) and skip events you already handled.
switch ($event['event'] ?? '') {
    case 'code_received':
        error_log("code {$event['code']} for activation {$event['activationId']} ({$event['phone']})");
        break;
    case 'cancelled':
        error_log("activation {$event['activationId']} cancelled, nothing charged");
        break;
}

http_response_code(200);                                  // answer 2xx within 5 seconds

在 PHP 中,用 php://input 读取原始正文,在调用 json_decode 之前先验证,用 hash_equals 比较以抵御计时攻击,并拒绝早于 5 分钟的时间戳。如果您没有在 5 秒内返回 2xx,推送会被重试(最多 8 次),因此不要重复处理同一个 id。把耗时任务放进队列,并立即返回 200。所有事件字段请见Webhook。

错误代码

应用层错误以 HTTP 200 的纯文本形式到达;网络故障、429 和 5xx 会被转换为 Transient 异常,可以放心重试。下表列出了您可能在响应正文中看到的代码,以及建议的处理方式。

代码含义处理方式
BAD_KEYAPI 密钥为空、错误或已被封锁。请重新从个人资料中复制密钥,并确认两端没有残留空白字符。
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 结构的 PHP 脚本或软件包,在大多数对接中,只需把基础 URL 切换为 Turonay 的 /stubs/handler_api.php 地址,并把密钥换成您的 Turonay 密钥;不过上线前仍请测试流程。如果地址是硬编码的,把它移到一个配置值中,也会让以后的修改更容易。

php
<?php
// Before: define('SMS_API_URL', 'https://provider.example.com/stubs/handler_api.php');
define('SMS_API_URL', getenv('SMS_API_URL') ?: 'https://turonay.com/stubs/handler_api.php');
define('SMS_API_KEY', (string) getenv('SMS_API_KEY'));   // your Turonay API key

// Scripts and libraries that build their own query string keep working unchanged:
// SMS_API_URL . '?api_key=' . SMS_API_KEY . '&action=getBalance'

切换之后请记住,价格以土耳其里拉计,并且服务代码和国家/地区 ID 必须与 getPrices 和 getCountries 的输出一致。当前价格请见API 价格。

常见问题

如何在 PHP 中使用兼容 handler_api 的 API?

Turonay 使用 handler_api 协议。通过 cURL,您向 API 地址发送带有 api_key 和 action 参数的 GET 请求,并解析纯文本响应。如果您已有 PHP 脚本,只需更改基础 URL 和密钥。

在 PHP 中可以用 file_get_contents 代替 cURL 吗?

可以,但 cURL 能更清楚地提供超时、连接时间和 HTTP 状态码。建议使用 cURL,这样您就能把 HTTP 429 频率限制与网络错误区分开。

验证码没来,会扣钱吗?

不会。getNumber 只做预留。短信验证码到达时才会扣费;如果您在验证码到达前取消、供应方取消或超过 20 分钟,金额会退回至您的可用余额。

轮询循环能在共享主机上运行吗?

它可以作为命令行脚本运行(cron 或 SSH);在 Web 请求中等待 20 分钟会触发超时。对于 Web 应用,最好使用 Webhook,或把轮询移到后台任务中。

如何在同一号码上请求第二条短信?

向 setStatus 传入 status=3。这是免费的,每次激活只需付费一次。响应为 ACCESS_RETRY_GET;继续用 getStatus 等待新验证码,并在最后一个验证码之后用 status=6 结束该激活。