status = $status; $this->apiCode = $apiCode; $this->details = $details; $this->requestId = $requestId; } } class MikroPanel { /** Refused before anything was done, so the same request may simply be sent again. */ private const WAIT_AND_RETRY = ['rate_limited', 'too_many_concurrent_writes', 'server_busy', 'router_busy', 'request_in_progress', 'database_unavailable']; private $key; private $base; private $attempts; public function __construct(string $key, string $base = 'https://api.mikropanel.ir/v1', int $attempts = 5) { $this->key = $key; $this->base = rtrim($base, '/'); $this->attempts = $attempts; } /** One API call. Retries only when that cannot do anything twice. Returns an array, or the raw body. */ public function call(string $method, string $path, ?array $body = null, array $query = [], ?string $idempotencyKey = null, bool $raw = false) { $url = $this->base . $path . ($query ? '?' . http_build_query($query) : ''); $headers = ['Authorization: Bearer ' . $this->key, 'Accept: application/json']; if ($body !== null) { $headers[] = 'Content-Type: application/json'; } if ($idempotencyKey !== null) { $headers[] = 'Idempotency-Key: ' . $idempotencyKey; } $repeatable = $method === 'GET' || $idempotencyKey !== null; for ($attempt = 1; ; $attempt++) { $retryAfter = 0; $curl = curl_init($url); curl_setopt_array($curl, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 15, CURLOPT_TIMEOUT => 130, CURLOPT_HEADERFUNCTION => function ($handle, string $line) use (&$retryAfter) { if (stripos($line, 'Retry-After:') === 0) { $retryAfter = (int) trim(substr($line, 12)); } return strlen($line); }, ]); if ($body !== null) { curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode((object) $body)); } $content = curl_exec($curl); $status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE); $problem = curl_error($curl); curl_close($curl); if ($content === false) { if (!$repeatable || $attempt >= $this->attempts) { // A change without a key: look at the resource before trying again. throw new MikroPanelError(0, 'no_answer', $problem); } sleep(2 * $attempt); continue; } if ($status >= 200 && $status < 300) { return $raw ? $content : json_decode($content, true); } $error = json_decode($content, true)['error'] ?? ['code' => 'bad_answer', 'message' => substr($content, 0, 200)]; if (in_array($error['code'], self::WAIT_AND_RETRY, true) && $attempt < $this->attempts) { sleep(min(60, $retryAfter ?: 2 * $attempt)); continue; } throw new MikroPanelError($status, $error['code'], $error['message'] ?? '', (array) ($error['details'] ?? []), $error['request_id'] ?? ''); } } public function me(): array { return $this->call('GET', '/me'); } public function balance(): array { return $this->call('GET', '/me/balance'); } public function routers(): array { return $this->call('GET', '/routers')['data']; } public function plans(): array { return $this->call('GET', '/plans')['data']; } public function peer(int $id): array { return $this->call('GET', "/peers/$id")['peer']; } public function config(int $id): string { return $this->call('GET', "/peers/$id/config")['config']; } public function qrPng(int $id): string { return $this->call('GET', "/peers/$id/qr", null, [], null, true); } /** Every matching peer, page by page. */ public function peers(array $filters = []): Generator { do { $page = $this->call('GET', '/peers', null, $filters); foreach ($page['data'] as $peer) { yield $peer; } $filters['cursor'] = $page['next_cursor'] ?? null; } while ($filters['cursor']); } /** $fields: router_id, plan_id, or traffic_bytes and days; protocols => ['wireguard', 'l2tp']. */ public function createPeer(string $orderId, string $name, array $fields): array { return $this->call('POST', '/peers', ['name' => $name, 'external_ref' => $orderId] + $fields, [], "order-$orderId-create"); } public function renewPeer(int $id, string $orderId, array $fields): array { return $this->call('POST', "/peers/$id/renew", $fields, [], "order-$orderId-renew"); } public function suspend(int $id): array { return $this->call('POST', "/peers/$id/suspend"); } public function unsuspend(int $id): array { return $this->call('POST', "/peers/$id/unsuspend"); } public function deletePeer(int $id): array { return $this->call('DELETE', "/peers/$id"); } } if (PHP_SAPI === 'cli' && realpath($argv[0]) === __FILE__) { $key = getenv('MP_KEY'); if (!$key) { fwrite(STDERR, "set MP_KEY (and optionally MP_BASE)\n"); exit(1); } $api = new MikroPanel($key, getenv('MP_BASE') ?: 'https://api.mikropanel.ir/v1'); echo 'signed in; tier: ', $api->me()['limits']['tier'], "\n"; foreach ($api->routers() as $router) { echo "router {$router['id']} {$router['name']}\n"; } if (($argv[1] ?? '') === 'demo') { $order = (string) time(); $made = $api->createPeer($order, "demo$order", ['router_id' => (int) getenv('MP_ROUTER'), 'traffic_bytes' => GB, 'days' => 1]); $id = $made['peer']['id']; echo "created $id, config bytes ", strlen($api->config($id)), "\n"; $api->renewPeer($id, "$order-2", ['traffic_bytes' => 2 * GB, 'days' => 2]); $api->suspend($id); $api->unsuspend($id); echo 'deleted, returned bytes ', $api->deletePeer($id)['refunded_bytes'], "\n"; } }