PHP SDK
用 billionsend-php 套件在 PHP 中傳送郵件、操作收件匣、驗證 Webhook,涵蓋全部 API 操作,內建重試與冪等鍵。
billionsend/billionsend-php 套件是 BillionSend 面向 PHP 的用戶端。它涵蓋 API 參考中的全部操作:傳送、網域、聯絡人、群發、範本、Webhook、含會話串與草稿的收件匣、即時的收件匣事件,以及 Agent 註冊。原始碼在 GitHub 上的 billionsend/billionsend-php。
安裝
需要 PHP 8.1 或更新版本,並啟用 curl 和 json 擴充,不需要其他東西。
composer require billionsend/billionsend-php
傳送郵件
use BillionSend\Client;
$client = new Client(); // 讀取 BILLIONSEND_API_KEY
$sent = $client->emails->send([
'from' => 'Acme <hello@acme.dev>',
'to' => ['success@simulator.amazonses.com'],
'subject' => 'Welcome to Acme',
'html' => '<p>Glad you are here.</p>',
], ['idempotency_key' => 'welcome/ana']);
echo $sent['id'];
new Client('bs_...') 直接傳入金鑰。第二個參數設定其餘選項:'base_url'、'timeout'(每次嘗試的秒數,預設 60)、'max_retries'、'headers' 和 'transport'(任何 BillionSend\Transport,用來經由你自己的 HTTP 堆疊傳送)。BILLIONSEND_BASE_URL 可以覆寫 API 網址。
方法命名
每個操作都是一個方法,以它在 API 參考中的 id 命名,以點分隔的路徑寫成服務鏈:emails.send 是 $client->emails->send(),emails.receiving.attachments.list 是 $client->emails->receiving->attachments->list()。emails.metrics 是 $client->emails->metrics->get(),與 ->links()、->countries() 和 ->clients() 並列。
方法依序接受路徑參數、請求本文、查詢與標頭參數,然後是該次呼叫的選項。請求本文和回應都是關聯式陣列,使用 API 自己的欄位名稱,所以 API 參考逐欄位地描述了它們。
冪等與重試
八個傳送操作(emails->send、emails->batch、收到的郵件的回覆與轉寄、inboxes->send、inboxes->drafts->send、會話串的回覆與轉寄)一律會帶上 Idempotency-Key。沒有 'idempotency_key' 時,每次呼叫都會自己產生一個,並在重試中沿用,所以逾時後的重試不會重複傳送;你自己的鍵還能讓另一個行程中的重複呼叫也保持安全。
值得重試的失敗預設會重試兩次:429、5xx、逾時、網路錯誤,以及同一個鍵的第一次請求仍在執行時回傳的 409 concurrent_idempotent_requests。只有重複執行也安全的請求才會重試:GET、PUT、DELETE 和傳送操作。用戶端依 Retry-After 的要求等待,最長一分鐘,其餘情況從 0.5 秒到 8 秒採指數退避。每個方法的最後一個參數都接受 'idempotency_key'、'headers'、'timeout'、'max_retries' 和 'response_headers' => &$headers,供該次呼叫使用。
錯誤
失敗的呼叫會拋出 ValidationError(400、422)、AuthenticationError(401,或沒有設定金鑰)、PermissionDeniedError(403)、NotFoundError(404)、ConflictError(409)、RateLimitError(429,getRetryAfter() 以秒為單位)、APIError(5xx)、APIConnectionError(沒有回應)或 APITimeoutError(這次嘗試逾時)。它們都在 BillionSend\Exception 中,並繼承 BillionSendError,帶有 getStatusCode()、getErrorName()(API 的錯誤名稱)、getMessage() 和 getRequestId();getRequestId() 是回應的 x-request-id,也就是這個請求在控制台日誌頁面上的 id。
use BillionSend\Exception\BillionSendError;
use BillionSend\Exception\NotFoundError;
try {
$email = $client->emails->get($id);
} catch (NotFoundError) {
// 沒有這封郵件
} catch (BillionSendError $e) {
error_log(sprintf('%s %s: %s (request %s)', $e->getStatusCode(), $e->getErrorName(), $e->getMessage(), $e->getRequestId()));
}
列表
列表方法回傳一頁。每個游標式列表還有一個 ...All() 產生器,會在迭代時取得後續的頁面,設定了 'before' 時則向前取得:
foreach ($client->contacts->listAll(['limit' => 100]) as $contact) {
echo $contact['email'], "\n";
}
Agent 的收件匣
在事件串流上等待新郵件,並在它所在的會話串中回覆:
use BillionSend\StreamGapEvent;
$stream = $client->inboxes->events->streamInbox('support@acme.dev', ['types' => 'inbox.email.received']);
foreach ($stream as $event) {
if ($event instanceof StreamGapEvent) {
continue; // 事件可能有遺漏:重新讀取會話串
}
$data = $event->payload();
$client->inboxes->threads->emails->reply(
$event->inboxId(),
$data['thread_id'],
$data['email_id'],
['text' => 'Thanks, we are on it.'],
['idempotency_key' => "reply/{$data['email_id']}"],
);
}
連線中斷時,事件串流會帶著 Last-Event-ID 重新連線,並補上錯過的事件;保留 $stream->lastEventId(),並以 'last_event_id' 選項傳回去,就能在重新啟動後接續。從 24 小時前的位置恢復時,會收到一次 StreamGapEvent。選項 'max_reconnects'(預設 5)、'reconnect_delay' 和 'reconnect' => false 可調整重新連線的行為。單一收件匣的事件串流在該收件匣被刪除或到期後結束;$client->inboxes->events->stream() 會追蹤金鑰能讀取的所有收件匣。
驗證 Webhook
Webhook::verify 用端點的 whsec_ 金鑰檢查一次 Webhook 投遞的簽章和時間戳記,並回傳解析後的事件。傳入的請求本文必須與收到時完全一致:
use BillionSend\Exception\WebhookVerificationError;
use BillionSend\Webhook;
try {
$event = Webhook::verify(file_get_contents('php://input'), getallheaders(), getenv('BILLIONSEND_WEBHOOK_SECRET'));
} catch (WebhookVerificationError) {
http_response_code(400);
exit;
}
if ($event['type'] === 'email.bounced') {
// ...
}
超過五分鐘的投遞會被拒絕,金鑰輪替期間,新舊兩個金鑰都能通過驗證。
Agent 註冊
$signup = (new BillionSend\Client())->agent->signup(['human_email' => 'owner@acme.dev', 'name' => 'Support agent']);
echo $signup['inbox']['email_address'], "\n";
這個呼叫不需要 API 金鑰;回應中帶有新的金鑰和收件匣。未認領的帳號可以做什麼,參閱 Agent 註冊。