Vérification par SMS en PHP
Un script complet en PHP 8 avec l’extension cURL : il achète un numéro temporaire, attend le code et clôture la commande.
Comment recevoir un code de vérification par SMS en PHP ?
Envoyez des requêtes cURL avec l’en-tête X-Api-Key : POST /v1/orders avec un corps JSON pour obtenir le numéro, interrogez GET /v1/orders/{id} toutes les 4 secondes jusqu’à ce que messages contienne le SMS, puis appelez POST finish. Annulez si rien n’arrive pour libérer le montant réservé.
Préparation
- PHP 8.0 ou plus récent avec les extensions curl et json.
- Définissez la clé dans l’environnement : SMSNITRO_API_KEY=...
Script complet
<?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";Utilisation dans une application web
- Exécutez la boucle de suivi dans une file de tâches ou une commande en terminal, pas dans une requête web.
- Conservez l’id de la commande ; votre front-end demande le statut à votre serveur.
- Gardez la clé dans l’environnement du serveur, jamais dans les gabarits ou le JavaScript.