query( "SELECT setting_value FROM `system` WHERE setting_name = 'clickatell_api_key'" )->fetch(); $api_key = $row['setting_value'] ?? ''; if ($api_key === '') { json_out(['error' => 'API key not configured', 'balance' => null]); } $ch = curl_init('https://platform.clickatell.com/public-client/balance'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_HTTPHEADER => [ 'Authorization: ' . $api_key, 'Accept: application/json', 'Content-Type: application/json', ], ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $err = curl_error($ch); curl_close($ch); if ($err !== '') { json_out(['error' => 'Request failed: ' . $err, 'balance' => null]); } $data = json_decode($body ?: '', true); if ($status !== 200 || $data === null) { json_out(['error' => 'Unexpected response (HTTP ' . $status . ')', 'balance' => null, 'raw' => $body]); } $credit = null; $currency = $data['currency'] ?? null; if (isset($data['balance']) && is_numeric($data['balance'])) { // Flat format: {"balance": 89.99, "currency": "GBP"} $credit = $data['balance']; } elseif (isset($data['balance']) && is_array($data['balance']) && isset($data['balance'][0]['credit'])) { // Array format: {"balance": [{"credit": "99.50", ...}]} $credit = $data['balance'][0]['credit']; $currency = $currency ?? ($data['balance'][0]['currency'] ?? null); } elseif (isset($data['credit'])) { $credit = $data['credit']; } elseif (isset($data['data']['credit'])) { $credit = $data['data']['credit']; } json_out(['balance' => $credit, 'currency' => $currency]);