一个功能完备的 PHP API 客户端,可与 Brevo 进行交互。
Official SDK for the Brevo API.
API reference documentation is available here.
This SDK requires PHP ^8.1.
composer require getbrevo/brevo-php
v5 is a major release. Most breaking changes come from an internal effort at Brevo to make endpoints, parameters and models more self-descriptive — so names, shapes and required fields convey intent without needing to cross-reference external docs (both for developers and for AI agents working against the Brevo API).
v4.x remains supported. If you need to hold on v4 temporarily, pin it:
composer require getbrevo/brevo-php:^4.0
View v4 → v5 migration guide
Companies — GetCompaniesRequest::filters renamed
filters is renamed to filtersAttributesName to match the wire format.'filters' => ... does not throw, but the filter is silently ignored server-side and the response is unfiltered. Audit every call site.Events — Event::createBatchEvents payload shape changed
// v4
$client->event->createBatchEvents($eventsArray);
// v5
use Brevo\Event\Requests\CreateBatchEventsRequest;
$client->event->createBatchEvents(
new CreateBatchEventsRequest(['events' => $eventsArray])
);
Balance — getActiveBalancesApi response shape changed
?BalanceLimit to ?GetLoyaltyBalanceProgramsPidActiveBalanceResponse.Balance — getContactBalances requires balanceDefinitionId
$request no longer defaults to empty; balanceDefinitionId is required.Balance — BeginTransactionRequest::eventTime type tightened
?string to ?DateTime. ISO strings now cause TypeError.CRM — Tasks::getAllTaskTypes returns an array (?array instead of ?GetCrmTasktypesResponse).
Email campaigns — utmIdActive renamed
EmailCampaigns\GetEmailCampaignResponse::utmIdActive renamed to utmId (wire key utmIDActive → utmID, type ?bool → ?int). Same change on GetEmailCampaignsResponseCampaignsItem.Model fields removed: GetAccountResponse::dateTimePreferences, Webhook::channel, GetProcessResponseInfo::export, GetProcessResponse::error/createdAt/completedAt, and several ExternalFeeds response fields.
Model field types tightened:
Process\GetProcessResponseInfoImport count fields: ?int → ?string (now URLs to CSV reports) — affects invalidEmails, duplicateContactId, duplicateExtId, etc.Ecommerce\CreateUpdateProductResponse::id and CreateUpdateCategoryResponse::id: ?int → ?string.string date fields tightened to ?DateTime (Program::*, Reward::*, BalanceLimit::createdAt/updatedAt).Model fields renamed: ConversationsMessageAttachmentsItem::fileName → name, ::inlineId → link.
Custom objects — associations union flattened: UpsertrecordsRequestRecordsItemAssociationsItem is now a single class with an action: 'link' | 'unlink' discriminator. Seven old variant classes have been deleted.
contacts->createContact, contacts->updateContact, emailCampaigns->getEmailCampaigns, ecommerce->getProducts, and several other endpoints.Warning: The legacy v1.x SDK will continue to receive critical security updates but no new features. We recommend migrating to v5.x.
View migration guide
Key changes:
Brevo client with namespaced resourcesBrevoApiExceptionv1.x:
use Brevo\Client\Configuration;
use Brevo\Client\Api\TransactionalEmailsApi;
use Brevo\Client\Model\SendSmtpEmail;
$config = Configuration::getDefaultConfiguration()->setApiKey('api-key', 'xkeysib-xxx');
$api = new TransactionalEmailsApi(new \GuzzleHttp\Client(), $config);
$message = new SendSmtpEmail();
$message->setSubject('First email');
$message->setTextContent('Hello world!');
$message->setSender(['name' => 'Bob Wilson', 'email' => '[email protected]']);
$message->setTo([['email' => '[email protected]', 'name' => 'Sarah Davis']]);
$api->sendTransacEmail($message);
v5.x:
…
Instantiate and use the client with the following:
',
);
$client->transactionalEmails->sendTransacEmail(
new SendTransacEmailRequest([
'htmlContent' => '
Hello,
This is my first transactional email sent from Brevo.
',
'sender' => new SendTransacEmailRequestSender([
'email' => '[email protected]',
'name' => 'Alex from Brevo',
]),
'subject' => 'Hello from Brevo!',
'to' => [
new SendTransacEmailRequestToItem([
'email' => '[email protected]',
'name' => 'John Doe',
]),
],
]),
);
When the API returns a non-success status code (4xx or 5xx response), an exception will be thrown.
use Brevo\Exceptions\BrevoApiException;
use Brevo\Exceptions\BrevoException;
try {
$response = $client->transactionalEmails->sendTransacEmail(...);
} catch (BrevoApiException $e) {
echo 'API Exception occurred: ' . $e->getMessage() . "\n";
echo 'Status Code: ' . $e->getCode() . "\n";
echo 'Response Body: ' . $e->getBody() . "\n";
// Optionally, rethrow the exception or handle accordingly.
}
This SDK is built to work with any HTTP client that implements the PSR-18 ClientInterface.
By default, if no client is provided, the SDK will use php-http/discovery to find an installed HTTP client.
However, you can pass your own client that adheres to ClientInterface:
use Brevo\Brevo;
// Pass any PSR-18 compatible HTTP client implementation.
// For example, using Guzzle:
$customClient = new \GuzzleHttp\Client([
'timeout' => 5.0,
]);
$client = new Brevo(
apiKey: 'xkeysib-xxx',
options: ['client' => $customClient],
);
// Or using Symfony HttpClient:
// $customClient = (new \Symfony\Component\HttpClient\Psr18Client())
// ->withOptions(['timeout' => 5.0]);
//
// $client = new Brevo(
// apiKey: 'xkeysib-xxx',
// options: ['client' => $customClient],
// );
The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).
A request is deemed retryable when any of the following HTTP status codes is returned:
Use the maxRetries request option to configure this behavior.
$response = $client->transactionalEmails->sendTransacEmail(
...,
options: [
'maxRetries' => 0 // Override maxRetries at the request level
]
);
The SDK does not configure a default timeout. Unless you set one, the underlying HTTP client's default applies (Guzzle, for example, defaults to no timeout). Set an explicit timeout (in seconds) at the client or request level:
// Client-level
$client = new Brevo('xkeysib-xxx', ['timeout' => 30.0]);
// Request-level (overrides client setting)
$response = $client->transactionalEmails->sendTransacEmail(
...,
options: [
'timeout' => 3.0
]
);
Timeout forwarding is supported for Guzzle and Symfony HttpClient. Other PSR-18 clients ignore the
timeoutoption.
The SDK does not ship a built-in logger. Because the client option accepts any PSR-18 HTTP client, you can plug in any PSR-3 logger (Monolog, Symfony Logger, Laravel's Log facade) by wrapping that client with logging middleware. This keeps the SDK lean and lets you reuse the logger your application already configures.
use Brevo\Brevo;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\MessageFormatter;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('brevo');
$logger->pushHandler(new StreamHandler('php://stderr', Logger::DEBUG));
$stack = HandlerStack::create();
$stack->push(Middleware::log(
$logger,
new MessageFormatter('{method} {uri} → {code}')
));
$client = new Brevo('xkeysib-xxx', [
'client' => new Client(['handler' => $stack, 'timeout' => 5.0]),
]);
Logging happens at the HTTP layer, so each SDK call produces one log line per HTTP request — including retries, which the SDK performs internally.
Warning: The
api-keyheader is sent on every request. If your message formatter includes request headers ({req_headers}), redact it before writing to disk or shipping to an external sink.
While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!
On the other hand, contributions to the README are always very welcome!
暂无开放 Issues,或尚未同步最近议题。