otpwatch handler_api.php recipes
Get API key

PHP client: cURL, one class, cleanup that always runs

PHP is where a lot of number bots and storefronts live, and where the classic mistake happens: polling getStatus inside a web request until the PHP-FPM timeout kills it. This client is a plain class for PHP 8.1 and newer, with cleanup that runs even when your code throws.

Get an API key Opens sign-up on SimAggregator, the marketplace this API belongs to. Key in the dashboard, balance in USD.

Requirements

PHP 8.1 or newer with the curl extension (php -m | grep curl). No Composer packages. The key goes in an environment variable, never in a file under the web root.

The client

SmsClient.php
<?php
// handler_api reference: https://otpwatch.com/php
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
declare(strict_types=1);

namespace Otp;

final class SmsApiException extends \RuntimeException
{
    public readonly string $reply;
    public readonly string $apiCode;

    public function __construct(string $reply)
    {
        parent::__construct($reply);
        $this->reply = $reply;
        $this->apiCode = explode(':', $reply, 2)[0];
    }
}

final class Activation
{
    public ?string $code = null;

    public function __construct(private readonly SmsClient $client, public readonly string $id, public readonly string $phone)
    {
    }

    public function e164(): string
    {
        return '+' . $this->phone;
    }

    public function waitCode(int $timeoutSeconds = 600, int $intervalSeconds = 3): string
    {
        $deadline = time() + $timeoutSeconds;
        while (time() < $deadline) {
            $reply = $this->client->call('getStatus', ['id' => $this->id]);
            if (str_starts_with($reply, 'STATUS_OK:')) {
                return $this->code = substr($reply, strlen('STATUS_OK:'));
            }
            if (!str_starts_with($reply, 'STATUS_WAIT')) {
                throw new SmsApiException($reply);
            }
            sleep($intervalSeconds);
        }
        throw new \RuntimeException("No SMS for activation {$this->id} within {$timeoutSeconds}s");
    }

    public function close(): void
    {
        if ($this->code !== null) {
            $this->client->call('setStatus', ['id' => $this->id, 'status' => 6]);
            return;
        }
        $tries = 9;  // tries and pause are our choice, not an API rule:
        $pause = 10; // the docs only say "too early to cancel, repeat the request later"
        for ($i = 0; $i < $tries; $i++) {
            if ($this->client->call('setStatus', ['id' => $this->id, 'status' => 8]) !== 'EARLY_CANCEL_DENIED') {
                return;
            }
            if ($i < $tries - 1) {
                sleep($pause); // too early to cancel: repeat later
            }
        }
        throw new \RuntimeException("Cancel {$this->id}: still EARLY_CANCEL_DENIED after {$tries} tries; cancel it later");
    }
}

final class SmsClient
{
    public const BASE_URL = 'https://sim-aggregator.org/stubs/handler_api.php';

    /** @var callable(string): string */
    private $transport;

    public function __construct(
        private readonly string $apiKey,
        private readonly string $baseUrl = self::BASE_URL,
        ?callable $transport = null,
    ) {
        $this->transport = $transport ?? self::curlGet(...);
    }

    public static function curlGet(string $url): string
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 10]);
        $body = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($body === false) {
            throw new \RuntimeException('HTTP request failed: ' . curl_error($ch));
        }
        if ($status >= 400) {
            throw new \RuntimeException("HTTP $status");
        }
        return (string) $body;
    }

    public function call(string $action, array $params = []): string
    {
        $query = http_build_query(['action' => $action, 'api_key' => $this->apiKey] + array_filter($params, fn ($v) => $v !== null));
        for ($attempt = 0; $attempt < 6; $attempt++) {
            $text = trim(($this->transport)($this->baseUrl . '?' . $query));
            if ($text !== 'REQUEST_LIMIT') {
                return $text;
            }
            usleep(min(2 ** $attempt, 30) * 1_000_000 + random_int(0, 500_000));
        }
        throw new SmsApiException('REQUEST_LIMIT');
    }

    public function balance(): float
    {
        $reply = $this->call('getBalance');
        if (!str_starts_with($reply, 'ACCESS_BALANCE:')) {
            throw new SmsApiException($reply);
        }
        return (float) substr($reply, strlen('ACCESS_BALANCE:'));
    }

    public function order(string $service, int $country, ?float $maxPrice = null, ?string $duration = null): Activation
    {
        $reply = $this->call('getNumber', [
            'service' => $service,
            'country' => $country,
            'maxPrice' => $maxPrice === null ? null : number_format($maxPrice, 2, '.', ''),
            'duration' => $duration,
        ]);
        if (!str_starts_with($reply, 'ACCESS_NUMBER:')) {
            throw new SmsApiException($reply);
        }
        [, $id, $phone] = explode(':', $reply, 3);
        return new Activation($this, $id, $phone);
    }

    /** Orders a number, runs $fn, then finishes or cancels it, even if $fn throws. */
    public function withActivation(string $service, int $country, callable $fn, ?float $maxPrice = null): mixed
    {
        $activation = $this->order($service, $country, $maxPrice);
        try {
            return $fn($activation);
        } finally {
            $activation->close();
        }
    }
}

Use it from the CLI

.env.example
# handler_api reference: https://otpwatch.com/php
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/key
SMS_API_KEY=
example.php
<?php
// handler_api reference: https://otpwatch.com/php
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
require __DIR__ . '/SmsClient.php';

use Otp\SmsApiException;
use Otp\SmsClient;

$client = new SmsClient(
    getenv('SMS_API_KEY') ?: throw new RuntimeException('SMS_API_KEY is not set'),
    getenv('SMS_API_BASE_URL') ?: SmsClient::BASE_URL,
);
echo 'balance: ', $client->balance(), PHP_EOL;

try {
    $code = $client->withActivation('tg', 16, function ($act) {   // Telegram, United Kingdom
        echo 'number: ', $act->e164(), PHP_EOL;
        // ... trigger the SMS to $act->e164() here ...
        return $act->waitCode(300);
    }, maxPrice: 2.0);
    echo 'code: ', $code, PHP_EOL;
} catch (SmsApiException $e) {
    echo 'not ordered: ', $e->reply, PHP_EOL;   // NO_NUMBERS, WRONG_MAX_PRICE:1.9, NO_BALANCE...
}

php example.php from a terminal has no execution time limit by default, which is what a polling loop needs.

Do not poll inside a web request

A storefront or bot webhook that calls waitCode inside the HTTP request ties up a PHP-FPM worker for as long as the SMS takes, and max_execution_time or the proxy timeout will eventually kill it mid-order. Split the work:

  1. The request handler calls order(), stores the activation id with the user's order, and returns the number to the user immediately.
  2. A CLI worker (cron every minute, or a long-running Supervisor process) loads open activation ids, calls getStatus once per id per pass, and writes codes back to the database.
  3. The page asks your own backend for the code; it never talks to the SMS API directly, so the key stays on the server.

With one worker and the 600 requests per minute key limit, keep open orders × 60 / seconds between passes well under 600.

PHPUnit without network

The constructor takes any callable as the transport.

SmsClientTest.php
<?php
// handler_api reference: https://otpwatch.com/php
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
use Otp\SmsClient;
use PHPUnit\Framework\TestCase;

final class SmsClientTest extends TestCase
{
    public function testCodeKeepsLeadingZerosAndOrderIsFinished(): void
    {
        $replies = ['ACCESS_NUMBER:9:447700900123', 'STATUS_OK:004821', 'ACCESS_ACTIVATION'];
        $urls = [];
        $client = new SmsClient('k', transport: function (string $url) use (&$replies, &$urls) {
            $urls[] = $url;
            return array_shift($replies);
        });

        $code = $client->withActivation('tg', 16, fn ($a) => $a->waitCode(5, 0));

        $this->assertSame('004821', $code);
        $this->assertStringContainsString('status=6', end($urls));
    }
}

Notes

  • withActivation uses finally, so a thrown exception in your callback still cancels the order and returns the hold to the balance.
  • maxPrice is sent with a dot as the decimal separator whatever the server locale.
  • Codes stay strings; never cast them to int.
  • Rentals for repeat logins: pass duration d1, d3 or d7 to order(); see renting a number.

ready to run it?

Copy SmsClient.php, set SMS_API_KEY, run it from the CLI first.

Get an API key

Install for your coding agent

terminal
# Agent skills index: https://otpwatch.com/.well-known/agent-skills/index.json
npx skills add https://otpwatch.com

Two skills: receiving an SMS code in your own app or test, and building a bot that sells numbers. Index: /.well-known/agent-skills/index.json

Updated