PHP code example of orynlabs / smsgo

1. Go to this page and download the library: Download orynlabs/smsgo library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

orynlabs / smsgo example snippets


use Orynlabs\SMSGo\Client;

$client = new Client(getenv('SMSGO_KEY'));

$result = $client->send(
    phone: '+5511999990000',
    message: 'Olá do SMSGo',
);

echo $result->id . ' ' . $result->status; // -> "a1b2c3...", "queued"

$client = new Client(getenv('SMSGO_KEY'), [
    'baseUrl'   => 'https://api.smsgo.com.br', // default; só mexa se a SMSGo orientar
    'timeout'   => 30,                          // segundos
    // 'transport' => $meuTransport,            // injeta um Http\Transport (testes)
]);

$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);

$client->send(
    phone: $user->phone,
    message: "Seu código SMSGo é {$code}. Válido por 5 minutos.",
);
// guarde $code (com TTL) e compare na verificação

$client->sendBulk(
    messages: [
        ['phone' => '+5511999990000', 'message' => 'Oi, Ana!'],
        ['phone' => '+5521988887777', 'message' => 'Oi, Bruno!'],
    ],
    urlCallback: 'https://seuapp.com/webhooks/smsgo', // status de entrega (opcional)
);

$page = $client->list(page: 1);         // Paginated<SendListItem> — { meta, data }
$one  = $client->get('a1b2c3-...');     // SendDetail + summary { total, delivered, failed, inProgress, done }

// Acompanhar um envio grande sem baixar tudo — números por bucket, paginado:
$failed = $client->getNumbers('a1b2c3-...', status: 'failed', page: 1);

$sandbox = new Client(getenv('SMSGO_TEST_KEY'));
$r = $sandbox->send(phone: '+5511999990000', message: 'Teste');
$r->test; // true

$sandbox->resolveMode(); // "test"  (ou $sandbox->mode() após a 1ª chamada)

$balance = $client->getBalance();  // Balance { balance, currency, company }
echo $balance->balance;            // 9.3

$types = $client->getSmsTypes();   // list<SmsTypeItem> { id, name, price, sale } — id vai em smsTypeId

$plans = $client->billing->plans(); // list<Plan> — pacotes por faixa
$cards = $client->billing->cards(); // list<Card> — 4 últimos dígitos

$receipt = $client->billing->purchase(quantity: 5000 /*, planId:, cardId:, coupon: */);
$receipt->status; // 'succeeded' já creditou o saldo | 'processing' confirma via webhook

$invoices = $client->billing->invoices(page: 1);

$client->setAutoRecharge(
    enabled: true,
    threshold: 5,        // recarrega quando o saldo ≤ R$ 5
    planQuantity: 5000,  // créditos por recarga
    cardId: '<uuid>',    // obrigatório p/ ligar
    alertEnabled: true,
    alertThreshold: 15,  // e-mail quando o saldo ≤ R$ 15
);

$cfg = $client->getAutoRecharge();

// Define a URL que recebe `sms.status` (DLR) e `sms.reply` (resposta). Guarde o secret.
$cfg = $client->setWebhook(url: 'https://seuapp.com/webhooks/smsgo');
$cfg->url; $cfg->secret;

$client->setWebhook(rotateSecret: true); // gira o segredo
$client->setWebhook(url: '');            // desativa

use Orynlabs\SMSGo\Webhook;

$rawBody   = file_get_contents('php://input');           // bytes exatos — não re-serialize!
$signature = $_SERVER['HTTP_X_SMSGO_SIGNATURE'] ?? null;

if (! Webhook::verifySignature($rawBody, $signature, $secret)) {
    http_response_code(401);
    exit;
}

$listId = $client->lists->create(name: 'Clientes VIP')->id;

$contactId = $client->contacts->create(
    fullName: 'Ana Souza',
    phone: '+5511999990000',
    email: '[email protected]',
    lists: [$listId],
);

$client->contacts->list(page: 1, search: 'ana'); // Paginated { meta, data }
$client->contacts->update($contactId, fullName: 'Ana S.', phone: '+5511999990000');
$client->contacts->delete($contactId);

use Orynlabs\SMSGo\Client;
use Orynlabs\SMSGo\SMSGoError;

try {
    $client->send(phone: '+5511999990000', message: 'Olá');
} catch (SMSGoError $e) {
    switch ($e->code) {
        case 'insufficient_balance': // 402 — sem saldo
        case 'rate_limited':         // 429 — muitas requisições (veja $e->details)
        case 'validation_error':     // 422 — dados inválidos ($e->errors por campo)
        default:
            error_log("{$e->status} {$e->code} {$e->getMessage()}");
    }
}
bash
composer install
SMSGO_KEY=suachave php examples/otp.php +5511999990000