Sign inGet Started

PHP SDK

messagebird/sdk 是 Bird API 的官方 PHP SDK:在生成的传输层之上手写的类型化接口。它面向 PHP 8.2+,采用同步方式;HTTP 通过你已有的任意 PSR-18 客户端(Guzzle、Symfony HttpClient 等)发送,并自动发现该客户端。本页介绍客户端本身;如需端到端发送电子邮件,请从 PHP 电子邮件快速入门开始。

安装

代码示例
composer require messagebird/sdk

该软件包以 Packagist 上的 messagebird/sdk 发布。

创建客户端

代码示例
$bird = new Bird(
    getenv('BIRD_API_KEY') ?: '',
    region: 'eu1',                                          // optional; overrides the region inferred from the key prefix
    maxRetries: 2,                                          // retry budget for transient failures (default 2)
    email: new EmailDefaults(from: 'hello@acme.com'),       // optional channel defaults, such as a default sender
    webhookSecret: getenv('BIRD_WEBHOOK_SECRET') ?: null,   // signing secret for $bird->webhooks->unwrap()
);

只有 API 密钥是必需的。区域根据密钥的 bk_{region}_ 前缀推断(bk_eu1_… 密钥路由到 https://eu1.platform.bird.com),因此大多数客户端只需密钥即可创建;规则请参阅区域推断。baseUrl 会完全覆盖区域(用于本地或自托管环境)。在此设置的渠道默认值(例如 email: new EmailDefaults(from: "hello@acme.com"))使该字段在每次发送时都变为可选,webhookSecret 是 $bird->webhooks->unwrap() 进行验证时使用的密钥。请在传给 Bird 的 PSR-18 客户端上配置单次请求超时。PSR-18 没有可移植的超时设置,因此该设置由传输层负责。

第一次调用

代码示例
$message = $bird->email->send(
    from: 'Bird <onboarding@messagebird.dev>',
    to: ['delivered@messagebird.dev'],
    subject: 'Hello from Bird',
    html: '<p>My first Bird email.</p>',
);
echo $message->getId(), ' ', $message->getStatus();

调用直接返回 API 结果:此处是一封带有 em_* id 的电子邮件消息。如需可运行的完整示例,请参阅 PHP 快速入门。

双层设计

SDK 结合了生成层和手写层。MessageBird\Wire 下的传输类型由 jane-php 根据 Bird 的 OpenAPI 规范生成,使请求和响应结构与契约保持一致。手写层提供 $bird->email->send(...)、重试、幂等性、分页、错误处理和 webhook 验证。传输字段以 snake_case 原样传递,例如 category 和 created_at。只有 SDK 定义的标识符(包括 idempotencyKey 等方法名和选项名)使用 camelCase。TypeScript、Go 和 Python SDK 采用相同架构;请参阅 SDK 概念。

自动幂等与重试

每个变更请求(POST、PUT、PATCH、DELETE)都会自动生成一个 Idempotency-Key 请求头,且同一个键会在每次重试尝试中复用,因此匹配的重试可以重放已保留的响应。重试默认开启(maxRetries: 2):客户端会以带抖动的指数退避重试临时性故障(429、除 501 外的 5xx,以及 PSR-18 传输错误),并遵循服务器的 Retry-After 响应头。确定性故障(如 401、404、422 等 4xx)永远不会重试。如需在多次独立的 SDK 调用之间使用自定义键,或了解重放限制,请参阅幂等性。可按调用覆盖幂等和重试设置:

代码示例
$bird->email->send(
    from: 'Bird <onboarding@messagebird.dev>',
    to: ['delivered@messagebird.dev'],
    subject: 'Hello from Bird',
    html: '<p>My first Bird email.</p>',
    options: new RequestOptions(idempotencyKey: 'order-1234', maxRetries: 0),
);

错误

调用失败时会抛出异常。MessageBird\Exception\ApiException 涵盖服务器返回的所有错误响应,并包含 status(HTTP 状态码)、type(粗粒度类别)和 errorCode(稳定的 E##### 错误码)。如果传输故障耗尽了重试预算,则会抛出 MessageBird\Exception\ConnectionException,因为此时不存在 HTTP 响应。两者都继承自 MessageBird\Exception\BirdException,捕获它即可同时处理这两种情况。

代码示例
try {
    $bird->email->send(
        from: 'Bird <onboarding@messagebird.dev>',
        to: ['delivered@messagebird.dev'],
        subject: 'Hello from Bird',
        html: '<p>My first Bird email.</p>',
    );
} catch (ApiException $e) {
    // The server returned an error response. $status is the HTTP status, $type
    // the coarse category, $errorCode the stable E##### code, and $requestId
    // the ID to quote when you contact support.
    echo $e->status, ' ', $e->errorCode ?? $e->type ?? 'error', ' ', $e->requestId ?? '';
} catch (ConnectionException $e) {
    // All retry attempts failed, so no HTTP response is available.
    echo 'transport error: ', $e->getMessage();
}

分页

列表方法返回惰性的 Core\Page;使用 foreach 遍历它时会跨游标自动分页,按需获取各页:

代码示例
foreach ($bird->email->list(['status' => 'delivered']) as $message) {
    echo $message->getId(), "\n";
}

如需手动控制游标,fetch() 只返回一页:其中包含 data 以及向前的 nextCursor,将后者作为 starting_after 传回即可翻到下一页:

代码示例
$page = $bird->email->list(['status' => 'delivered'])->fetch();
foreach ($page->data as $message) {
    echo $message->getId(), "\n";
}
$next = $page->nextCursor; // pass back as starting_after to fetch the next page

底层调用

尚未纳入类型化接口的端点可通过 $bird->get / post / put / patch / delete 访问,并采用相同的认证、重试、幂等和基础 URL 处理:

代码示例
// The verb methods (get/post/put/patch/delete) run through the same auth,
// retries, idempotency, and base-URL handling as the typed methods; pass a
// path and, for writes, a body array.
$messages = $bird->get('/v1/sms/messages', query: ['limit' => 10]);
$created = $bird->post('/v1/sms/messages', body: [
    'from' => '+15557654321',
    'to' => '+15551234567',
    'text' => 'Your code is 123456.',
    'category' => 'authentication',
]);

请在 API 参考文档中查找路径。

Webhook

验证已送达 webhook 的 Standard Webhooks 签名,并获取解码后的事件。在客户端上设置签名密钥(或在每次调用时传入),并且传入原始请求体:签名基于原始字节计算,因此在验证前解析请求体会导致签名验证失败。

代码示例
// Pass the raw request body because parsing changes the bytes used to compute
// the signature.
$rawBody = file_get_contents('php://input') ?: '';
try {
    $event = $bird->webhooks->unwrap($rawBody, getallheaders());
    // $event is the decoded payload as an array; branch on $event['type'].
    echo $event['type'];
} catch (WebhookVerificationError) {
    http_response_code(400); // bad signature, stale timestamp, or missing/malformed headers
}

后续步骤