# SMS verification in PHP

A complete PHP 8 script with the cURL extension: buy a temporary number, wait for the code and close the order.

## How do I receive an SMS verification code in PHP?

Send cURL requests with the X-Api-Key header: POST /v1/orders with a JSON body to get a number, poll GET /v1/orders/{id} every 4 seconds until messages has the SMS, then POST finish. Cancel when nothing arrives to release the frozen amount.

## Setup

- PHP 8.0 or newer with the curl and json extensions.
- Set the key in the environment: SMSNITRO_API_KEY=...

## Complete script

**activation.php**

```php
<?php
// PHP 8+ with the cURL extension. Run: SMSNITRO_API_KEY=... php activation.php
const API = 'https://smsnitro.com/api/v1';

function api(string $method, string $path, ?array $body = null): array {
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTPHEADER     => [
            'X-Api-Key: ' . getenv('SMSNITRO_API_KEY'),
            'Content-Type: application/json',
        ],
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }
    $data = json_decode(curl_exec($ch), true);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    if ($status >= 400) {
        throw new RuntimeException("$status: " . ($data['detail'] ?? 'error'));
    }
    return $data;
}

echo 'Balance: ', api('GET', '/balance')['balance'], " USD\n";

$order = api('POST', '/orders', ['product' => 'telegram', 'country' => 'usa']);
echo "Number: {$order['phone']} (order {$order['id']})\n";

$deadline = time() + 600; // numbers stay reserved for up to 20 minutes
while (time() < $deadline) {
    $order = api('GET', "/orders/{$order['id']}");
    if ($order['messages']) {
        echo 'Code: ', end($order['messages'])['code'], "\n";
        api('POST', "/orders/{$order['id']}/finish");
        exit(0);
    }
    if (in_array($order['status'], ['CANCELED', 'TIMEOUT', 'BANNED', 'FINISHED'], true)) {
        exit("Ended without SMS: {$order['status']} (not charged)\n");
    }
    sleep(4); // poll every 3 to 5 seconds
}
api('POST', "/orders/{$order['id']}/cancel"); // refund the frozen amount
echo "No SMS: cancelled and refunded\n";
```

## Using it in a web app

- Run the polling loop in a queue worker or a CLI job, not inside a web request.
- Store the order id; your front end can ask your server for the status.
- Keep the key in the server environment, never in templates or JavaScript.

Source: https://smsnitro.com/developers/php
