|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, '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] ?? ''; $templateId = (int) ($argv[2] ?? 0); $from = getenv('SENDPIER_FROM'); if ($recipient === '' || $templateId <= 0 || $from === false || $from === '') { fwrite(STDERR, "usage: SENDPIER_FROM=orders@example.com php send-with-template.php \n"); exit(64); } $response = sendpier_request('POST', '/v1/messages', [ 'from' => ['email' => $from], 'to' => [['email' => $recipient]], 'template_id' => $templateId, // Send every variable the template uses. Miss one and the whole request is // refused with 422 missing_template_variables, naming the fields you left // out -- so nobody receives a half-filled message. // // Values under an email address apply to that recipient only and win from // the general ones: // 'variables' => ['ordernummer' => 'A-1', 'jan@example.org' => ['voornaam' => 'Jan']] 'variables' => [ 'voornaam' => 'Jan', 'ordernummer' => 'A-1024', ], // 'html' or 'text' next to a template_id is refused with 422 // template_body_conflict: the body comes from the template. Your own // 'subject' is allowed and overrides the one of the template. ]); echo $response['raw'], "\n"; if ($response['status'] !== 202) { fwrite(STDERR, "request failed with HTTP {$response['status']}\n"); exit(1); } foreach ($response['body']['data'] ?? [] as $message) { fwrite(STDERR, sprintf("queued %s for %s\n", $message['id'] ?? '?', $message['to'] ?? '?')); }