Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Brevo Php Laravel Package

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.

View on GitHub
Deep Wiki
Context7
## 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';
  1. 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);
    
  2. First Use Case: Fetch Contacts

    try {
        $result = $apiInstance->getContacts();
        print_r($result);
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
    }
    

Key Starting Points

  • Account Info: Use AccountApi to fetch account details.
  • Contacts: Use ContactsApi for CRUD operations on contacts.
  • Lists: Use ContactsApi methods like getLists() or createList().
  • Double-Opt-In (DOI): Use createDoiContact() for DOI workflows.

Implementation Patterns

Common Workflows

1. Contact Management

  • Create/Update Contacts:
    $contact = new \Brevo\Client\Model\Contact([
        'email' => 'user@example.com',
        'attributes' => ['CUSTOM_FIELD' => 'value']
    ]);
    $apiInstance->createContact($contact);
    
  • Batch Updates:
    $contacts = [
        ['email' => 'user1@example.com', 'attributes' => ['AGE' => '30']],
        ['email' => 'user2@example.com', 'attributes' => ['AGE' => '25']]
    ];
    $apiInstance->updateBatchContacts($contacts);
    

2. List Management

  • Add Contacts to List:
    $listId = 123;
    $contacts = ['user1@example.com', 'user2@example.com'];
    $apiInstance->addContactToList($listId, $contacts);
    

3. Email Campaigns

  • Send Transactional Email (via 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);
    

4. CRM Operations

  • Create a Deal:
    $deal = new \Brevo\Client\Model\Deal([
        'title' => 'Project X',
        'amount' => 1000.00,
        'contactId' => 456
    ]);
    $apiInstance = new Brevo\Client\Api\DealsApi(..., $config);
    $apiInstance->createDeal($deal);
    

5. Webhooks

  • Register a Webhook (via WebhooksApi):
    $webhook = new \Brevo\Client\Model\Webhook([
        'url' => 'https://your-app.com/webhook',
        'events' => ['transactionalEmailSent']
    ]);
    $apiInstance->createWebhook($webhook);
    

Integration Tips

Laravel-Specific Patterns

  1. 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);
        });
    }
    
  2. 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();
    
  3. 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);
    }
    
  4. 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'),
    ],
    
  5. 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);
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Misconfiguration

    • Issue: Forgetting to set the API key or using the wrong key type (api-key vs. partner-key).
    • Fix: Double-check the key in Configuration::setApiKey() and verify it matches your Brevo account.
  2. Pagination Handling

    • Issue: The SDK doesn’t automatically paginate responses. Large datasets (e.g., contacts) require manual pagination.
    • Fix: Use the page and pageSize parameters:
      $apiInstance->getContacts(['page' => 1, 'pageSize' => 50]);
      
      Loop through pages until nextPage is null.
  3. Idempotency

    • Issue: Some endpoints (e.g., createContact) may not support idempotency, leading to duplicate entries.
    • Fix: Use identifier (e.g., email) to check for existing contacts before creation.
  4. Webhook Delays

    • Issue: Webhook deliveries may be delayed or retried by Brevo.
    • Fix: Implement idempotency in your webhook handler (e.g., store webhookId in a database).
  5. Attribute Limits

    • Issue: Custom attributes have limits (e.g., 50 per category). Exceeding limits may cause silent failures.
    • Fix: Validate attribute counts before bulk operations.
  6. Deprecation Warnings

    • Issue: The v1.x SDK is deprecated. New features require migration to v4.
    • Fix: Plan a migration timeline and test v4 in a staging environment.

Debugging Tips

  1. 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
            ]);
        }))
    ]);
    
  2. 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));
    
  3. Error Codes

    • 400 Bad Request: Validate request payloads (e.g., missing required fields).
    • 401 Unauthorized: Check API key permissions or expiration.
    • 404 Not Found: Verify resource IDs (e.g., contact/list IDs).
    • 429 Too Many Requests: Implement rate limiting (see Integration Tips).
  4. Testing

    • Use Brevo’s sandbox environment for testing.
    • Mock the SDK in unit tests:
      $mockApi = Mockery::mock(Brevo\Client\Api\ContactsApi::class);
      $mockApi->should
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony