createOrder(['service_id' => 1001, 'link' => 'https://instagram.com/x', 'quantity' => 1000]); declare(strict_types=1); namespace Smm; /** The standard error object, thrown for every non-2xx response. */ final class SmmException extends \RuntimeException { public function __construct( public readonly int $status, public readonly string $type, public readonly string $errorCode, string $message, public readonly string $messageFa, public readonly ?string $param, public readonly string $requestId, ) { parent::__construct($message, $status); } } final class SmmClient { private string $baseUrl; /** @var array{limit:int,remaining:int,reset:int}|null */ public ?array $rateLimit = null; public function __construct( private string $apiKey, string $baseUrl, private int $maxRetries = 2, private int $timeout = 30, ) { if ($apiKey === '') { throw new \InvalidArgumentException('apiKey is required'); } $this->baseUrl = rtrim($baseUrl, '/') . '/api/v3'; } /** Sends a request; most code calls the typed methods below instead. */ public function request(string $method, string $path, ?array $body = null, array $query = [], ?string $idempotencyKey = null): ?array { $url = $this->baseUrl . $path; $query = array_filter($query, static fn ($v) => $v !== null); if ($query) { $url .= '?' . http_build_query($query); } $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: smm-sdk-php/3']; $payload = null; if ($body !== null) { $payload = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); $headers[] = 'Content-Type: application/json'; } if ($method === 'POST') { $headers[] = 'Idempotency-Key: ' . ($idempotencyKey ?? self::uuid()); } for ($attempt = 0; ; $attempt++) { $respHeaders = []; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_HEADERFUNCTION => static function ($ch, string $line) use (&$respHeaders): int { $p = strpos($line, ':'); if ($p !== false) { $respHeaders[strtolower(trim(substr($line, 0, $p)))] = trim(substr($line, $p + 1)); } return strlen($line); }, ]); if ($payload !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } $raw = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $err = curl_error($ch); curl_close($ch); if ($raw === false) { if ($attempt < $this->maxRetries) { usleep((int) (500000 * 2 ** $attempt)); continue; } throw new \RuntimeException('network error: ' . $err); } if (isset($respHeaders['ratelimit-limit'])) { $this->rateLimit = [ 'limit' => (int) $respHeaders['ratelimit-limit'], 'remaining' => (int) ($respHeaders['ratelimit-remaining'] ?? 0), 'reset' => (int) ($respHeaders['ratelimit-reset'] ?? 1), ]; } if (($status === 429 || $status >= 500) && $attempt < $this->maxRetries) { $after = (int) ($respHeaders['retry-after'] ?? 0); usleep($after > 0 ? $after * 1000000 : (int) (500000 * 2 ** $attempt)); continue; } if ($status === 204 || $raw === '') { return null; } $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); if ($status >= 400) { $e = $data['error'] ?? []; throw new SmmException($status, $e['type'] ?? 'api_error', $e['code'] ?? 'unknown', $e['message'] ?? 'request failed', $e['message_fa'] ?? '', $e['param'] ?? null, $e['request_id'] ?? ''); } return $data; } } /** Iterates every item of a list method, following next_cursor. */ public function paginate(callable $list, array $params = []): \Generator { $cursor = null; do { $page = $list(array_merge($params, ['cursor' => $cursor])); foreach ($page['data'] as $item) { yield $item; } $cursor = $page['next_cursor']; } while ($cursor); } /** * Verifies the Smm-Signature header: t=,v1=. * Pass the raw request body (file_get_contents('php://input')). Several v1= values may be present. */ public static function verifyWebhook(string $secret, string $header, string $rawBody, int $tolerance = 300, ?int $now = null): bool { $t = 0; $sigs = []; foreach (explode(',', $header) as $part) { [$k, $v] = array_pad(explode('=', trim($part), 2), 2, ''); if ($k === 't' && ctype_digit($v)) { $t = (int) $v; } elseif ($k === 'v1') { $sigs[] = $v; } } if ($t === 0 || !$sigs || abs(($now ?? time()) - $t) > $tolerance) { return false; } $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret); foreach ($sigs as $s) { if (hash_equals($expected, $s)) { return true; } } return false; } private static function uuid(): string { $b = random_bytes(16); $b[6] = chr((ord($b[6]) & 0x0f) | 0x40); $b[8] = chr((ord($b[8]) & 0x3f) | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4)); } // ---- operations --------------------------------------------------------- /** Sign the app out (revokes the current app session) */ public function logout(?string $idempotencyKey = null): ?array { return $this->request('POST', '/auth/logout', null, [], $idempotencyKey); } /** Send a login code to a phone number */ public function requestOtp(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/auth/otp', $body, [], $idempotencyKey); } /** Verify the code and receive app tokens */ public function verifyOtp(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/auth/otp/verify', $body, [], $idempotencyKey); } /** Rotate the refresh token and get a new access token */ public function refreshToken(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/auth/refresh', $body, [], $idempotencyKey); } /** Wallet balance (the test wallet for test keys) (scope: read) */ public function getBalance(): ?array { return $this->request('GET', '/balance', null, [], null); } /** A batch and its orders (scope: read) */ public function getBatch(int $id): ?array { return $this->request('GET', '/batches/' . $id, null, [], null); } /** Categories (scope: read) Params: platform. */ public function listCategories(array $params = []): ?array { return $this->request('GET', '/categories', null, $params, null); } /** Redeem a voucher (credited now) or a deposit coupon (applied to the next deposit) (scope: payments) */ public function redeemCoupon(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/coupons/redeem', $body, [], $idempotencyKey); } /** Your events from the last 30 days, newest first (scope: read) Params: type, created_after, limit, cursor. */ public function listEvents(array $params = []): ?array { return $this->request('GET', '/events', null, $params, null); } /** An event (scope: read) */ public function getEvent(int $id): ?array { return $this->request('GET', '/events/' . $id, null, [], null); } /** Favorite services (scope: read) */ public function listFavorites(): ?array { return $this->request('GET', '/favorites', null, [], null); } /** Add a favorite service (scope: orders) */ public function addFavorite(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/favorites', $body, [], $idempotencyKey); } /** Remove a favorite (the id is the service id) (scope: orders) */ public function deleteFavorite(int $id): ?array { return $this->request('DELETE', '/favorites/' . $id, null, [], null); } /** Detect the platform and target of a link, and the services that accept it (scope: read) */ public function resolveLink(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/links/resolve', $body, [], $idempotencyKey); } /** The signed-in user and the current credential (scope: read) */ public function getMe(): ?array { return $this->request('GET', '/me', null, [], null); } /** API metadata and server time */ public function getMeta(): ?array { return $this->request('GET', '/meta', null, [], null); } /** In-app notifications, newest first (scope: read) Params: limit, cursor. */ public function listNotifications(array $params = []): ?array { return $this->request('GET', '/notifications', null, $params, null); } /** Mark one notification (id) or all of them read (scope: read) */ public function markNotificationsRead(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/notifications/read', $body, [], $idempotencyKey); } /** Your orders, newest first (scope: read) Params: status, service_id, client_label, link, batch_id, created_after, created_before, limit, cursor. */ public function listOrders(array $params = []): ?array { return $this->request('GET', '/orders', null, $params, null); } /** Place an order (always send an Idempotency-Key) (scope: orders) */ public function createOrder(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/orders', $body, [], $idempotencyKey); } /** Place up to 100 orders in one charge (scope: orders) */ public function createOrderBatch(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/orders/batch', $body, [], $idempotencyKey); } /** Price an order without placing it (scope: read) */ public function quoteOrder(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/orders/quote', $body, [], $idempotencyKey); } /** An order (scope: read) */ public function getOrder(int $id): ?array { return $this->request('GET', '/orders/' . $id, null, [], null); } /** Ask to cancel an order (the refund follows when it is canceled) (scope: orders) */ public function cancelOrder(int $id, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/orders/' . $id . '/cancel', null, [], $idempotencyKey); } /** Request a refill within the service's refill window (scope: orders) */ public function refillOrder(int $id, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/orders/' . $id . '/refill', null, [], $idempotencyKey); } /** Start a wallet top-up through the gateway (scope: payments) */ public function createPayment(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/payments', $body, [], $idempotencyKey); } /** A payment (scope: read) */ public function getPayment(int $id): ?array { return $this->request('GET', '/payments/' . $id, null, [], null); } /** Platforms (scope: read) */ public function listPlatforms(): ?array { return $this->request('GET', '/platforms', null, [], null); } /** Your referral link, totals and recent commissions (scope: read) */ public function getReferrals(): ?array { return $this->request('GET', '/referrals', null, [], null); } /** Your refills, newest first (scope: read) Params: order_id, limit. */ public function listRefills(array $params = []): ?array { return $this->request('GET', '/refills', null, $params, null); } /** A refill (scope: read) */ public function getRefill(int $id): ?array { return $this->request('GET', '/refills/' . $id, null, [], null); } /** Your API request log (writes and errors, 14 days) (scope: read) Params: limit, cursor. */ public function listRequestLogs(array $params = []): ?array { return $this->request('GET', '/request-logs', null, $params, null); } /** Active services with your prices (scope: read) Params: platform, category, target_kind, q. */ public function listServices(array $params = []): ?array { return $this->request('GET', '/services', null, $params, null); } /** A service (scope: read) */ public function getService(int $id): ?array { return $this->request('GET', '/services/' . $id, null, [], null); } /** Saved targets (links and usernames) (scope: read) Params: tag. */ public function listTargets(array $params = []): ?array { return $this->request('GET', '/targets', null, $params, null); } /** Save a target (scope: orders) */ public function createTarget(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/targets', $body, [], $idempotencyKey); } /** Delete a saved target (scope: orders) */ public function deleteTarget(int $id): ?array { return $this->request('DELETE', '/targets/' . $id, null, [], null); } /** Order templates (bulk lines) (scope: read) */ public function listTemplates(): ?array { return $this->request('GET', '/templates', null, [], null); } /** Save a template (same name replaces it) (scope: orders) */ public function createTemplate(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/templates', $body, [], $idempotencyKey); } /** Delete a template (scope: orders) */ public function deleteTemplate(int $id): ?array { return $this->request('DELETE', '/templates/' . $id, null, [], null); } /** Add funds to the test wallet (test keys only) (scope: read) Test mode only. */ public function testTopUp(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/test/balance', $body, [], $idempotencyKey); } /** Your support tickets, latest activity first (scope: support) Params: limit, cursor. */ public function listTickets(array $params = []): ?array { return $this->request('GET', '/tickets', null, $params, null); } /** Open a ticket (scope: support) */ public function createTicket(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/tickets', $body, [], $idempotencyKey); } /** A ticket with its messages (scope: support) */ public function getTicket(int $id): ?array { return $this->request('GET', '/tickets/' . $id, null, [], null); } /** Reply to a ticket (reopens it) (scope: support) */ public function replyTicket(int $id, array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/tickets/' . $id . '/messages', $body, [], $idempotencyKey); } /** A public tracking link for an order (no login needed to open it) (scope: read) */ public function createTrackingLink(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/tracking-links', $body, [], $idempotencyKey); } /** Wallet ledger lines, newest first (scope: read) Params: kind, created_after, created_before, limit, cursor. */ public function listTransactions(array $params = []): ?array { return $this->request('GET', '/transactions', null, $params, null); } /** Send a delivery again (scope: webhooks) */ public function redeliverWebhook(int $id, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/webhook-deliveries/' . $id . '/redeliver', null, [], $idempotencyKey); } /** Your webhook endpoints (for this mode) (scope: webhooks) */ public function listWebhookEndpoints(): ?array { return $this->request('GET', '/webhook-endpoints', null, [], null); } /** Create an endpoint; the signing secret is shown once (scope: webhooks) */ public function createWebhookEndpoint(array $body, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/webhook-endpoints', $body, [], $idempotencyKey); } /** An endpoint (scope: webhooks) */ public function getWebhookEndpoint(int $id): ?array { return $this->request('GET', '/webhook-endpoints/' . $id, null, [], null); } /** Change the URL, the events or turn it on or off (scope: webhooks) */ public function updateWebhookEndpoint(int $id, array $body): ?array { return $this->request('PATCH', '/webhook-endpoints/' . $id, $body, [], null); } /** Delete an endpoint (scope: webhooks) */ public function deleteWebhookEndpoint(int $id): ?array { return $this->request('DELETE', '/webhook-endpoints/' . $id, null, [], null); } /** The endpoint's delivery log (scope: webhooks) Params: limit, cursor. */ public function listWebhookDeliveries(int $id, array $params = []): ?array { return $this->request('GET', '/webhook-endpoints/' . $id . '/deliveries', null, $params, null); } /** Send a test event to the endpoint (scope: webhooks) */ public function testWebhookEndpoint(int $id, ?string $idempotencyKey = null): ?array { return $this->request('POST', '/webhook-endpoints/' . $id . '/test', null, [], $idempotencyKey); } }