|null $body * @return array{status: int, body: array|null, raw: string} */ function sendpier_request(string $method, string $path, ?array $body = null): 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); } $headers = [ 'Authorization: Bearer '.$key, // Required on every request. The key belongs to one domain and this // header has to name that same domain, or the answer is 403. 'X-Domain-Name: '.$domain, 'Accept: application/json', ]; $handle = curl_init(API_BASE.$path); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($handle, CURLOPT_TIMEOUT, 30); if ($body !== null) { $headers[] = 'Content-Type: application/json'; curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)); } curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); $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, ]; } $recipient = $argv[1] ?? ''; $from = getenv('SENDPIER_FROM'); if ($recipient === '' || $from === false || $from === '') { fwrite(STDERR, "usage: SENDPIER_FROM=noreply@example.com php send-message.php \n"); exit(64); } $response = sendpier_request('POST', '/v1/messages', [ 'from' => ['email' => $from, 'name' => 'Example'], // Ten recipients fit in one request, but prefer one: then you know the // status per email and one bad address cannot take the rest down with it. 'to' => [['email' => $recipient]], 'subject' => 'Hello from the Send API', 'text' => 'This message was sent from PHP.', 'html' => '

This message was sent from PHP.

', ]); echo $response['raw'], "\n"; if ($response['status'] !== 202) { // Log the status code *and* the body: the body carries the error code that // says what to change. Retry 429 and 503 with a growing wait; a 422 will // come back in exactly the same way. fwrite(STDERR, "request failed with HTTP {$response['status']}\n"); exit(1); } foreach ($response['body']['data'] ?? [] as $message) { // Store this identifier next to your own record: it is what you look the // message up with, and what a webhook reports back to you. fwrite(STDERR, sprintf("queued %s for %s\n", $message['id'] ?? '?', $message['to'] ?? '?')); }