getbrevo/brevo-php
Legacy (v1.x) PHP SDK for Brevo API v3, auto-generated from OpenAPI/Swagger. Supports PHP 5.6+ and provides wrappers for Brevo features (email, contacts, campaigns, etc.). Maintained for critical security fixes only; migrate to brevo-php v4.
## Getting Started
### Minimal Setup
1. **Installation**
Add the package via Composer:
```bash
composer require getbrevo/brevo-php:1.x.x
Include the autoloader:
require __DIR__ . '/vendor/autoload.php';
First API Call
Configure API key (replace YOUR_API_KEY):
$config = Brevo\Client\Configuration::getDefaultConfiguration()
->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new Brevo\Client\Api\ContactsApi(new GuzzleHttp\Client(), $config);
First Use Case: Fetch Contacts
try {
$result = $apiInstance->getContacts();
print_r($result);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
AccountApi to fetch account details.ContactsApi for CRUD operations on contacts.ContactsApi methods like getLists() or createList().createDoiContact() for DOI workflows.$contact = new \Brevo\Client\Model\Contact([
'email' => 'user@example.com',
'attributes' => ['CUSTOM_FIELD' => 'value']
]);
$apiInstance->createContact($contact);
$contacts = [
['email' => 'user1@example.com', 'attributes' => ['AGE' => '30']],
['email' => 'user2@example.com', 'attributes' => ['AGE' => '25']]
];
$apiInstance->updateBatchContacts($contacts);
$listId = 123;
$contacts = ['user1@example.com', 'user2@example.com'];
$apiInstance->addContactToList($listId, $contacts);
TransactionalEmailsApi):
$sendSmtpEmail = new \Brevo\Client\Model\SendSmtpEmail([
'sender' => ['name' => 'John', 'email' => 'john@example.com'],
'to' => [['email' => 'user@example.com']],
'htmlContent' => '<p>Hello!</p>'
]);
$apiInstance->sendTransacEmail($sendSmtpEmail);
$deal = new \Brevo\Client\Model\Deal([
'title' => 'Project X',
'amount' => 1000.00,
'contactId' => 456
]);
$apiInstance = new Brevo\Client\Api\DealsApi(..., $config);
$apiInstance->createDeal($deal);
WebhooksApi):
$webhook = new \Brevo\Client\Model\Webhook([
'url' => 'https://your-app.com/webhook',
'events' => ['transactionalEmailSent']
]);
$apiInstance->createWebhook($webhook);
Service Provider Setup
Register the Brevo client in AppServiceProvider:
public function register()
{
$this->app->singleton('brevo', function ($app) {
$config = Brevo\Client\Configuration::getDefaultConfiguration()
->setApiKey('api-key', config('services.brevo.api_key'));
return new Brevo\Client\Api\ContactsApi(new GuzzleHttp\Client(), $config);
});
}
Facade for Cleaner Code
Create a BrevoFacade:
use Illuminate\Support\Facades\Facade;
class BrevoFacade extends Facade
{
protected static function getFacadeAccessor() { return 'brevo'; }
}
Usage:
Brevo::getContacts();
Exception Handling
Wrap API calls in a try-catch block or use Laravel’s try-catch helpers:
try {
$contacts = Brevo::getContacts();
} catch (\Brevo\Client\ApiException $e) {
Log::error('Brevo API Error: ' . $e->getMessage());
return response()->json(['error' => 'Failed to fetch contacts'], 500);
}
Configuration
Store API keys in .env:
BREVO_API_KEY=your_api_key_here
Load in config/services.php:
'brevo' => [
'api_key' => env('BREVO_API_KEY'),
],
Rate Limiting Implement middleware to handle Brevo’s rate limits (e.g., 10 requests/second):
public function handle($request, Closure $next)
{
$limit = Cache::get('brevo_requests', 0);
if ($limit >= 10) {
sleep(1); // Throttle
Cache::put('brevo_requests', 0, now()->addSecond());
} else {
Cache::increment('brevo_requests');
}
return $next($request);
}
API Key Misconfiguration
api-key vs. partner-key).Configuration::setApiKey() and verify it matches your Brevo account.Pagination Handling
page and pageSize parameters:
$apiInstance->getContacts(['page' => 1, 'pageSize' => 50]);
Loop through pages until nextPage is null.Idempotency
createContact) may not support idempotency, leading to duplicate entries.identifier (e.g., email) to check for existing contacts before creation.Webhook Delays
webhookId in a database).Attribute Limits
Deprecation Warnings
v1.x SDK is deprecated. New features require migration to v4.v4 in a staging environment.Enable Debugging Configure Guzzle’s HTTP client to log requests:
$client = new GuzzleHttp\Client([
'debug' => true,
'handler' => GuzzleHttp\HandlerStack::create(new GuzzleHttp\Middleware::tap(function ($request) {
Log::debug('Brevo Request:', [
'url' => (string) $request->getUri(),
'method' => $request->getMethod(),
'body' => $request->getBody() ? $request->getBody()->getContents() : null
]);
}))
]);
Validate Requests
Use json_encode() to inspect request payloads:
$contact = new \Brevo\Client\Model\Contact(['email' => 'test@example.com']);
Log::debug('Request Payload:', json_encode($contact));
Error Codes
Testing
$mockApi = Mockery::mock(Brevo\Client\Api\ContactsApi::class);
$mockApi->should
How can I help you explore Laravel packages today?