# Verifica via SMS in PHP

Uno script completo in PHP 8 con l’estensione cURL: acquista un numero temporaneo, attende il codice e chiude l’ordine.

## Come ricevo un codice di verifica via SMS in PHP?

Invia richieste cURL con l’intestazione X-Api-Key: POST /v1/orders con corpo JSON per ottenere il numero, interroga GET /v1/orders/{id} ogni 4 secondi finché messages contiene l’SMS e chiama POST finish. Annulla se non arriva nulla per sbloccare l’importo.

## Preparazione

- PHP 8.0 o successivo con le estensioni curl e json.
- Imposta la chiave nell’ambiente: SMSNITRO_API_KEY=...

## Script completo

**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";
```

## Uso in un’applicazione web

- Esegui il ciclo di controllo in una coda di lavori o in un comando da terminale, non dentro una richiesta web.
- Salva l’id dell’ordine; il front-end chiede lo stato al tuo server.
- Tieni la chiave nell’ambiente del server, mai nei template o nel JavaScript.

Fonte: https://smsnitro.com/it/sviluppatori/php
