Огляд
API для розробників продає ті самі номери, що й застосунок, з того самого балансу — через REST API та сумісну адресу.
- Base URL
https://smsgrab.com/api/dev/v1- sms-activate compatible
https://smsgrab.com/api/stubs/handler_api.php- Format
- JSON over HTTPS with
snake_casefields in UTF-8. Fields are sent even when their value isnull, except where an endpoint says otherwise. New fields may be added at any time, so ignore what you do not know. - Money
- Integers in minor units of
currency, which isUSD(cents). Every charge goes through the same double-entry ledger as the app, and numbers without a code are refunded automatically. - Time
- ISO 8601 in UTC with milliseconds, for example
2026-09-27T10:05:00.000Z. - Authentication
- An API key (
sgk_…) inAuthorization: BearerorX-Api-Key. See Authentication. - Ids
- Services and countries use our catalogue ids (
whatsapp,indonesia); activations a UUID and a numericcompat_id, both accepted everywhere. - Request ids
- Every answer carries
X-Request-Id. Quote it when you contact support.
Every answer also carries the rate-limit headers of the tightest limit that applies. GET answers carry an ETag, and a matching If-None-Match answers 304 Not Modified.
HTTP/1.1 200 OK
Content-Type: application/json
X-Request-Id: 36faf252-2aed-460b-8fbb-db15c8b571be
RateLimit-Limit: 600
RateLimit-Remaining: 597
RateLimit-Reset: 41
RateLimit-Policy: 600;w=60
ETag: "5d41402abc4b2a76b9719d911017c592"
Cache-Control: no-store
Швидкий старт
Три виклики ведуть від нового ключа до отриманого коду.
- Створіть обліковий запис із підтвердженою адресою пошти й відкрийте розділ розробника.
- Створіть ключ із доступом «Читання й покупки» та скопіюйте його секрет.
- Переконайтеся, що балансу вистачить на потрібний номер, і виконайте виклики нижче.
curl
set -euo pipefail
API="https://smsgrab.com/api/dev/v1"
call() {
local response
response=$(curl -sS -w '\n%{http_code}' -H "Authorization: Bearer $SMSGRAB_API_KEY" "$@") || return 1
if [ "${response##*$'\n'}" -ge 400 ]; then
echo "${response%$'\n'*}" >&2
return 1
fi
echo "${response%$'\n'*}"
}
call "$API/balance"
activation=$(call -X POST "$API/activations" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{"service":"telegram","country":"indonesia","max_price_minor":30}')
id=$(jq -r .id <<<"$activation")
echo "Number: $(jq -r .phone_number <<<"$activation")"
status=WAITING_SMS
while [ "$status" = WAITING_SMS ]; do
activation=$(call "$API/activations/$id?wait=25")
status=$(jq -r .status <<<"$activation")
done
if [ "$(jq '.sms | length' <<<"$activation")" -gt 0 ]; then
echo "Code: $(jq -r '.sms[-1].code' <<<"$activation")"
if [ "$status" = CODE_RECEIVED ]; then
call -X POST "$API/activations/$id/finish" > /dev/null
fi
else
echo "No code arrived ($status), the charge was refunded"
fi
Python
import os
import uuid
import requests
API = "https://smsgrab.com/api/dev/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['SMSGRAB_API_KEY']}"
class SmsGrabError(Exception):
pass
def call(method: str, path: str, **kwargs) -> dict:
response = session.request(method, f"{API}{path}", timeout=40, **kwargs)
if response.status_code >= 400:
try:
error = response.json()
except ValueError:
error = {"code": str(response.status_code), "message": response.text[:200]}
raise SmsGrabError(f"{error.get('code')}: {error.get('message')}")
return response.json()
activation = call(
"POST",
"/activations",
json={"service": "telegram", "country": "indonesia", "max_price_minor": 30},
headers={"Idempotency-Key": str(uuid.uuid4())},
)
print("Number:", activation["phone_number"])
while activation["status"] == "WAITING_SMS":
activation = call("GET", f"/activations/{activation['id']}", params={"wait": 25})
if activation["sms"]:
print("Code:", activation["sms"][-1]["code"])
if activation["status"] == "CODE_RECEIVED":
call("POST", f"/activations/{activation['id']}/finish")
else:
print("No code arrived, the charge was refunded")
Node.js
import { randomUUID } from 'node:crypto';
const API = 'https://smsgrab.com/api/dev/v1';
async function call(method, path, { body, idempotencyKey } = {}) {
const response = await fetch(`${API}${path}`, {
method,
headers: {
Authorization: `Bearer ${process.env.SMSGRAB_API_KEY}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(40_000),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(`${data.code ?? response.status}: ${data.message ?? response.statusText}`);
}
return data;
}
let activation = await call('POST', '/activations', {
body: { service: 'telegram', country: 'indonesia', max_price_minor: 30 },
idempotencyKey: randomUUID(),
});
console.log('Number:', activation.phone_number);
while (activation.status === 'WAITING_SMS') {
activation = await call('GET', `/activations/${activation.id}?wait=25`);
}
if (activation.sms.length > 0) {
console.log('Code:', activation.sms.at(-1).code);
if (activation.status === 'CODE_RECEIVED') {
await call('POST', `/activations/${activation.id}/finish`);
}
} else {
console.log('No code arrived, the charge was refunded');
}
PHP
<?php
require __DIR__.'/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://smsgrab.com/api/dev/v1/',
'headers' => ['Authorization' => 'Bearer '.getenv('SMSGRAB_API_KEY'), 'Accept' => 'application/json'],
'timeout' => 40,
]);
function call(Client $client, string $method, string $path, array $options = []): array
{
try {
$response = $client->request($method, $path, $options);
} catch (RequestException $failure) {
$error = json_decode((string) $failure->getResponse()?->getBody(), true) ?? [];
throw new RuntimeException(($error['code'] ?? 'HTTP').': '.($error['message'] ?? $failure->getMessage()), 0, $failure);
}
return json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
}
$activation = call($client, 'POST', 'activations', [
'json' => ['service' => 'telegram', 'country' => 'indonesia', 'max_price_minor' => 30],
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
]);
echo 'Number: '.$activation['phone_number'].PHP_EOL;
while ($activation['status'] === 'WAITING_SMS') {
$activation = call($client, 'GET', 'activations/'.$activation['id'], ['query' => ['wait' => 25]]);
}
if ($activation['sms'] !== []) {
echo 'Code: '.$activation['sms'][array_key_last($activation['sms'])]['code'].PHP_EOL;
if ($activation['status'] === 'CODE_RECEIVED') {
call($client, 'POST', 'activations/'.$activation['id'].'/finish');
}
} else {
echo 'No code arrived, the charge was refunded'.PHP_EOL;
}
Go
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
const api = "https://smsgrab.com/api/dev/v1"
type Activation struct {
ID string `json:"id"`
Status string `json:"status"`
PhoneNumber string `json:"phone_number"`
PriceMinor int64 `json:"price_minor"`
SMS []struct {
Code string `json:"code"`
Text string `json:"text"`
} `json:"sms"`
}
var client = &http.Client{Timeout: 40 * time.Second}
func call(method, path string, body any, idempotencyKey string, out any) error {
var payload bytes.Buffer
if body != nil {
if err := json.NewEncoder(&payload).Encode(body); err != nil {
return err
}
}
request, err := http.NewRequest(method, api+path, &payload)
if err != nil {
return err
}
request.Header.Set("Authorization", "Bearer "+os.Getenv("SMSGRAB_API_KEY"))
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if idempotencyKey != "" {
request.Header.Set("Idempotency-Key", idempotencyKey)
}
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 300 {
var failure struct {
Code string `json:"code"`
Message string `json:"message"`
}
_ = json.NewDecoder(response.Body).Decode(&failure)
return fmt.Errorf("%d %s: %s", response.StatusCode, failure.Code, failure.Message)
}
if out == nil {
return nil
}
return json.NewDecoder(response.Body).Decode(out)
}
func idempotencyKey() string {
buffer := make([]byte, 16)
_, _ = rand.Read(buffer)
return hex.EncodeToString(buffer)
}
func main() {
var activation Activation
order := map[string]any{"service": "telegram", "country": "indonesia", "max_price_minor": 30}
if err := call("POST", "/activations", order, idempotencyKey(), &activation); err != nil {
panic(err)
}
fmt.Println("Number:", activation.PhoneNumber)
for activation.Status == "WAITING_SMS" {
if err := call("GET", "/activations/"+activation.ID+"?wait=25", nil, "", &activation); err != nil {
panic(err)
}
}
if len(activation.SMS) == 0 {
fmt.Println("No code arrived, the charge was refunded")
return
}
fmt.Println("Code:", activation.SMS[len(activation.SMS)-1].Code)
if activation.Status == "CODE_RECEIVED" {
if err := call("POST", "/activations/"+activation.ID+"/finish", nil, "", nil); err != nil {
panic(err)
}
}
}
Each program buys a number, waits for the code with long polling, prints it and finishes the activation. Set SMSGRAB_API_KEY first. The curl version needs jq and uuidgen, Python 3.10 or newer with requests, Node.js 18 or newer (save it as buy.mjs), PHP 8.1 or newer with guzzlehttp/guzzle, and Go 1.21 or newer.
The number is yours until expires_at, usually 10 to 20 minutes depending on the provider. If no code arrives in time it expires and the charge is refunded automatically. Prefer pushes? Subscribe to webhooks instead of polling.
Автентифікація
Кожен запит містить один із ваших API-ключів.
GET /api/dev/v1/balance HTTP/1.1
Host: smsgrab.com
Authorization: Bearer sgk_your_key
X-Api-Key: sgk_… works as well. A key in the query string is accepted only by the compatible endpoint. There is no CORS: keys belong on your servers, never in browsers or in apps you ship to users.
| Situation | Answer |
|---|---|
| No key, a malformed or an unknown key | 401 UNAUTHORIZED · API_KEY_INVALID |
| Revoked key | 401 UNAUTHORIZED · API_KEY_REVOKED |
| Expired key, or an old secret after its rotation grace | 401 UNAUTHORIZED · API_KEY_EXPIRED |
| Address outside the key's allowlist | 403 FORBIDDEN · API_KEY_IP_NOT_ALLOWED |
| The key lacks the needed scope | 403 FORBIDDEN · API_KEY_SCOPE |
| E-mail address no longer verified | 403 FORBIDDEN · EMAIL_NOT_VERIFIED |
| Account suspended, or developer access blocked | 403 FORBIDDEN · ACCOUNT_BLOCKED, DEVELOPER_ACCESS_BLOCKED |
| 30+ rejected keys from one network within a minute | 429 RATE_LIMITED for that network |
API-ключі
Ключі створюються, обмежуються й замінюються у вашому обліковому записі.
| Format | sgk_ followed by 40 letters and digits. Shown once, when it is created or rotated; we store only a keyed hash. |
|---|---|
| Scopes | read (balance, catalogue, prices, activations, usage) or read + purchase (also buy, cancel and finish). Add topup to either to create and follow top-ups. |
| IP allowlist | Up to 50 IPv4 or IPv6 addresses or CIDR ranges. Empty means any address. |
| Daily spend cap | Optional, per UTC day, counted over the key's net charges. A purchase that would pass it answers 403 DAILY_SPEND_CAP_REACHED and nothing is charged. |
| Expiry | Optional, at most two years ahead. |
| Rotation | A new secret for the same key, settings, usage and webhooks. The old secret keeps working for the grace period you choose (up to 72 hours), so you can deploy without downtime. |
| Revocation | Immediate and final. The key's webhooks are switched off. |
| Per account | Up to 10 active keys. |
Creating or rotating a key, adding a webhook, rolling its secret and widening a key's access (more scopes, a wider allowlist, a higher cap or a later expiry) ask for your password again, and for your two-step code when it is on. Revoking and tightening never do.
Ціни
Ви платите ціну застосунку за вирахуванням гуртової знижки.
price = ceil(list_price × (100 − discount_percent) / 100)
price = max(price, minimum_price)
price = min(price, list_price)
list_price is the price of the same number in the app. discount_percent is your wholesale discount: the tier you reached with your spend of the last 30 days on every channel (the app, the website, the Telegram bot, the API and the compatible endpoint, minus refunds), or the fixed discount of an approved reseller, whichever is larger. A tier applies within five minutes of crossing its threshold.
minimum_price keeps a few very cheap numbers above our cost, so their discount can be smaller. Your price is never above the list price. Volume tiers are switched off right now; reseller discounts still apply.
The price is fixed when you buy and stored on the activation. Read it with GET /prices and send max_price_minor to protect yourself from a change in between. Your discount and tier are in GET /me.
Реселери
Продавайте номери під своїм брендом і обліковуйте кожну покупку за клієнтами.
Approved resellers sell numbers to their own customers under their own brand. Your customers never see SmsGrab: you buy through this API, show the number and the code in your product and set your own prices. Apply on the wholesale page; once approved, your fixed discount applies to every purchase of the account.
- Send
customer_refwithPOST /activations(or&customer_ref=with the compatiblegetNumber) to tag each purchase with your own customer. Use an opaque id, never personal data. - Filter with
GET /activations?customer_ref=…to answer your customer's questions, and refund them when the activation reportsrefunded: true. GET /statementsums charges, refunds and savings per day, customer and service for your bookkeeping; your account has the same statement with a CSV of every activation.- Your reseller account can have its own limits for numbers waiting at once and daily spend. A purchase past the daily limit answers
403 WHOLESALE_DAILY_LIMIT_REACHEDand charges nothing.
curl
curl -s -X POST \
https://smsgrab.com/api/dev/v1/activations \
-H "Authorization: Bearer $SMSGRAB_API_KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{
"service": "whatsapp",
"country": "indonesia",
"customer_ref": "shop-4821"
}'
Python
activation = requests.post(
"https://smsgrab.com/api/dev/v1/activations",
headers={
"Authorization": f"Bearer {key}",
"Idempotency-Key": str(uuid.uuid4()),
},
json={
"service": "whatsapp",
"country": "indonesia",
"customer_ref": customer.ref,
},
timeout=30,
).json()
Node.js
const url = 'https://smsgrab.com/api/dev/v1/activations';
const activation = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${key}`,
'Content-Type': 'application/json',
'Idempotency-Key': crypto.randomUUID(),
},
body: JSON.stringify({
service: 'whatsapp',
country: 'indonesia',
customer_ref: customer.ref,
}),
}).then((response) => response.json());
PHP
$activation = json_decode((string) $client->post('activations', [
'json' => [
'service' => 'whatsapp',
'country' => 'indonesia',
'customer_ref' => $customer->ref,
],
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
])->getBody(), true);
Go
order := map[string]any{
"service": "whatsapp",
"country": "indonesia",
"customer_ref": customer.Ref,
}
err := call("POST", "/activations", order, idempotencyKey(), &activation)
Поповнення
Поповнюйте баланс криптовалютою зі своїх систем і відстежуйте кожен платіж до зарахування.
A key with the topup scope adds money to your balance with crypto, so an integration can keep itself funded or let an operator pay without opening the website. There is no processor and no fee: you send coins to an address we watch, and the balance is credited once the network reaches finality.
- Read the networks, coins and limits with
GET /topups/options. - Create a top-up with
POST /topups: the network, the coin, the amount in cents, your ownreferenceand anIdempotency-Key. - Send exactly
amountof the coin toaddress(on TON withmemoas the comment) beforeexpires_at, usually 30 minutes. - Follow it with long polling or the
topup.*webhooks untilstatusiscredited.
- Exact amounts.
amountends in a few extra cents that tell the top-up apart; they are credited too. Exchanges that take their fee from the amount break the match: such payments go to review and are matched by hand. - Finality. Nothing is credited before the network is final (
confirmations). A reorganisation before that only delays the credit; money is credited at most once. - Late payments. An exact payment that arrives after
expires_atbut beforelate_untilis still credited, at the lower of the locked and the current rate. - Limits. An account has a limit of top-ups waiting at once and a 24-hour amount; new accounts start lower. The errors say which limit applies and what is left.
- Receipts. Every credited top-up has a receipt in your account, listed with the purchases of the API.
curl
topup=$(curl -sS -X POST https://smsgrab.com/api/dev/v1/topups \
-H "Authorization: Bearer $SMSGRAB_API_KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{"network":"tron","asset":"usdt","amount_minor":5000,"reference":"order-1042"}')
id=$(jq -r .id <<<"$topup")
echo "Send exactly $(jq -r .amount <<<"$topup") USDT to $(jq -r .address <<<"$topup")"
status=$(jq -r .status <<<"$topup")
while [[ "$status" =~ ^(pending|detected|confirming)$ ]]; do
topup=$(curl -sS "https://smsgrab.com/api/dev/v1/topups/$id?wait=25" -H "Authorization: Bearer $SMSGRAB_API_KEY")
status=$(jq -r .status <<<"$topup")
done
echo "Finished as $status, credited $(jq -r .credited_minor <<<"$topup") cents"
Python
import os, uuid, requests
api = "https://smsgrab.com/api/dev/v1"
auth = {"Authorization": f"Bearer {os.environ['SMSGRAB_API_KEY']}"}
topup = requests.post(
f"{api}/topups",
headers={**auth, "Idempotency-Key": str(uuid.uuid4())},
json={"network": "tron", "asset": "usdt", "amount_minor": 5000, "reference": "order-1042"},
timeout=30,
).json()
print(f"Send exactly {topup['amount']} USDT to {topup['address']}")
while topup["status"] in ("pending", "detected", "confirming"):
topup = requests.get(f"{api}/topups/{topup['id']}", headers=auth, params={"wait": 25}, timeout=40).json()
print(f"Finished as {topup['status']}, credited {topup['credited_minor']} cents")
Node.js
const api = 'https://smsgrab.com/api/dev/v1';
const auth = { Authorization: `Bearer ${process.env.SMSGRAB_API_KEY}` };
let topup = await fetch(`${api}/topups`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID() },
body: JSON.stringify({ network: 'tron', asset: 'usdt', amount_minor: 5000, reference: 'order-1042' }),
}).then((response) => response.json());
console.log(`Send exactly ${topup.amount} USDT to ${topup.address}`);
while (['pending', 'detected', 'confirming'].includes(topup.status)) {
topup = await fetch(`${api}/topups/${topup.id}?wait=25`, { headers: auth }).then((response) => response.json());
}
console.log(`Finished as ${topup.status}, credited ${topup.credited_minor} cents`);
PHP
$client = new GuzzleHttp\Client([
'base_uri' => 'https://smsgrab.com/api/dev/v1/',
'headers' => ['Authorization' => 'Bearer '.getenv('SMSGRAB_API_KEY')],
'timeout' => 40,
]);
$topup = json_decode((string) $client->post('topups', [
'json' => ['network' => 'tron', 'asset' => 'usdt', 'amount_minor' => 5000, 'reference' => 'order-1042'],
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
])->getBody(), true);
echo "Send exactly {$topup['amount']} USDT to {$topup['address']}\n";
while (in_array($topup['status'], ['pending', 'detected', 'confirming'], true)) {
$topup = json_decode((string) $client->get("topups/{$topup['id']}", ['query' => ['wait' => 25]])->getBody(), true);
}
echo "Finished as {$topup['status']}, credited {$topup['credited_minor']} cents\n";
Go
var topup struct {
ID string `json:"id"`
Status string `json:"status"`
Amount string `json:"amount"`
Address string `json:"address"`
CreditedMinor int64 `json:"credited_minor"`
}
order := map[string]any{"network": "tron", "asset": "usdt", "amount_minor": 5000, "reference": "order-1042"}
if err := call("POST", "/topups", order, idempotencyKey(), &topup); err != nil {
log.Fatal(err)
}
fmt.Printf("Send exactly %s USDT to %s\n", topup.Amount, topup.Address)
for topup.Status == "pending" || topup.Status == "detected" || topup.Status == "confirming" {
if err := call("GET", "/topups/"+topup.ID+"?wait=25", nil, "", &topup); err != nil {
log.Fatal(err)
}
}
fmt.Printf("Finished as %s, credited %d cents\n", topup.Status, topup.CreditedMinor)
Ліміти частоти
Ліміти зберігають швидкість платформи для всіх. Більшість інтеграцій ніколи їх не досягає.
| Limit | Default | When exceeded |
|---|---|---|
| Requests per key | 600 / minute | 429 RATE_LIMITED |
| Purchases per key | 60 / minute | 429 RATE_LIMITED |
| Requests per account, all keys | 3 000 / minute | 429 RATE_LIMITED |
| Numbers waiting at once per account | 100 | 422 VALIDATION · ACTIVATION_LIMIT_REACHED |
| Held long-poll requests per key | 20 | 429 RATE_LIMITED |
| Webhooks per key | 3 | 422 VALIDATION · WEBHOOK_LIMIT_REACHED |
Limits use one-minute windows. Every answer carries RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (seconds until the window resets) and RateLimit-Policy (for example 600;w=60) for the tightest limit; a 429 also carries Retry-After. Purchases count against both the request and the purchase limit. Numbers waiting at once include numbers bought in the app. SmsGrab can raise the limits of a key or an account on request.
Помилки
Невдалі виклики відповідають стабільним кодом і, де це корисно, точнішою причиною.
{
"code": "NO_NUMBERS_AVAILABLE",
"message": "No numbers available for this service and country",
"reason": "OUT_OF_STOCK"
}
code is stable and tells you what to do; reason, when present, is more precise. message is meant for people and may change. New reason values can appear at any time: treat an unknown one like its code.
-
401
UNAUTHORIZEDAPI_KEY_INVALIDAPI_KEY_REVOKEDAPI_KEY_EXPIRED
No key, a malformed or unknown key, a revoked key, an expired key, or an old secret after its rotation grace.
-
402
INSUFFICIENT_BALANCEYour balance does not cover the price. Nothing is charged.
-
403
FORBIDDENAPI_KEY_IP_NOT_ALLOWEDAPI_KEY_SCOPEEMAIL_NOT_VERIFIEDACCOUNT_BLOCKEDDEVELOPER_ACCESS_BLOCKEDDAILY_SPEND_CAP_REACHEDWHOLESALE_DAILY_LIMIT_REACHEDWHOLESALE_RESELLER_REQUIRED
The key or the account may not do this right now. Nothing is charged.
-
404
NOT_FOUNDACTIVATION_NOT_FOUND
Unknown activation, or one of another account. Unknown paths answer it too.
-
404
SERVICE_NOT_FOUNDThe service is unknown or not sold right now.
-
404
COUNTRY_NOT_FOUNDThe country is unknown or not sold right now.
-
409
NO_NUMBERS_AVAILABLEOUT_OF_STOCKPROVIDER_OUT_OF_NUMBERS
No number could be delivered. Any charge was refunded in the same request.
-
409
PRICE_CHANGEDThe price is above
max_price_minoror rose while buying. Nothing is charged; read the price again. -
413
VALIDATIONThe request body is too large.
-
415
VALIDATIONThe body is not
application/json. -
422
VALIDATIONACTIVATION_LIMIT_REACHEDACTIVATION_CODE_RECEIVEDACTIVATION_FINISHEDACTIVATION_NO_CODE_YETACTIVATION_CANCEL_NOT_YETACTIVATION_SMS_REQUEST_UNSUPPORTEDACTIVATION_SMS_REQUEST_CLOSEDACTIVATION_SMS_REQUEST_REFUSEDCUSTOMER_REF_INVALIDWHOLESALE_PERIOD_INVALID
A field is missing or malformed (the message names it), or the activation is in the wrong state.
-
429
RATE_LIMITEDToo many requests. Wait the number of seconds in
Retry-After. -
5xx
INTERNALSomething failed on our side or at the number provider. Retry with exponential backoff and quote
X-Request-Idif it persists.
Ідемпотентність
Безпечний повтор покупки ніколи не купує двічі.
Send an Idempotency-Key header with POST /activations: 1 to 128 letters, digits, ., _, : or -, unique per purchase (a UUID is ideal). If the connection drops and you retry with the same key, you get the first answer again with Idempotent-Replayed: true instead of a second number.
- Keys belong to your account and are kept for 24 hours.
- The same key with a different body (service, country or
max_price_minor) answers422 VALIDATION. - A retry while the first request is still running answers
422 VALIDATION; wait a moment and retry. - Only successes are stored. After an error the same key buys again, so a retry after
409 NO_NUMBERS_AVAILABLEis safe. - Cancel and finish accept an
Idempotency-Keytoo, and repeating them on an activation that already has that status succeeds anyway.
Адреси API
Усі адреси розташовані під базовою адресою й відповідають у JSON.
- GET
/meКлюч, що виконує виклик, ваша ціна та ліміти. - GET
/balanceБаланс вашого облікового запису. - GET
/countriesКраїни з номерами в наявності. - GET
/servicesСервіси, за бажанням лише ті, що є в одній країні. - GET
/pricesВаші ціни з урахуванням знижки та наявність за кожною пропозицією. - POST
/activationsКупити номер. - GET
/activationsСписок ваших активацій. - GET
/activations/{id}Одна активація, за бажанням із long polling. - POST
/activations/{id}/cancelСкасувати до приходу коду й отримати повернення. - POST
/activations/{id}/finishЗавершити активацію після коду. - POST
/activations/{id}/retrydeveloper.docs.endpoints.retry - GET
/usageЗапити, покупки й витрати в часі. - GET
/statementВаша виписка реселера за днями, клієнтами й сервісами. - GET
/topups/optionsМережі та монети для поповнення. - POST
/topupsСтворити криптопоповнення. - GET
/topupsСписок ваших поповнень. - GET
/topups/{id}Одне поповнення, з необов’язковим long polling. - POST
/topups/{id}/cancelСкасувати поповнення до появи платежу.
Besides the errors listed under each endpoint, every endpoint can answer these:
- 401
UNAUTHORIZEDAPI_KEY_INVALID, API_KEY_REVOKED, API_KEY_EXPIRED The key is missing, unknown, revoked or expired. - 403
FORBIDDENAPI_KEY_IP_NOT_ALLOWED, EMAIL_NOT_VERIFIED, ACCOUNT_BLOCKED, DEVELOPER_ACCESS_BLOCKED The key or the account may not use the API right now. - 429
RATE_LIMITEDA per-key or per-account limit is reached. WaitRetry-Afterseconds. - 503
FEATURE_UNAVAILABLEThe developer API is switched off for maintenance.
GET
/me
Ключ, що виконує виклик, ваша ціна та ліміти. права: read
pricing.discount_percent is your wholesale discount right now and pricing.source says where it comes from: none, tier (your 30-day volume on every channel) or reseller (the fixed discount of an approved reseller; you always get the larger of the two). tier and next_tier are null when they do not apply, and program_enabled is false while volume tiers are switched off.
limits.active_activations counts every number of the account that is still waiting or holds a code, including numbers bought in the app.
spend_today_minor is what this key spent today (UTC), net of refunds.
curl -s https://smsgrab.com/api/dev/v1/me \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"key": {
"id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"name": "production bot",
"display_prefix": "sgk_4hT9wQ",
"last4": "Xa7Q",
"scopes": [
"read",
"purchase"
],
"ip_allowlist": [
"203.0.113.0/24"
],
"daily_spend_cap_minor": 5000,
"rate_limit_per_minute": 600,
"purchase_limit_per_minute": 60,
"status": "active",
"expires_at": null,
"created_at": "2026-09-27T09:58:41.006Z",
"last_used_at": "2026-09-27T10:05:00.112Z",
"rotated_at": null,
"previous_expires_at": null,
"revoked_at": null,
"revoked_by": null,
"webhooks_count": 1,
"spend_today_minor": 420
},
"account": {
"user_id": "2b4b9c1d-3e5f-4a6b-8c7d-9e0f1a2b3c4d",
"email": "dev@example.org"
},
"currency": "USD",
"pricing": {
"discount_percent": 5,
"source": "tier",
"program_enabled": true,
"trailing_30d_spend_minor": 31250,
"tier": {
"level": 2,
"min_spend_minor": 25000,
"discount_percent": 5
},
"next_tier": {
"level": 3,
"min_spend_minor": 100000,
"discount_percent": 8,
"remaining_minor": 68750
},
"tiers": [
{
"level": 1,
"min_spend_minor": 5000,
"discount_percent": 3
},
{
"level": 2,
"min_spend_minor": 25000,
"discount_percent": 5
},
{
"level": 3,
"min_spend_minor": 100000,
"discount_percent": 8
},
{
"level": 4,
"min_spend_minor": 500000,
"discount_percent": 12
}
]
},
"limits": {
"max_active_activations": 100,
"active_activations": 3,
"spend_today_minor": 420
}
}
GET
/balance
Баланс вашого облікового запису. права: read
The same balance as in the app and on the website, in cents. Top it up in your wallet.
curl -s https://smsgrab.com/api/dev/v1/balance \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"balance_minor": 12345,
"currency": "USD",
"updated_at": "2026-09-27T10:02:11.482Z"
}
GET
/countries
Країни з номерами в наявності. права: read
Every country with at least one service in stock, the most popular first and then by name. The list follows the live catalogue, so new countries appear without a new API version.
compat_id is the country's id in the compatible endpoint, null when the protocol has none (use id there instead). available_numbers is the stock reported by the number providers and changes quickly.
curl -s https://smsgrab.com/api/dev/v1/countries \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"items": [
{
"id": "indonesia",
"name": "Indonesia",
"iso_code": "ID",
"dial_code": "62",
"flag_emoji": "🇮🇩",
"available_numbers": 812334,
"service_count": 402,
"compat_id": 6
}
]
}
Response headers
Cache-Controlprivate, max-age=30: the answer may be reused for 30 seconds.ETag- Send it back in
If-None-Matchto get304 Not Modifiedwhile nothing changed.
GET
/services
Сервіси, за бажанням лише ті, що є в одній країні. права: read
Without country, every service in stock somewhere with the number of countries that sell it and your cheapest price. The most popular services come first, then by name.
category is MESSAGING, SOCIAL, FINANCE, SHOPPING, GAMING, DEVELOPER or OTHER. icon_url is an icon served by SmsGrab (SVG, or PNG for clients that do not accept SVG); its v parameter changes whenever the icon changes, so you can cache it for good.
compat_code is the service's code in the compatible endpoint, null when it has none (use id there instead).
| Parameter | In | Type | Description |
|---|---|---|---|
country | query | string | A country id (indonesia), ISO code (ID) or compatible id (6). Only services in stock there are listed, min_price_minor is your price in that country and country_count is left out. |
curl -s https://smsgrab.com/api/dev/v1/services \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"items": [
{
"id": "whatsapp",
"name": "WhatsApp",
"category": "MESSAGING",
"icon_url": "https://smsgrab.com/api/v1/icons/whatsapp?v=1fceb4feb3",
"compat_code": "wa",
"country_count": 151,
"min_price_minor": 17
}
]
}
Response headers
Cache-Controlprivate, max-age=30: the answer may be reused for 30 seconds.ETag- Send it back in
If-None-Matchto get304 Not Modifiedwhile nothing changed.
Errors
- 404
COUNTRY_NOT_FOUNDcountryis unknown or has nothing in stock.
GET
/prices
Ваші ціни з урахуванням знижки та наявність за кожною пропозицією. права: read
price_minor is what you pay for that offer now, your wholesale discount included; retail_price_minor is the list price of the same number in the app. Items are sorted by service, then price, then stock.
Without filters the answer lists every offer in stock, tens of thousands of rows. Ask for compression (Accept-Encoding: gzip, curl --compressed) and reuse the answer for 30 seconds.
| Parameter | In | Type | Description |
|---|---|---|---|
service | query | string | A service id (whatsapp) or compatible code (wa). Leave it out for every service. |
country | query | string | A country id, ISO code or compatible id. Leave it out for every country. |
curl -s --compressed "https://smsgrab.com/api/dev/v1/prices?service=whatsapp&country=indonesia" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"currency": "USD",
"discount_percent": 5,
"items": [
{
"service_id": "whatsapp",
"country_id": "indonesia",
"price_minor": 34,
"retail_price_minor": 35,
"available_numbers": 30412
}
]
}
Response headers
Cache-Controlprivate, max-age=30: the answer may be reused for 30 seconds.ETag- Send it back in
If-None-Matchto get304 Not Modifiedwhile nothing changed.
Errors
- 404
SERVICE_NOT_FOUNDserviceis unknown or not sold right now. - 404
COUNTRY_NOT_FOUNDcountryis unknown or not sold right now.
POST
/activations
Купити номер. права: purchase
The body is JSON with Content-Type: application/json. The price is charged when the number is bought and stored on the activation as price_minor.
If no number can be delivered the charge is refunded within the same request and the answer is 409 NO_NUMBERS_AVAILABLE. A purchase may try more than one route for the same offer, but never charges more than the price it quotes.
The number is yours until expires_at, usually 10 to 20 minutes depending on the provider. Wait for the code with long polling or webhooks.
| Parameter | In | Type | Description |
|---|---|---|---|
service required | body | string | A service id (whatsapp) or compatible code (wa). |
country required | body | string | A country id (indonesia), ISO code (ID) or compatible id (6). |
max_price_minor | body | integer | The most you accept to pay, in cents. When the price is higher the answer is 409 PRICE_CHANGED and nothing is charged. |
customer_ref | body | string | Your own reference for the end customer you buy for, 1 to 64 letters, digits, ., _, :, @ or -. Stored on the activation, filterable in GET /activations and grouped in statements. Never shown to anyone but you. |
Idempotency-Key | header | string | 1 to 128 letters, digits, ., _, : or -, for example a UUID. A retry with the same key answers the first purchase again instead of buying twice. See Idempotency. |
curl -s -X POST https://smsgrab.com/api/dev/v1/activations \
-H "Authorization: Bearer $SMSGRAB_API_KEY" \
-H "Idempotency-Key: 7f3c2a90-4d1e-4b8a-9c6f-2e5d8a1b3c4d" \
-H "Content-Type: application/json" \
-d '{"service":"whatsapp","country":"indonesia","max_price_minor":20}'
{
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "WAITING_SMS",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": null,
"refunded": false,
"refund_minor": 0,
"sms": [],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": false
}
Response headers
Location- The address of the new activation.
Idempotent-Replayedtruewhen the answer replays an earlier purchase with the sameIdempotency-Key,falseotherwise. Sent only with anIdempotency-Key.
Errors
- 402
INSUFFICIENT_BALANCEYour balance does not cover the price. Nothing is charged. - 403
FORBIDDENAPI_KEY_SCOPE The key has read access only. - 403
FORBIDDENDAILY_SPEND_CAP_REACHED This purchase would pass the key's daily spend cap. Nothing is charged. - 403
FORBIDDENWHOLESALE_DAILY_LIMIT_REACHED The daily spend limit of your reseller account is reached. Nothing is charged. - 404
SERVICE_NOT_FOUNDserviceis unknown or not sold right now. - 404
COUNTRY_NOT_FOUNDcountryis unknown or not sold right now. - 409
NO_NUMBERS_AVAILABLEOUT_OF_STOCK, PROVIDER_OUT_OF_NUMBERS No number could be delivered. Any charge was refunded; try again or pick another country. - 409
PRICE_CHANGEDThe price is abovemax_price_minoror rose while buying. Nothing is charged. - 415
VALIDATIONThe body is notapplication/json. - 422
VALIDATIONserviceorcountryis missing,max_price_minoris not positive, or theIdempotency-Keyis malformed, was used with a different body, or its first request is still running. - 422
VALIDATIONCUSTOMER_REF_INVALIDcustomer_refis longer than 64 characters or has other characters than letters, digits,.,_,:,@and-. - 422
VALIDATIONACTIVATION_LIMIT_REACHED The account already has 100 numbers waiting or holding a code. Finish or cancel some first. - 503
PROVIDER_UNAVAILABLEPURCHASES_PAUSED, PROVIDER_PAUSED, PROVIDER_CIRCUIT_OPEN, SERVER_DRAINING Buying is paused for a moment. Nothing is charged; retry in a few seconds.
GET
/activations
Список ваших активацій. права: read
Newest first. Each item is the full activation object. next_cursor is null on the last page; a cursor only works with the filters it was issued for.
| Parameter | In | Type | Description |
|---|---|---|---|
status | query | string | active (WAITING_SMS, CODE_RECEIVED) or finished (COMPLETED, CANCELLED, EXPIRED). Leave it out for both. |
service | query | string | Only this service id. |
country | query | string | Only this country id. |
from, to | query | date-time | Only activations bought at or after from and before to (ISO 8601, for example 2026-09-27T00:00:00Z). |
source | query | string | api (default: bought through the REST API or the compatible endpoint) or all (the whole account, the app included). |
customer_ref | query | string | Only activations bought with this customer_ref. |
limit | query | integer | 1 to 100, default 50. |
cursor | query | string | next_cursor of the previous page, with the same filters. |
curl -s "https://smsgrab.com/api/dev/v1/activations?status=active&limit=20" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"items": [
{
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "CODE_RECEIVED",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": null,
"refunded": false,
"refund_minor": 0,
"sms": [
{
"code": "482913",
"text": "Your WhatsApp code is 482-913",
"sender": "WhatsApp",
"received_at": "2026-09-27T10:06:11.870Z"
}
],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": false
}
],
"next_cursor": "MjAyNi0wOS0yN1QxMDowNTowMFo.Qm8kTd9xVf2pL3"
}
Errors
- 422
VALIDATIONA filter has an unknown value, orcursoris not valid for these filters.
GET
/activations/{id}
Одна активація, за бажанням із long polling. права: read
Long polling holds a request for at most 25 seconds, then answers the current activation whether or not it changed. Use a client timeout of at least 35 seconds and simply ask again; a finished activation answers at once.
At most 20 requests per key can be held at the same time; more answer 429 RATE_LIMITED.
| Parameter | In | Type | Description |
|---|---|---|---|
id required | path | string | The activation UUID or its numeric compat_id. |
wait | query | integer | 0 to 30 seconds of long polling. The request is held until the activation changes (a new SMS or a new status) or the time runs out. |
curl -s "https://smsgrab.com/api/dev/v1/activations/100000123?wait=25" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "CODE_RECEIVED",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": null,
"refunded": false,
"refund_minor": 0,
"sms": [
{
"code": "482913",
"text": "Your WhatsApp code is 482-913",
"sender": "WhatsApp",
"received_at": "2026-09-27T10:06:11.870Z"
}
],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": false
}
Errors
- 404
NOT_FOUNDACTIVATION_NOT_FOUND No activation with this id belongs to your account. - 422
VALIDATIONwaitis not a whole number from 0 to 30.
POST
/activations/{id}/cancel
Скасувати до приходу коду й отримати повернення. права: purchase
Possible only while the activation is WAITING_SMS. The charge is refunded at once and the answer carries refunded: true. Cancelling an activation that is already cancelled answers it again.
Right after a purchase a provider may refuse a cancel for a short time. The answer is then 422 ACTIVATION_CANCEL_NOT_YET and its message says how many seconds to wait.
| Parameter | In | Type | Description |
|---|---|---|---|
id required | path | string | The activation UUID or its numeric compat_id. |
Idempotency-Key | header | string | Optional, as for buying. |
curl -s -X POST https://smsgrab.com/api/dev/v1/activations/100000123/cancel \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "CANCELLED",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": "2026-09-27T10:08:40.215Z",
"refunded": true,
"refund_minor": 17,
"sms": [],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": false
}
Errors
- 403
FORBIDDENAPI_KEY_SCOPE The key has read access only. - 404
NOT_FOUNDACTIVATION_NOT_FOUND No activation with this id belongs to your account. - 422
VALIDATIONACTIVATION_CANCEL_NOT_YET Too early to cancel this number; retry after the time in the message. - 422
VALIDATIONACTIVATION_CODE_RECEIVED A code has arrived, so the number can no longer be cancelled. Finish it instead. - 422
VALIDATIONACTIVATION_FINISHED The activation is already completed or expired.
POST
/activations/{id}/finish
Завершити активацію після коду. права: purchase
Accepted once a code has arrived (CODE_RECEIVED). Finishing an activation that is already completed answers it again. If you never finish, the activation completes by itself at expires_at.
| Parameter | In | Type | Description |
|---|---|---|---|
id required | path | string | The activation UUID or its numeric compat_id. |
Idempotency-Key | header | string | Optional, as for buying. |
curl -s -X POST https://smsgrab.com/api/dev/v1/activations/100000123/finish \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "COMPLETED",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": "2026-09-27T10:07:02.113Z",
"refunded": false,
"refund_minor": 0,
"sms": [
{
"code": "482913",
"text": "Your WhatsApp code is 482-913",
"sender": "WhatsApp",
"received_at": "2026-09-27T10:06:11.870Z"
}
],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": false
}
Errors
- 403
FORBIDDENAPI_KEY_SCOPE The key has read access only. - 404
NOT_FOUNDACTIVATION_NOT_FOUND No activation with this id belongs to your account. - 422
VALIDATIONACTIVATION_NO_CODE_YET No code has arrived yet. Wait, or cancel for a refund. - 422
VALIDATIONACTIVATION_FINISHED The activation is already cancelled or expired.
POST
/activations/{id}/retry
developer.docs.endpoints.retry права: purchase
Asks the provider to deliver one more SMS to the same number, for example after the service sent its code again. It is free and does not move expires_at.
Accepted while can_request_sms is true: the activation is CODE_RECEIVED, at least 30 seconds are left, fewer than 10 requests were made and the previous one was at least 20 seconds ago. While awaiting_next_sms is true a repeated call answers the activation unchanged.
The next SMS is added to sms and awaiting_next_sms turns false; long polling and the activation.code_received webhook report it.
| Parameter | In | Type | Description |
|---|---|---|---|
id required | path | string | The activation UUID or its numeric compat_id. |
Idempotency-Key | header | string | Optional, as for buying. |
curl -s -X POST https://smsgrab.com/api/dev/v1/activations/100000123/retry \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "CODE_RECEIVED",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": null,
"refunded": false,
"refund_minor": 0,
"sms": [
{
"code": "482913",
"text": "Your WhatsApp code is 482-913",
"sender": "WhatsApp",
"received_at": "2026-09-27T10:06:11.870Z"
}
],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": true
}
Errors
- 403
FORBIDDENAPI_KEY_SCOPE The key has read access only. - 404
NOT_FOUNDACTIVATION_NOT_FOUND No activation with this id belongs to your account. - 422
VALIDATIONACTIVATION_NO_CODE_YET The first code has not arrived yet. - 422
VALIDATIONACTIVATION_FINISHED The activation is already completed, cancelled or expired. - 422
VALIDATIONACTIVATION_SMS_REQUEST_UNSUPPORTED The provider of this number cannot send another SMS. - 422
VALIDATIONACTIVATION_SMS_REQUEST_CLOSED 10 requests were used, or less than 30 seconds are left. - 422
VALIDATIONACTIVATION_SMS_REQUEST_REFUSED The provider refused for this number right now; the next try opens after 20 seconds. - 429
RATE_LIMITEDThe previous request was less than 20 seconds ago. WaitRetry-Afterseconds. - 503
PROVIDER_UNAVAILABLEThe provider did not answer. Nothing changed; try again.
GET
/usage
Запити, покупки й витрати в часі. права: read
Counters are kept per key and UTC day and written every 30 seconds. errors counts answers of 400 and above plus error answers of the compatible endpoint; rate_limited counts 429 answers.
| Parameter | In | Type | Description |
|---|---|---|---|
from, to | query | date | YYYY-MM-DD in UTC, both included, at most 366 days apart. Default: the last 30 days. |
granularity | query | string | day (default) or month; monthly rows are dated YYYY-MM. |
key | query | string | current (default, the calling key) or all (every key of the account). |
curl -s "https://smsgrab.com/api/dev/v1/usage?granularity=day&key=all" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"currency": "USD",
"from": "2026-09-01",
"to": "2026-09-27",
"granularity": "day",
"totals": {
"requests": 48211,
"errors": 120,
"rate_limited": 3,
"purchases": 1804,
"spend_minor": 31211,
"refunds_minor": 2410,
"net_minor": 28801
},
"series": [
{
"date": "2026-09-27",
"requests": 2103,
"errors": 4,
"rate_limited": 0,
"purchases": 88,
"spend_minor": 1496,
"refunds_minor": 102,
"net_minor": 1394
}
],
"by_key": [
{
"key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"name": "production bot",
"requests": 48211,
"net_minor": 28801
}
]
}
Errors
- 422
VALIDATIONA date is malformed,fromis afterto, the range is longer than 366 days, orgranularityorkeyhas an unknown value.
GET
/statement
Ваша виписка реселера за днями, клієнтами й сервісами. права: read
For approved resellers. Every channel of the account counts: the API, the compatible endpoint, the app, the website and the Telegram bot. net is charges minus refunds; savings is what the list prices would have cost more.
by_customer lists the 100 biggest customer_ref values (null for purchases without one) and by_service the 50 biggest services. A CSV with one row per activation is in your account under Wholesale.
| Parameter | In | Type | Description |
|---|---|---|---|
from, to | query | date | YYYY-MM-DD in UTC, both included, at most 366 days apart. Default: this month so far. |
curl -s "https://smsgrab.com/api/dev/v1/statement?from=2026-10-01&to=2026-10-31" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"currency": "USD",
"from": "2026-10-01",
"to": "2026-10-31",
"totals": {
"purchases": 1804,
"refunded": 96,
"charged_minor_units": 31211,
"refunded_minor_units": 2410,
"net_minor_units": 28801,
"list_minor_units": 32001,
"savings_minor_units": 3200
},
"by_day": [
{
"day": "2026-10-08",
"purchases": 88,
"net_minor_units": 1394
}
],
"by_customer": [
{
"customer_ref": "shop-4821",
"purchases": 312,
"net_minor_units": 5480
},
{
"customer_ref": null,
"purchases": 96,
"net_minor_units": 1720
}
],
"by_service": [
{
"service_id": "whatsapp",
"service_name": "WhatsApp",
"purchases": 401,
"net_minor_units": 7230
}
],
"truncated": false
}
Errors
- 403
FORBIDDENWHOLESALE_RESELLER_REQUIRED The account is not an approved reseller. - 422
VALIDATIONWHOLESALE_PERIOD_INVALID A date is malformed,fromis afterto, or the range is longer than 366 days.
GET
/topups/options
Мережі та монети для поповнення. права: topup
Every network and coin the account can pay with right now, with the smallest and largest amount of one top-up in cents. A network or coin with available: false carries a reason (disabled, watcher, oracle, depeg, address).
indicative_usd is the current price of one coin. The rate of a top-up is locked when you create it and holds until expires_at.
curl -s https://smsgrab.com/api/dev/v1/topups/options \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"currency": "USD",
"client": "web",
"available": true,
"presets_minor": [
500,
1000,
2000,
5000,
10000
],
"invoice_ttl_seconds": 1800,
"networks": [
{
"id": "tron",
"name": "TRON",
"standard": "TRC20",
"family": "tron",
"finality_eta_seconds": 60,
"memo_required": false,
"available": true,
"reason": null,
"assets": [
{
"code": "usdt",
"symbol": "USDT",
"name": "Tether USD",
"kind": "stable",
"issuer": "Tether",
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"decimals": 6,
"min_minor": 100,
"max_minor": 200000,
"available": true,
"reason": null,
"indicative_usd": "1"
}
]
}
]
}
Errors
- 403
FORBIDDENAPI_KEY_SCOPE The key has notopupscope. - 403
FORBIDDENPAYMENT_METHOD_NOT_AVAILABLE Crypto top-ups are not offered to this account.
POST
/topups
Створити криптопоповнення. права: topup
Pay exactly amount of asset to address on network. amount ends in a few extra cents that tell this top-up apart from others; they are credited too, so expected_credit_minor is what reaches the balance. On TON add memo as the transfer comment.
Show address, amount, memo, qr and links exactly as returned. address_fingerprint lets your customer check the address in a second place.
The balance is credited once the network reaches finality, never before: see confirmations. A payment that arrives after expires_at but before late_until is still credited.
| Parameter | In | Type | Description |
|---|---|---|---|
network required | body | string | A network id from GET /topups/options, for example tron, bsc or ton. |
asset required | body | string | A coin of that network, for example usdt. |
amount_minor required | body | integer | What you want on the balance, in cents, between the coin's min_minor and max_minor. |
reference | body | string | Your own id for this top-up, 1 to 64 letters, digits, ., _, : or -. Returned on the top-up and in webhooks, and filterable in GET /topups. |
Idempotency-Key required | header | string | 1 to 128 letters, digits, ., _, : or -. The same key with the same body answers the first top-up again with 200; another body answers 409 IDEMPOTENCY_KEY_REUSED. |
curl -s -X POST https://smsgrab.com/api/dev/v1/topups \
-H "Authorization: Bearer $SMSGRAB_API_KEY" \
-H "Idempotency-Key: 1d6b0c2a-8f4e-4b1c-9d3e-7a5f2c8e1b40" \
-H "Content-Type: application/json" \
-d '{"network":"tron","asset":"usdt","amount_minor":5000,"reference":"order-1042"}'
{
"id": "8d2f61b4-3c0e-4a9b-b7d5-1e6f2a9c4b03",
"reference_code": "SG7K2M9QXA",
"status": "pending",
"notice": null,
"late": false,
"network": {
"id": "tron",
"name": "TRON",
"standard": "TRC20",
"family": "tron"
},
"asset": {
"code": "usdt",
"symbol": "USDT",
"name": "Tether USD",
"kind": "stable",
"decimals": 6,
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
},
"address": "TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy",
"address_fingerprint": "ZAD6-C8TN-F4M1-DJH9",
"amount": "50.37",
"amount_atomic": "50370000",
"memo": null,
"memo_required": false,
"solana_reference": null,
"requested_minor": 5000,
"expected_credit_minor": 5037,
"credited_minor": 0,
"currency": "USD",
"rate": {
"usd_per_unit": "1",
"source": "peg",
"locked_until": "2026-10-10T10:35:00.000Z"
},
"created_at": "2026-10-10T10:05:00.000Z",
"expires_at": "2026-10-10T10:35:00.000Z",
"late_until": "2026-10-11T10:35:00.000Z",
"server_time": "2026-10-10T10:05:00.120Z",
"confirmations": {
"current": 0,
"required": 19,
"mode": "solidified",
"eta_seconds": 60
},
"qr": "tron:TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy?amount=50.37&token=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"links": [
{
"kind": "trust",
"url": "https://link.trustwallet.com/send?asset=c195_tTR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t&address=TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy&amount=50.37"
}
],
"deposits": [],
"receipt": null,
"reference": "order-1042",
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b"
}
Response headers
Location- The address of the new top-up.
Idempotent-Replayedtruewhen the answer replays an earlier top-up with the sameIdempotency-Key.
Other answers
- 200A retry with the same
Idempotency-Keyand the same body answers the first top-up again, withIdempotent-Replayed: true. Nothing new is created.
Errors
- 403
FORBIDDENAPI_KEY_SCOPE The key has notopupscope. - 409
CONFLICTIDEMPOTENCY_KEY_REUSED TheIdempotency-Keywas used with another body. - 409
CONFLICTRAIL_UNAVAILABLE This network or coin is paused;details.detailsays why. Pick another one. - 409
CONFLICTTOO_MANY_OPEN_INVOICES The account already has the most top-ups waiting for payment. Let one finish, expire or cancel it. - 409
CONFLICTPAYMENT_LIMIT_REACHED The top-up would pass the account's 24-hour limit;details.remaining_minoris what can still be added. - 422
VALIDATIONIDEMPOTENCY_KEY_REQUIRED TheIdempotency-Keyheader is missing. - 422
VALIDATIONRAIL_INVALIDnetworkorassetis missing or not offered. - 422
VALIDATIONAMOUNT_OUT_OF_RANGEamount_minoris outsidemin_minorandmax_minorof the coin;detailshas both. - 422
VALIDATIONTOPUP_REFERENCE_INVALIDreferenceis longer than 64 characters or has other characters than letters, digits,.,_,:and-. - 429
RATE_LIMITEDCRYPTO_INVOICE_RATE_LIMITED Too many top-ups in a short time. WaitRetry-Afterseconds. - 503
FEATURE_UNAVAILABLERAIL_BUSY Every unique amount of this coin is in use for a moment. Retry in a minute or pick another network. - 503
FEATURE_UNAVAILABLEPAYMENTS_DISABLED Crypto top-ups are switched off for a moment.
GET
/topups
Список ваших поповнень. права: topup
Top-ups created through the developer API on this account, newest first. Top-ups made in the app, on the website or in Telegram are not listed.
| Parameter | In | Type | Description |
|---|---|---|---|
status | query | string | open (waiting for payment or confirming), done (credited, expired, cancelled or under review) or all. Default: all. |
reference | query | string | Only top-ups with this reference. |
cursor | query | string | The next_cursor of the previous page. |
limit | query | integer | 1 to 100. Default: 20. |
curl -s "https://smsgrab.com/api/dev/v1/topups?status=open" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"items": [
{
"id": "8d2f61b4-3c0e-4a9b-b7d5-1e6f2a9c4b03",
"reference_code": "SG7K2M9QXA",
"status": "pending",
"notice": null,
"late": false,
"network": {
"id": "tron",
"name": "TRON",
"standard": "TRC20",
"family": "tron"
},
"asset": {
"code": "usdt",
"symbol": "USDT",
"name": "Tether USD",
"kind": "stable",
"decimals": 6,
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
},
"address": "TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy",
"address_fingerprint": "ZAD6-C8TN-F4M1-DJH9",
"amount": "50.37",
"amount_atomic": "50370000",
"memo": null,
"memo_required": false,
"solana_reference": null,
"requested_minor": 5000,
"expected_credit_minor": 5037,
"credited_minor": 0,
"currency": "USD",
"rate": {
"usd_per_unit": "1",
"source": "peg",
"locked_until": "2026-10-10T10:35:00.000Z"
},
"created_at": "2026-10-10T10:05:00.000Z",
"expires_at": "2026-10-10T10:35:00.000Z",
"late_until": "2026-10-11T10:35:00.000Z",
"server_time": "2026-10-10T10:05:00.120Z",
"confirmations": {
"current": 0,
"required": 19,
"mode": "solidified",
"eta_seconds": 60
},
"qr": "tron:TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy?amount=50.37&token=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"links": [
{
"kind": "trust",
"url": "https://link.trustwallet.com/send?asset=c195_tTR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t&address=TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy&amount=50.37"
}
],
"deposits": [],
"receipt": null,
"reference": "order-1042",
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b"
}
],
"next_cursor": null
}
Errors
- 422
VALIDATIONstatushas an unknown value,limitis out of range orcursoris malformed.
GET
/topups/{id}
Одне поповнення, з необов’язковим long polling. права: topup
status moves from pending to detected and confirming and ends as credited, expired, cancelled or review. notice explains anything unusual: underpaid (less arrived and was credited), overpaid, late, review, depeg or dropped.
deposits lists every transfer seen for this top-up with its transaction id, explorer link and confirmations. receipt appears once the balance is credited.
| Parameter | In | Type | Description |
|---|---|---|---|
id required | path | string | The top-up id. |
wait | query | integer | 1 to 30 seconds. While the top-up is open, the answer waits until it changes or the time is up. |
curl -s "https://smsgrab.com/api/dev/v1/topups/8d2f61b4-3c0e-4a9b-b7d5-1e6f2a9c4b03?wait=25" \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"id": "8d2f61b4-3c0e-4a9b-b7d5-1e6f2a9c4b03",
"reference_code": "SG7K2M9QXA",
"status": "credited",
"notice": null,
"late": false,
"network": {
"id": "tron",
"name": "TRON",
"standard": "TRC20",
"family": "tron"
},
"asset": {
"code": "usdt",
"symbol": "USDT",
"name": "Tether USD",
"kind": "stable",
"decimals": 6,
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
},
"address": "TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy",
"address_fingerprint": "ZAD6-C8TN-F4M1-DJH9",
"amount": "50.37",
"amount_atomic": "50370000",
"memo": null,
"memo_required": false,
"solana_reference": null,
"requested_minor": 5000,
"expected_credit_minor": 5037,
"credited_minor": 5037,
"currency": "USD",
"rate": {
"usd_per_unit": "1",
"source": "peg",
"locked_until": "2026-10-10T10:35:00.000Z"
},
"created_at": "2026-10-10T10:05:00.000Z",
"expires_at": "2026-10-10T10:35:00.000Z",
"late_until": "2026-10-11T10:35:00.000Z",
"server_time": "2026-10-10T10:05:00.120Z",
"confirmations": {
"current": 19,
"required": 19,
"mode": "solidified",
"eta_seconds": 0
},
"qr": "tron:TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy?amount=50.37&token=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"links": [
{
"kind": "trust",
"url": "https://link.trustwallet.com/send?asset=c195_tTR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t&address=TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy&amount=50.37"
}
],
"deposits": [
{
"id": "2b7c9e10-4d3a-4f6b-8e21-9c0d1a2b3c4d",
"status": "credited",
"txid": "81832963394b6f0e2d1c9a8b7f6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0f53a6e",
"explorer_url": "https://tronscan.org/#/transaction/81832963394b6f0e2d1c9a8b7f6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0f53a6e",
"asset": "usdt",
"amount": "50.37",
"confirmations": 19,
"required": 19,
"final": true,
"credited_minor": 5037,
"late": false,
"first_seen_at": "2026-10-10T10:07:41.002Z"
}
],
"receipt": {
"entry_id": "6a1b2c3d-4e5f-4a7b-8c9d-0e1f2a3b4c5d",
"number": "SGR-1WA5-MHTK-BN25"
},
"reference": "order-1042",
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b"
}
Errors
- 404
NOT_FOUNDINVOICE_NOT_FOUND Unknown top-up, or one of another account or created outside the developer API.
POST
/topups/{id}/cancel
Скасувати поповнення до появи платежу. права: topup
Only a top-up that is still pending with no transfer seen. An exact payment that arrives later anyway is still credited.
| Parameter | In | Type | Description |
|---|---|---|---|
id required | path | string | The top-up id. |
curl -s -X POST https://smsgrab.com/api/dev/v1/topups/8d2f61b4-3c0e-4a9b-b7d5-1e6f2a9c4b03/cancel \
-H "Authorization: Bearer $SMSGRAB_API_KEY"
{
"id": "8d2f61b4-3c0e-4a9b-b7d5-1e6f2a9c4b03",
"reference_code": "SG7K2M9QXA",
"status": "cancelled",
"notice": null,
"late": false,
"network": {
"id": "tron",
"name": "TRON",
"standard": "TRC20",
"family": "tron"
},
"asset": {
"code": "usdt",
"symbol": "USDT",
"name": "Tether USD",
"kind": "stable",
"decimals": 6,
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
},
"address": "TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy",
"address_fingerprint": "ZAD6-C8TN-F4M1-DJH9",
"amount": "50.37",
"amount_atomic": "50370000",
"memo": null,
"memo_required": false,
"solana_reference": null,
"requested_minor": 5000,
"expected_credit_minor": 5037,
"credited_minor": 0,
"currency": "USD",
"rate": {
"usd_per_unit": "1",
"source": "peg",
"locked_until": "2026-10-10T10:35:00.000Z"
},
"created_at": "2026-10-10T10:05:00.000Z",
"expires_at": "2026-10-10T10:35:00.000Z",
"late_until": "2026-10-11T10:35:00.000Z",
"server_time": "2026-10-10T10:05:00.120Z",
"confirmations": {
"current": 0,
"required": 19,
"mode": "solidified",
"eta_seconds": 60
},
"qr": "tron:TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy?amount=50.37&token=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"links": [
{
"kind": "trust",
"url": "https://link.trustwallet.com/send?asset=c195_tTR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t&address=TSViE3S1p5f4PcJkz2qGHkCDjKq8R1AEfy&amount=50.37"
}
],
"deposits": [],
"receipt": null,
"reference": "order-1042",
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b"
}
Errors
- 404
NOT_FOUNDINVOICE_NOT_FOUND Unknown top-up. - 409
CONFLICTINVOICE_NOT_CANCELLABLE A transfer for it was already seen, or it is no longer pending.
Життєвий цикл активації
Від покупки до коду активація проходить кілька станів.
WAITING_SMSCODE_RECEIVEDCOMPLETED
WAITING_SMS: the number is ready and waits for the first message. You can cancel it for a full refund.CODE_RECEIVED: at least one SMS arrived.smsholds every message, oldest first, withcode,text,senderandreceived_at; more messages may follow untilexpires_at.COMPLETED: you finished it, or its time ran out after a code. Nothing is refunded.CANCELLED: you cancelled it while it was waiting.EXPIRED: no code arrived beforeexpires_at. Both are refunded, withrefunded: trueandrefund_minorset.
expires_at is set by the number provider, usually 10 to 20 minutes after the purchase; always read it rather than assuming a fixed time. finished_at is the time of the final status. Cancel is accepted only while waiting, finish only once a code has arrived.
Long polling. GET /activations/{id}?wait=25 holds the request until the activation changes or the time runs out, then answers the current object. It replaces tight polling loops and costs one request per change.
Вебхуки
Вебхуки одразу надсилають на ваш сервер події активацій і поповнень.
A webhook belongs to one API key and receives the events of the numbers bought and the top-ups created with that key, through the REST API or the compatible endpoint, plus the account-wide balance.low. Add up to 3 per key in your account, choose its events, and copy its secret (whsec_…) once.
| Event | When | data |
|---|---|---|
activation.created | A number was bought with the webhook's key. | activation |
activation.code_received | An SMS arrived; one event per message. | activation with every SMS so far |
activation.completed | You finished it, or its time ran out after a code. | activation |
activation.cancelled | It was cancelled before a code and refunded. | activation |
activation.expired | No code arrived before expires_at; refunded. | activation |
activation.refunded | The charge went back to your balance. | activation with refund_minor |
balance.low | Your balance fell below your alert amount, once per drop. | balance_minor, currency, threshold_minor |
topup.created | A top-up was created with the webhook's key. | topup |
topup.confirming | A transfer for it was seen and waits for finality. | topup |
topup.credited | Its money reached your balance; also for late payments. | topup |
topup.expired | No payment arrived before expires_at. | topup |
topup.review | It needs a manual check, for example another coin arrived. | topup |
webhook.test | You sent a test from your account. | message |
The activation in data is the same object as in GET /activations/{id}, and the topup the same as in GET /topups/{id}. When the SMS texts would make it longer than about 15,000 characters, the texts are shortened; codes always stay complete.
POST /smsgrab/webhook HTTP/1.1
Content-Type: application/json
User-Agent: SmsGrab-Webhooks/1.0
SmsGrab-Event: activation.code_received
SmsGrab-Delivery: 9f7d6c1e-2b4a-4f0e-9c3d-1a2b3c4d5e6f
SmsGrab-Signature: t=1790503572,v1=3b9a0c5e7d2f41a8b6c9e0d1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5
{
"id": "evt_4e1f9a0b2c3d4e5f8a9b0c1d2e3f4a5b",
"type": "activation.code_received",
"created_at": "2026-09-27T10:06:11.870Z",
"api_version": "2026-09-27",
"data": {
"activation": {
"id": "5c1d0c2e-9f3a-4b7e-8a61-2f0c9d4e7b10",
"compat_id": 100000123,
"status": "CODE_RECEIVED",
"service_id": "whatsapp",
"service_name": "WhatsApp",
"country_id": "indonesia",
"country_name": "Indonesia",
"country_iso_code": "ID",
"phone_number": "+6281234567890",
"price_minor": 17,
"currency": "USD",
"created_at": "2026-09-27T10:05:00.000Z",
"expires_at": "2026-09-27T10:25:00.000Z",
"finished_at": null,
"refunded": false,
"refund_minor": 0,
"sms": [
{
"code": "482913",
"text": "Your WhatsApp code is 482-913",
"sender": "WhatsApp",
"received_at": "2026-09-27T10:06:11.870Z"
}
],
"api_key_id": "0b8e2a41-7c1d-4e5f-9a3b-6c7d8e9f0a1b",
"customer_ref": null,
"can_request_sms": false,
"awaiting_next_sms": false
}
}
}
- Success is any
2xxanswer within 10 seconds. Redirects are never followed and the response body is ignored. - Retries follow after 1 minute, 5 minutes, 15 minutes, 1 hour, 3 hours, 6 hours, 12 hours and 24 hours (±10 %), nine attempts in all; then the delivery is marked
dead. - De-duplicate by the event
id: a retry or a redelivery repeats it, whileSmsGrab-Deliverynames the delivery to one webhook. - Order: the events of one activation are delivered one after another, in order.
- Switching off:
410 Goneswitches the webhook off at once. After 50 failed attempts in a row spanning at least 24 hours it is switched off and you get a notification. - URLs must be
https://on port 443 or 1024–65535 and use a host name that resolves only to public addresses. Private, loopback, link-local and reserved ranges are refused, when you save and before every delivery. - History: deliveries are kept 30 days. Send a test event, inspect every attempt and redeliver from your account.
Перевірка підписів
Перевіряйте кожну доставку, перш ніж їй довіряти.
Every delivery carries SmsGrab-Signature: t=<unix seconds>,v1=<hex>. v1 is the lowercase hex HMAC-SHA256 of <t>.<raw body> keyed with your webhook secret.
- Read the raw request body before any JSON parsing; a re-encoded body does not match.
- Compute the HMAC of the
tvalue, a dot and the raw body, and compare it withv1in constant time. - Reject a
tmore than 300 seconds away from your clock, then answer2xxquickly and do slow work afterwards.
Rolling the secret in your account takes effect at once for new attempts. Each example below is a complete receiver.
PHP
<?php
function verifySmsGrabSignature(string $header, string $body, string $secret, int $tolerance = 300): bool
{
$parts = [];
foreach (explode(',', $header) as $part) {
[$name, $value] = array_pad(explode('=', trim($part), 2), 2, '');
$parts[$name] = $value;
}
$timestamp = $parts['t'] ?? '';
if (! ctype_digit($timestamp) || ($parts['v1'] ?? '') === '') {
return false;
}
$expected = hash_hmac('sha256', $timestamp.'.'.$body, $secret);
return abs(time() - (int) $timestamp) <= $tolerance && hash_equals($expected, $parts['v1']);
}
$body = (string) file_get_contents('php://input');
$secret = (string) getenv('SMSGRAB_WEBHOOK_SECRET');
if (! verifySmsGrabSignature($_SERVER['HTTP_SMSGRAB_SIGNATURE'] ?? '', $body, $secret)) {
http_response_code(400);
exit;
}
$event = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if ($event['type'] === 'activation.code_received') {
$sms = $event['data']['activation']['sms'];
error_log('Code: '.$sms[array_key_last($sms)]['code']);
}
http_response_code(204);
Python
import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["SMSGRAB_WEBHOOK_SECRET"]
def verify(header: str, body: bytes, secret: str, tolerance: int = 300) -> bool:
parts = dict(part.strip().split("=", 1) for part in header.split(",") if "=" in part)
timestamp, signature = parts.get("t", ""), parts.get("v1", "")
if not timestamp.isdigit() or not signature:
return False
expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
return abs(time.time() - int(timestamp)) <= tolerance and hmac.compare_digest(expected, signature)
@app.post("/smsgrab/webhook")
def webhook():
if not verify(request.headers.get("SmsGrab-Signature", ""), request.get_data(), SECRET):
abort(400)
event = request.get_json()
if event["type"] == "activation.code_received":
print("Code:", event["data"]["activation"]["sms"][-1]["code"])
return "", 204
Node.js
import crypto from 'node:crypto';
import express from 'express';
const secret = process.env.SMSGRAB_WEBHOOK_SECRET;
function verify(header, rawBody, secret, tolerance = 300) {
const parts = {};
for (const part of header.split(',')) {
const index = part.indexOf('=');
if (index > 0) {
parts[part.slice(0, index).trim()] = part.slice(index + 1).trim();
}
}
if (!/^\d+$/.test(parts.t ?? '') || !parts.v1) {
return false;
}
const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.`).update(rawBody).digest();
const given = Buffer.from(parts.v1, 'hex');
return Math.abs(Date.now() / 1000 - Number(parts.t)) <= tolerance
&& given.length === expected.length
&& crypto.timingSafeEqual(expected, given);
}
const app = express();
app.post('/smsgrab/webhook', express.raw({ type: 'application/json' }), (request, response) => {
if (!verify(request.get('SmsGrab-Signature') ?? '', request.body, secret)) {
return response.sendStatus(400);
}
const event = JSON.parse(request.body.toString('utf8'));
if (event.type === 'activation.code_received') {
console.log('Code:', event.data.activation.sms.at(-1).code);
}
return response.sendStatus(204);
});
app.listen(3000);
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
type Event struct {
ID string `json:"id"`
Type string `json:"type"`
Data struct {
Activation struct {
ID string `json:"id"`
SMS []struct {
Code string `json:"code"`
} `json:"sms"`
} `json:"activation"`
} `json:"data"`
}
func verify(header string, body []byte, secret string) bool {
var timestamp, signature string
for _, part := range strings.Split(header, ",") {
name, value, found := strings.Cut(strings.TrimSpace(part), "=")
if !found {
continue
}
switch name {
case "t":
timestamp = value
case "v1":
signature = value
}
}
seconds, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil || signature == "" {
return false
}
if age := time.Now().Unix() - seconds; age > 300 || age < -300 {
return false
}
given, err := hex.DecodeString(signature)
if err != nil {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(timestamp + "."))
mac.Write(body)
return hmac.Equal(mac.Sum(nil), given)
}
func main() {
secret := os.Getenv("SMSGRAB_WEBHOOK_SECRET")
http.HandleFunc("POST /smsgrab/webhook", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil || !verify(r.Header.Get("SmsGrab-Signature"), body, secret) {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
var event Event
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
if sms := event.Data.Activation.SMS; event.Type == "activation.code_received" && len(sms) > 0 {
log.Println("Code:", sms[len(sms)-1].Code)
}
w.WriteHeader(http.StatusNoContent)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Перехід із SMS-Activate
SMS-Activate закрився в грудні 2025 року. Перенесіть свої інструменти на SmsGrab, змінивши базовий URL і ключ.
Its protocol lives on: SmsGrab speaks it, so bots, panels and libraries written for SMS-Activate keep working. The actions, answers and numeric ids stay the same; only the address, the key and the currency change.
- Create an SmsGrab account, verify your e-mail address and top up your balance.
- Create an API key with “Read and buy” access in the developer area. Add your server addresses to its allowlist and, if you like, a daily spend cap.
- Replace the SMS-Activate base URL with the SmsGrab one and the old
api_keywith yoursgk_key. That is the whole switch for most tools. - Re-check money settings: balances and prices are USD with two decimals, so set
maxPricein dollars.
- https://api.sms-activate.org/stubs/handler_api.php
+ https://smsgrab.com/api/stubs/handler_api.php
- api_key=YOUR_SMS_ACTIVATE_KEY
+ api_key=sgk_your_key
What stays the same
getNumber,getNumberV2,getStatus,getStatusV2,setStatuswith1,3,6and8,getBalance,getPrices,getCountries,getServicesList,getNumbersStatus,getActiveActivationsandgetTopCountriesByService.- Plain-text answers such as
ACCESS_NUMBER,STATUS_OKandNO_NUMBERS, with HTTP 200, and the same JSON shapes. - Numeric activation ids, the usual service codes (
wa,tg,goand more) and numeric country ids (0Russia,6Indonesia,187USA). GETor form-encodedPOST, withapi_keyin the query or the body.
What is different
- Money is USD:
getBalance,getPricesandmaxPriceuse dollars with two decimals. - Rentals, forwarding and voice activations are not available; unknown actions answer
BAD_ACTION, and extras such asoperatorare accepted and ignored. - Too many requests answer HTTP
429withTOO_MANY_REQUESTSandRetry-After. Default limits: 600 requests and 60 purchases per minute per key. - A cancel right after a purchase can answer
EARLY_CANCEL_DENIED; retry a little later. - Our catalogue ids and ISO country codes work as well, so services without a short code are reachable.
getServicesListtells you the code of every service.
Once switched, you can adopt the REST API one call at a time: it accepts the same numeric ids and adds signed webhooks, long polling and idempotent purchases. The full protocol reference is in the next section.
Сумісність із sms-activate
Інструменти для протоколу sms-activate працюють після заміни однієї адреси.
https://smsgrab.com/api/stubs/handler_api.php
GET or POST (form encoded) with api_key, action and the action's parameters. The key may also be sent as Authorization: Bearer. Every protocol answer, errors included, comes with HTTP 200 as plain text or JSON, exactly like the original protocol. Amounts are decimal USD with two decimals at your developer price; times are UTC, yyyy-MM-dd HH:mm:ss.
Any action can also answer: BAD_KEY (missing, wrong, revoked or expired key), NO_ACCESS (address outside the allowlist, missing purchase access, e-mail not verified, spend cap reached or the API switched off), BANNED:<time> (account or developer access suspended), BAD_ACTION (unknown action) and ERROR_SQL (an internal error, nothing charged). Rate limiting answers HTTP 429 with TOO_MANY_REQUESTS.
getBalance
Your balance in USD. getBalanceAndCashBack answers the same.
- Parameters
- –
- Success
ACCESS_BALANCE:12.34- Errors
BAD_KEYNO_ACCESSBANNED:2026-09-27 10:05:00
getNumber
Buys a number: the activation id, then the number without +. maxPrice is decimal USD; a higher price, or a value that is not a positive decimal, answers WRONG_MAX_PRICE: with the current price. CHANNELS_LIMIT means too many numbers are waiting at once. country=any buys in the cheapest country that has the service, the best stocked first at equal price. customer_ref tags the purchase for your statement, like in the REST API. Nothing is charged on any error.
- Parameters
service,country(default0, orany),maxPrice?,customer_ref?,operator? (ignored)- Success
ACCESS_NUMBER:100000123:6281234567890- Errors
BAD_SERVICEBAD_COUNTRYNO_NUMBERSNO_BALANCEWRONG_MAX_PRICE:0.17CHANNELS_LIMITNO_ACCESSBANNED:2026-09-27 10:05:00ERROR_SQL
getNumberV2
The same purchase with a JSON answer. currency is the ISO 4217 number of the price's currency, 840 for USD.
- Parameters
- as
getNumber - Success
{"activationId":"100000123","phoneNumber":"6281234567890", "activationCost":"0.17", "currency":840, "countryCode":"6", "canGetAnotherSms":true, "activationTime":"2026-09-27 10:05:00", "activationEndTime":"2026-09-27 10:25:00", "activationOperator":"any"} - Errors
- as
getNumber
- as
setStatus
1 number is ready (ACCESS_READY), 3 ask for another SMS (ACCESS_RETRY_GET), 6 finish (ACCESS_ACTIVATION), 8 cancel and refund (ACCESS_CANCEL). After a code, 3 asks the provider for one more SMS, like POST /activations/{id}/retry; BAD_STATUS means it cannot (provider refused, 10 requests used or less than 30 seconds left) and a second 3 within 20 seconds answers HTTP 429. EARLY_CANCEL_DENIED means it is too early to cancel; retry a little later. 3, 6 and 8 need a key with purchase access.
- Parameters
id,status(1,3,6or8)- Success
ACCESS_READY · ACCESS_RETRY_GET · ACCESS_ACTIVATION · ACCESS_CANCEL- Errors
NO_ACTIVATIONWRONG_ACTIVATION_IDBAD_STATUSEARLY_CANCEL_DENIEDNO_ACCESSERROR_SQL
getStatus
STATUS_WAIT_RETRY follows setStatus 3 until the next SMS. STATUS_CANCEL covers cancelled and expired numbers, both refunded.
- Parameters
id- Success
STATUS_WAIT_CODE · STATUS_WAIT_RETRY:482913 · STATUS_OK:482913 · STATUS_CANCEL- Errors
NO_ACTIVATIONWRONG_ACTIVATION_ID
getStatusV2
sms is null while waiting and holds the latest message after that.
- Parameters
id- Success
{"verificationType":0,"sms":{"dateTime":"2026-09-27 10:06:11", "code":"482913", "text":"Your WhatsApp code is 482-913"}, "call":null} - Errors
NO_ACTIVATIONWRONG_ACTIVATION_ID
getFullSms
The full text of the latest SMS. STATUS_WAIT_CODE while nothing has arrived, STATUS_CANCEL when the number ended without one.
- Parameters
id- Success
FULL_SMS:Your WhatsApp code is 482-913 · STATUS_WAIT_CODE · STATUS_CANCEL- Errors
NO_ACTIVATIONWRONG_ACTIVATION_ID
getActiveActivations
Up to 100 numbers bought through the API that are waiting (activationStatus 4) or hold a code (1).
- Parameters
- –
- Success
{"status":"success","activeActivations":[{"activationId":"100000123", "serviceCode":"wa", "phoneNumber":"6281234567890", "activationCost":"0.17", "activationStatus":"4", "smsCode":null, "smsText":null, "activationTime":"2026-09-27 10:05:00", "countryCode":"6"}]} - Errors
{"status":"error","error":"NO_ACTIVATIONS"}
getPrices
Your price in USD, your wholesale discount included, and the stock, by country and service. country=any or no country lists every country.
- Parameters
service?,country?- Success
{"6":{"wa":{"cost":0.17,"count":30412}}} - Errors
BAD_SERVICEBAD_COUNTRY
getPricesV2
The same list as a map from your price in USD (four decimals) to the stock at that price.
- Parameters
service?,country?- Success
{"6":{"wa":{"0.1700":30412}}}- Errors
BAD_SERVICEBAD_COUNTRY
getPricesV3
The same list with a provider breakdown. SmsGrab picks the route itself, so there is one entry with provider_id 1; providerIds and exceptProviderIds are accepted and ignored.
- Parameters
service?,country?- Success
{"6":{"wa":{"price":0.17,"count":30412, "providers":{"1":{"count":30412, "price":[0.17], "provider_id":1}}}}} - Errors
BAD_SERVICEBAD_COUNTRY
getOperators
Operators per country. The route is picked by SmsGrab, so every country lists any.
- Parameters
country?- Success
{"status":"success","countryOperators":{"6":["any"]}} - Errors
BAD_COUNTRY
getCountries
Every country in stock, keyed by its SMS-Activate id. A country SMS-Activate never listed has an id of its own (Singapore 10351, Malta 199).
- Parameters
- –
- Success
{"6":{"id":6,"rus":"Indonesia", "eng":"Indonesia", "chn":"Indonesia", "visible":1, "retry":1, "rent":0, "multiService":0}}
getServicesList
Every service in stock, or only those in one country, with the code to use in getNumber: the SMS-Activate code where one exists, otherwise our own code. A catalogue id that is also another service's protocol code gets the prefix sg_ (Amazon Web Services is sg_aws, because aws is 7-Eleven).
- Parameters
country?- Success
{"status":"success","services":[{"code":"wa", "name":"WhatsApp"}]} - Errors
BAD_COUNTRY
getNumbersStatus
Stock per service; without country the stock of every country is added up.
- Parameters
country?- Success
{"wa_0":"30412","tg_0":"1822"} - Errors
BAD_COUNTRY
getTopCountriesByService
Up to 100 countries for one service, cheapest first.
- Parameters
service- Success
{"0":{"country":6,"count":30412, "price":0.17, "retail_price":0.35}} - Errors
BAD_SERVICE
The activation id is the numeric compat_id, which the REST API accepts too. Services use the short codes below where one exists and our catalogue ids otherwise; countries use the protocol's numeric ids, and our country ids or ISO codes work as well. getServicesList and getCountries are the authoritative lists. Keys, scopes, allowlists, spend caps, limits, prices, refunds, webhooks and usage are shared with the REST API.
Service codes
waWhatsApptgTelegramviViberigInstagramfbFacebookgoGoogle, Gmail, YouTubetwX (Twitter)dsDiscordlfTikTokamAmazonmmMicrosoftmbYahoooiTinderubUbertsPayPalnfNetflixwbWeChatvkVKontakteokOdnoklassnikidheBaykaShopeefuSnapchatmtSteambwSignaldrOpenAImeLINEktKakaoTalktnLinkedInwxAppleqqTencent QQimimohbTwitchreCoinbaseyaYandexmaMail.ruavAvitootAny other
Popular country ids
0Russia6Indonesia4Philippines10Vietnam16United Kingdom22India36Canada43Germany73Brazil187USA62Türkiye54Mexico
All 206 country ids
0Russia RU1Ukraine UA2Kazakhstan KZ3China CN4Philippines PH5Myanmar MM6Indonesia ID7Malaysia MY8Kenya KE9Tanzania TZ10Vietnam VN11Kyrgyzstan KG13Israel IL14Hong Kong HK15Poland PL16United Kingdom GB17Madagascar MG18DR Congo CD19Nigeria NG20Macao MO21Egypt EG22India IN23Ireland IE24Cambodia KH25Laos LA26Haiti HT27Côte d’Ivoire CI28Gambia GM29Serbia RS30Yemen YE31South Africa ZA32Romania RO33Colombia CO34Estonia EE35Azerbaijan AZ36Canada CA37Morocco MA38Ghana GH39Argentina AR40Uzbekistan UZ41Cameroon CM42Chad TD43Germany DE44Lithuania LT45Croatia HR46Sweden SE47Iraq IQ48Netherlands NL49Latvia LV50Austria AT51Belarus BY52Thailand TH53Saudi Arabia SA54Mexico MX55Taiwan TW56Spain ES57Iran IR58Algeria DZ59Slovenia SI60Bangladesh BD61Senegal SN62Türkiye TR63Czechia CZ64Sri Lanka LK65Peru PE66Pakistan PK67New Zealand NZ68Guinea GN69Mali ML70Venezuela VE71Ethiopia ET72Mongolia MN73Brazil BR74Afghanistan AF75Uganda UG76Angola AO77Cyprus CY78France FR79Papua New Guinea PG80Mozambique MZ81Nepal NP82Belgium BE83Bulgaria BG84Hungary HU85Moldova MD86Italy IT87Paraguay PY88Honduras HN89Tunisia TN90Nicaragua NI91Timor-Leste TL92Bolivia BO93Costa Rica CR94Guatemala GT95United Arab Emirates AE96Zimbabwe ZW97Puerto Rico PR98Sudan SD99Togo TG100Kuwait KW101El Salvador SV102Libya LY103Jamaica JM104Trinidad and Tobago TT105Ecuador EC106Eswatini SZ107Oman OM108Bosnia and Herzegovina BA109Dominican Republic DO110Syria SY111Qatar QA112Panama PA113Cuba CU114Mauritania MR115Sierra Leone SL116Jordan JO117Portugal PT118Barbados BB119Burundi BI120Benin BJ121Brunei BN122Bahamas BS123Botswana BW124Belize BZ125Central African Republic CF126Dominica DM127Grenada GD128Georgia GE129Greece GR130Guinea-Bissau GW131Guyana GY132Iceland IS133Comoros KM134Saint Kitts and Nevis KN135Liberia LR136Lesotho LS137Malawi MW138Namibia NA139Niger NE140Rwanda RW141Slovakia SK142Suriname SR143Tajikistan TJ144Monaco MC145Bahrain BH146Réunion RE147Zambia ZM148Armenia AM149Somalia SO150Congo CG151Chile CL152Burkina Faso BF153Lebanon LB154Gabon GA155Albania AL156Uruguay UY157Mauritius MU158Bhutan BT159Maldives MV160Guadeloupe GP161Turkmenistan TM162French Guiana GF163Finland FI164Saint Lucia LC165Luxembourg LU166Saint Vincent and the Grenadines VC167Equatorial Guinea GQ168Djibouti DJ169Antigua and Barbuda AG170Cayman Islands KY171Montenegro ME172Denmark DK173Switzerland CH174Norway NO175Australia AU176Eritrea ER177South Sudan SS178São Tomé and Príncipe ST179Aruba AW180Montserrat MS181Anguilla AI182Japan JP183North Macedonia MK184Seychelles SC185New Caledonia NC186Cape Verde CV187USA US188Palestine PS189Fiji FJ190South Korea KR199Malta MT201Gibraltar GI203Kosovo XK204Niue NU1003Bermuda BM1007Vanuatu VU1008Greenland GL1011Martinique MQ1012French Polynesia PF1062Andorra AD10161American Samoa AS10227Tonga TO10231Samoa WS10348Liechtenstein LI10349Sint Maarten SX10351Singapore SG
curl
BASE="https://smsgrab.com/api/stubs/handler_api.php?api_key=$SMSGRAB_API_KEY"
curl -s -w '\n' "$BASE&action=getBalance"
curl -s -w '\n' "$BASE&action=getNumber&service=tg&country=6&maxPrice=0.30"
curl -s -w '\n' "$BASE&action=getStatus&id=100000123"
curl -s -w '\n' "$BASE&action=setStatus&id=100000123&status=6"
Python
import os
import time
import requests
BASE = "https://smsgrab.com/api/stubs/handler_api.php"
KEY = os.environ["SMSGRAB_API_KEY"]
def action(name: str, **params) -> str:
response = requests.get(BASE, params={"api_key": KEY, "action": name, **params}, timeout=30)
response.raise_for_status()
return response.text
print(action("getBalance"))
answer = action("getNumber", service="tg", country=6, maxPrice="0.30")
if not answer.startswith("ACCESS_NUMBER:"):
raise SystemExit(answer)
_, activation_id, number = answer.split(":")
print("Number:", number)
while True:
status = action("getStatus", id=activation_id)
if status.startswith("STATUS_OK:"):
print("Code:", status.split(":", 1)[1])
action("setStatus", id=activation_id, status=6)
break
if status == "STATUS_CANCEL":
print("Cancelled or expired, the charge was refunded")
break
time.sleep(5)
Node.js
const BASE = 'https://smsgrab.com/api/stubs/handler_api.php';
async function action(name, params = {}) {
const url = new URL(BASE);
url.search = new URLSearchParams({ api_key: process.env.SMSGRAB_API_KEY, action: name, ...params }).toString();
const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
return response.text();
}
console.log(await action('getBalance'));
const answer = await action('getNumber', { service: 'tg', country: '6', maxPrice: '0.30' });
if (!answer.startsWith('ACCESS_NUMBER:')) {
throw new Error(answer);
}
const [, id, number] = answer.split(':');
console.log('Number:', number);
for (;;) {
const status = await action('getStatus', { id });
if (status.startsWith('STATUS_OK:')) {
console.log('Code:', status.slice('STATUS_OK:'.length));
await action('setStatus', { id, status: '6' });
break;
}
if (status === 'STATUS_CANCEL') {
console.log('Cancelled or expired, the charge was refunded');
break;
}
await new Promise((resolve) => setTimeout(resolve, 5000));
}
PHP
<?php
function smsgrab(string $action, array $params = []): string
{
$query = http_build_query(['api_key' => getenv('SMSGRAB_API_KEY'), 'action' => $action] + $params);
$answer = file_get_contents('https://smsgrab.com/api/stubs/handler_api.php?'.$query, false, stream_context_create(['http' => ['timeout' => 30]]));
if ($answer === false) {
throw new RuntimeException('The request failed');
}
return $answer;
}
echo smsgrab('getBalance').PHP_EOL;
$answer = smsgrab('getNumber', ['service' => 'tg', 'country' => 6, 'maxPrice' => '0.30']);
if (! str_starts_with($answer, 'ACCESS_NUMBER:')) {
exit($answer.PHP_EOL);
}
[, $id, $number] = explode(':', $answer);
echo 'Number: '.$number.PHP_EOL;
while (true) {
$status = smsgrab('getStatus', ['id' => $id]);
if (str_starts_with($status, 'STATUS_OK:')) {
echo 'Code: '.substr($status, strlen('STATUS_OK:')).PHP_EOL;
smsgrab('setStatus', ['id' => $id, 'status' => 6]);
break;
}
if ($status === 'STATUS_CANCEL') {
echo 'Cancelled or expired, the charge was refunded'.PHP_EOL;
break;
}
sleep(5);
}
Go
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
const base = "https://smsgrab.com/api/stubs/handler_api.php"
var client = &http.Client{Timeout: 30 * time.Second}
func action(name string, params url.Values) (string, error) {
query := url.Values{"api_key": {os.Getenv("SMSGRAB_API_KEY")}, "action": {name}}
for key, values := range params {
query[key] = values
}
response, err := client.Get(base + "?" + query.Encode())
if err != nil {
return "", err
}
defer response.Body.Close()
body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if err != nil {
return "", err
}
if response.StatusCode != http.StatusOK {
return "", fmt.Errorf("http %d: %s", response.StatusCode, body)
}
return string(body), nil
}
func main() {
answer, err := action("getNumber", url.Values{"service": {"tg"}, "country": {"6"}, "maxPrice": {"0.30"}})
if err != nil {
panic(err)
}
if !strings.HasPrefix(answer, "ACCESS_NUMBER:") {
fmt.Println(answer)
return
}
parts := strings.Split(answer, ":")
id := parts[1]
fmt.Println("Number:", parts[2])
for {
status, err := action("getStatus", url.Values{"id": {id}})
if err != nil {
panic(err)
}
if code, ok := strings.CutPrefix(status, "STATUS_OK:"); ok {
fmt.Println("Code:", code)
if _, err := action("setStatus", url.Values{"id": {id}, "status": {"6"}}); err != nil {
panic(err)
}
return
}
if status == "STATUS_CANCEL" {
fmt.Println("Cancelled or expired, the charge was refunded")
return
}
time.Sleep(5 * time.Second)
}
}
Повні приклади
Купити номер, дочекатися коду й завершити активацію — п’ятьма мовами.
curl
set -euo pipefail
API="https://smsgrab.com/api/dev/v1"
call() {
local response
response=$(curl -sS -w '\n%{http_code}' -H "Authorization: Bearer $SMSGRAB_API_KEY" "$@") || return 1
if [ "${response##*$'\n'}" -ge 400 ]; then
echo "${response%$'\n'*}" >&2
return 1
fi
echo "${response%$'\n'*}"
}
call "$API/balance"
activation=$(call -X POST "$API/activations" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{"service":"telegram","country":"indonesia","max_price_minor":30}')
id=$(jq -r .id <<<"$activation")
echo "Number: $(jq -r .phone_number <<<"$activation")"
status=WAITING_SMS
while [ "$status" = WAITING_SMS ]; do
activation=$(call "$API/activations/$id?wait=25")
status=$(jq -r .status <<<"$activation")
done
if [ "$(jq '.sms | length' <<<"$activation")" -gt 0 ]; then
echo "Code: $(jq -r '.sms[-1].code' <<<"$activation")"
if [ "$status" = CODE_RECEIVED ]; then
call -X POST "$API/activations/$id/finish" > /dev/null
fi
else
echo "No code arrived ($status), the charge was refunded"
fi
Python
import os
import uuid
import requests
API = "https://smsgrab.com/api/dev/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['SMSGRAB_API_KEY']}"
class SmsGrabError(Exception):
pass
def call(method: str, path: str, **kwargs) -> dict:
response = session.request(method, f"{API}{path}", timeout=40, **kwargs)
if response.status_code >= 400:
try:
error = response.json()
except ValueError:
error = {"code": str(response.status_code), "message": response.text[:200]}
raise SmsGrabError(f"{error.get('code')}: {error.get('message')}")
return response.json()
activation = call(
"POST",
"/activations",
json={"service": "telegram", "country": "indonesia", "max_price_minor": 30},
headers={"Idempotency-Key": str(uuid.uuid4())},
)
print("Number:", activation["phone_number"])
while activation["status"] == "WAITING_SMS":
activation = call("GET", f"/activations/{activation['id']}", params={"wait": 25})
if activation["sms"]:
print("Code:", activation["sms"][-1]["code"])
if activation["status"] == "CODE_RECEIVED":
call("POST", f"/activations/{activation['id']}/finish")
else:
print("No code arrived, the charge was refunded")
Node.js
import { randomUUID } from 'node:crypto';
const API = 'https://smsgrab.com/api/dev/v1';
async function call(method, path, { body, idempotencyKey } = {}) {
const response = await fetch(`${API}${path}`, {
method,
headers: {
Authorization: `Bearer ${process.env.SMSGRAB_API_KEY}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(40_000),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(`${data.code ?? response.status}: ${data.message ?? response.statusText}`);
}
return data;
}
let activation = await call('POST', '/activations', {
body: { service: 'telegram', country: 'indonesia', max_price_minor: 30 },
idempotencyKey: randomUUID(),
});
console.log('Number:', activation.phone_number);
while (activation.status === 'WAITING_SMS') {
activation = await call('GET', `/activations/${activation.id}?wait=25`);
}
if (activation.sms.length > 0) {
console.log('Code:', activation.sms.at(-1).code);
if (activation.status === 'CODE_RECEIVED') {
await call('POST', `/activations/${activation.id}/finish`);
}
} else {
console.log('No code arrived, the charge was refunded');
}
PHP
<?php
require __DIR__.'/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://smsgrab.com/api/dev/v1/',
'headers' => ['Authorization' => 'Bearer '.getenv('SMSGRAB_API_KEY'), 'Accept' => 'application/json'],
'timeout' => 40,
]);
function call(Client $client, string $method, string $path, array $options = []): array
{
try {
$response = $client->request($method, $path, $options);
} catch (RequestException $failure) {
$error = json_decode((string) $failure->getResponse()?->getBody(), true) ?? [];
throw new RuntimeException(($error['code'] ?? 'HTTP').': '.($error['message'] ?? $failure->getMessage()), 0, $failure);
}
return json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
}
$activation = call($client, 'POST', 'activations', [
'json' => ['service' => 'telegram', 'country' => 'indonesia', 'max_price_minor' => 30],
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
]);
echo 'Number: '.$activation['phone_number'].PHP_EOL;
while ($activation['status'] === 'WAITING_SMS') {
$activation = call($client, 'GET', 'activations/'.$activation['id'], ['query' => ['wait' => 25]]);
}
if ($activation['sms'] !== []) {
echo 'Code: '.$activation['sms'][array_key_last($activation['sms'])]['code'].PHP_EOL;
if ($activation['status'] === 'CODE_RECEIVED') {
call($client, 'POST', 'activations/'.$activation['id'].'/finish');
}
} else {
echo 'No code arrived, the charge was refunded'.PHP_EOL;
}
Go
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
const api = "https://smsgrab.com/api/dev/v1"
type Activation struct {
ID string `json:"id"`
Status string `json:"status"`
PhoneNumber string `json:"phone_number"`
PriceMinor int64 `json:"price_minor"`
SMS []struct {
Code string `json:"code"`
Text string `json:"text"`
} `json:"sms"`
}
var client = &http.Client{Timeout: 40 * time.Second}
func call(method, path string, body any, idempotencyKey string, out any) error {
var payload bytes.Buffer
if body != nil {
if err := json.NewEncoder(&payload).Encode(body); err != nil {
return err
}
}
request, err := http.NewRequest(method, api+path, &payload)
if err != nil {
return err
}
request.Header.Set("Authorization", "Bearer "+os.Getenv("SMSGRAB_API_KEY"))
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if idempotencyKey != "" {
request.Header.Set("Idempotency-Key", idempotencyKey)
}
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 300 {
var failure struct {
Code string `json:"code"`
Message string `json:"message"`
}
_ = json.NewDecoder(response.Body).Decode(&failure)
return fmt.Errorf("%d %s: %s", response.StatusCode, failure.Code, failure.Message)
}
if out == nil {
return nil
}
return json.NewDecoder(response.Body).Decode(out)
}
func idempotencyKey() string {
buffer := make([]byte, 16)
_, _ = rand.Read(buffer)
return hex.EncodeToString(buffer)
}
func main() {
var activation Activation
order := map[string]any{"service": "telegram", "country": "indonesia", "max_price_minor": 30}
if err := call("POST", "/activations", order, idempotencyKey(), &activation); err != nil {
panic(err)
}
fmt.Println("Number:", activation.PhoneNumber)
for activation.Status == "WAITING_SMS" {
if err := call("GET", "/activations/"+activation.ID+"?wait=25", nil, "", &activation); err != nil {
panic(err)
}
}
if len(activation.SMS) == 0 {
fmt.Println("No code arrived, the charge was refunded")
return
}
fmt.Println("Code:", activation.SMS[len(activation.SMS)-1].Code)
if activation.Status == "CODE_RECEIVED" {
if err := call("POST", "/activations/"+activation.ID+"/finish", nil, "", nil); err != nil {
panic(err)
}
}
}
Версії та зміни
Ми зберігаємо стабільність API і розповідаємо про зміни.
- The current version is
2026-09-27; webhook payloads carry it inapi_version. - We add fields, events, error reasons, countries and services without notice. Ignore what you do not know.
- Breaking changes get a new path (
/dev/v2) and a long overlap, announced by e-mail to every key owner. - The machine-readable description is part of the OpenAPI document at
https://smsgrab.com/api/v1/openapi.json.
Історія змін
Що змінилося в API, спочатку нове.
-
- Top-ups: keys with the new
topupscope create crypto top-up invoices withPOST /topupsand follow them withGET /topups,GET /topups/{id}(with long polling) andPOST /topups/{id}/cancel;GET /topups/optionslists the networks and coins. Every top-up carries your ownreference. - Webhooks: new events
topup.created,topup.confirming,topup.credited,topup.expiredandtopup.reviewwith the top-up indata.topup.
- Top-ups: keys with the new
-
- Prices: the API now sells at the same prices as the app, minus your wholesale discount. Volume tiers count your 30-day spend on every channel, and approved resellers get a fixed discount; you always get the larger one. The developer markup tiers are retired.
/pricesreportsdiscount_percentinstead ofmarkup_percent, andpricinginGET /medescribes your discount and tier. - Resellers:
customer_refonPOST /activationsand the compatiblegetNumberandgetNumberV2tags a purchase with your end customer, activations carry it,GET /activationsfilters by it, and the newGET /statementsums charges, refunds and savings per day, customer and service.
- Prices: the API now sells at the same prices as the app, minus your wholesale discount. Volume tiers count your 30-day spend on every channel, and approved resellers get a fixed discount; you always get the larger one. The developer markup tiers are retired.
-
- New
POST /activations/{id}/retryasks the provider for another SMS on a number that already showed a code; activations carrycan_request_smsandawaiting_next_sms. The compatiblesetStatus3now really asks the provider for the next SMS, andcanGetAnotherSmsingetNumberV2tells whether the number can.
- New
-
- More countries and services: numbers now come from more than one wholesale provider.
/countries,/services,/pricesand the compatiblegetCountries,getServicesListandgetPricesfollow the bigger live catalogue. - Compatible endpoint: every country and service has a protocol id. Countries keep their SMS-Activate id and otherwise have an id of their own; services use the SMS-Activate code and otherwise our own code, with
sg_in front of a catalogue id that collides with a protocol code. Old ids, catalogue ids and ISO codes still work. - Compatible endpoint: new actions
getPricesV2,getPricesV3,getFullSmsandgetOperators,country=anyingetNumberand the price actions, andgetNumberV2reports the ISO number of the price's currency. - Developer prices are computed from the exact wholesale cost, to a millionth of a dollar, and are never at or below cost.
- A purchase may try more than one route for the same offer. It never charges more than the quoted price and refunds exactly once when no number can be delivered.
- The lifetime of a number follows its provider: read
expires_atinstead of assuming 20 minutes. - A cancel right after a purchase can be refused for a short time with
422 ACTIVATION_CANCEL_NOT_YET(EARLY_CANCEL_DENIEDin the compatible endpoint); the message says when to retry. icon_urlof every service points to an icon served by SmsGrab.
- More countries and services: numbers now come from more than one wholesale provider.
-
/countries,/servicesand/pricesare served from a cache refreshed in the background and answer304 Not Modifiedto a matchingIf-None-Match.- During a deploy a purchase that cannot start answers
503 PROVIDER_UNAVAILABLEwith reasonSERVER_DRAININGand charges nothing; held long-poll requests answer early.
-
- First release: the REST API under
/dev/v1, keys with scopes, IP allowlists, spend caps and rotation, signed webhooks, usage reports and the sms-activate compatible endpoint. maxPriceofgetNumbermust be a positive decimal, anything else answersWRONG_MAX_PRICE.setStatus3needs a key with purchase access. Webhook deliveries have a hard 10-second deadline.
- First release: the REST API under