|null, raw: string} */ function sendpier_get(string $path): array { $key = getenv('SENDPIER_API_KEY'); $domain = getenv('SENDPIER_DOMAIN'); if ($key === false || $key === '' || $domain === false || $domain === '') { fwrite(STDERR, "set SENDPIER_API_KEY and SENDPIER_DOMAIN first\n"); exit(78); } $handle = curl_init(API_BASE.$path); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_TIMEOUT, 30); curl_setopt($handle, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer '.$key, 'X-Domain-Name: '.$domain, 'Accept: application/json', ]); $raw = curl_exec($handle); if ($raw === false) { $error = curl_error($handle); curl_close($handle); fwrite(STDERR, "connection failed: {$error}\n"); exit(1); } $status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE); curl_close($handle); $decoded = json_decode((string) $raw, true); return [ 'status' => $status, 'body' => is_array($decoded) ? $decoded : null, 'raw' => (string) $raw, ]; } $argument = $argv[1] ?? '5'; if (str_starts_with($argument, 'msg_')) { // An identifier: ask for exactly that message. The path segment is an // identifier we handed out ourselves, so urlencode is belt and braces. $response = sendpier_get('/v1/messages/'.rawurlencode($argument)); } else { // A number: the list endpoint. limit is clamped to 1..20 and defaults to 5. $response = sendpier_get('/v1/messages?limit='.max(1, min(20, (int) $argument))); } echo $response['raw'], "\n"; if ($response['status'] !== 200) { // 404 message_not_found also covers "this identifier belongs to another // domain" -- a key only ever sees its own. fwrite(STDERR, "request failed with HTTP {$response['status']}\n"); exit(1); } // The single lookup answers one message object, the list answers a "messages" // array. Wrapping the first in an array lets one loop print both. $messages = $response['body']['messages'] ?? [$response['body']]; foreach ($messages as $message) { if (! is_array($message)) { continue; } fwrite(STDERR, sprintf( "%s %-28s %s\n", $message['status'] ?? '?', // The single lookup names the recipient "to", the list "to_email". $message['to'] ?? $message['to_email'] ?? '?', $message['subject'] ?? '' )); }