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

Sendinblue Api Bundle Laravel Package

blue-energy/sendinblue-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sendinblue/sendinblue-api-bundle:2.0.*
    

    Add to AppKernel.php:

    new SendinBlue\SendinBlueApiBundle\SendinBlueApiBundle(),
    
  2. Configure API Key: In config/packages/sendin_blue_api.yaml (Symfony 4+) or app/config/config.yml (Symfony 2/3):

    sendin_blue_api:
        api_key: "%env(SENDINBLUE_API_KEY)%"  # Use env vars for security
    
  3. First Use Case: Send a transactional email via a controller:

    use SendinBlue\SendinBlueApiBundle\Service\TransactionalEmailService;
    
    class EmailController extends AbstractController
    {
        public function sendEmail(TransactionalEmailService $emailService)
        {
            $email = [
                'to' => ['john@doe.com'],
                'subject' => 'Welcome!',
                'htmlContent' => '<h1>Hello!</h1>',
            ];
            $emailService->sendTransactionalEmail($email);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Transactional Emails:

    $emailService = $this->get('sendinblue_api.transactional_email');
    $emailService->sendTransactionalEmail([
        'to' => ['user@example.com'],
        'subject' => 'Your Order Confirmation',
        'htmlContent' => '<p>Order #12345</p>',
        'templateId' => 123, // Optional: Use a pre-designed template
    ]);
    
  2. SMTP Configuration: Use the bundle’s SMTP service for Laravel-like mailers:

    # config/packages/sendin_blue_api.yaml
    sendin_blue_api:
        api_key: "%env(SENDINBLUE_API_KEY)%"
        smtp:
            enabled: true
            host: "smtp.sendinblue.com"
            port: 587
    

    Then inject SendinBlue\SendinBlueApiBundle\Service\SmtpService into your mailer.

  3. Contact Management:

    $contactService = $this->get('sendinblue_api.contact');
    $contactService->createContact([
        'email' => 'user@example.com',
        'attributes' => ['NAME' => 'John Doe', 'AGE' => 30],
    ]);
    
  4. Event Hooks: Subscribe to SendinBlue webhooks (e.g., bounce events) via Symfony’s event dispatcher:

    # config/packages/sendin_blue_api.yaml
    sendin_blue_api:
        webhook:
            enabled: true
            secret: "%env(SENDINBLUE_WEBHOOK_SECRET)%"
    

    Create a listener:

    // src/EventListener/SendinBlueWebhookListener.php
    class SendinBlueWebhookListener
    {
        public function onWebhook(Request $request, EventDispatcherInterface $dispatcher)
        {
            $data = json_decode($request->getContent(), true);
            // Handle bounce, open, etc.
        }
    }
    
  5. Batch Operations: Use the BatchService for bulk contacts/emails:

    $batchService = $this->get('sendinblue_api.batch');
    $batchService->createBatch([
        'contacts' => [
            ['email' => 'user1@example.com'],
            ['email' => 'user2@example.com'],
        ],
        'email' => [
            'subject' => 'Batch Email',
            'htmlContent' => '<p>Hello batch!</p>',
        ],
    ]);
    

Integration Tips

  • Environment Variables: Store SENDINBLUE_API_KEY and SENDINBLUE_WEBHOOK_SECRET in .env for security. Example:

    SENDINBLUE_API_KEY=your_api_key_here
    SENDINBLUE_WEBHOOK_SECRET=your_webhook_secret
    
  • Dependency Injection: Prefer constructor injection for services:

    public function __construct(
        private TransactionalEmailService $emailService,
        private ContactService $contactService
    ) {}
    
  • Error Handling: Wrap API calls in try-catch blocks to handle SendinBlue\SendinBlueApiBundle\Exception\ApiException:

    try {
        $emailService->sendTransactionalEmail($email);
    } catch (ApiException $e) {
        $this->addFlash('error', 'Failed to send email: ' . $e->getMessage());
    }
    
  • Logging: Enable debug logging in config/packages/monolog.yaml:

    handlers:
        sendinblue:
            type: stream
            path: "%kernel.logs_dir%/sendinblue.log"
            level: debug
            channels: ["sendinblue"]
    

Gotchas and Tips

Pitfalls

  1. Deprecated API Version: This bundle uses SendinBlue API V2, which is outdated. Migrate to API V3 for long-term support.

    • Workaround: Fork the bundle and update the underlying SDK or use a wrapper.
  2. Symfony 4+ Compatibility: The bundle is not officially tested for Symfony 4/5. Use config/packages/sendin_blue_api.yaml instead of app/config/config.yml.

    • Fix: Manually create the config file or use config/packages/extra.yaml for legacy support.
  3. Webhook Verification: SendinBlue webhooks require a secret for verification. Always validate the X-Signature header:

    use SendinBlue\SendinBlueApiBundle\Event\WebhookEvent;
    
    public function onWebhook(WebhookEvent $event)
    {
        if (!$event->isValid()) {
            throw new \RuntimeException('Invalid webhook signature');
        }
    }
    
  4. Rate Limiting: SendinBlue enforces rate limits (e.g., 100 emails/hour for free tier). Implement retries with exponential backoff:

    use Symfony\Component\Stopwatch\Stopwatch;
    
    $stopwatch = new Stopwatch();
    $event = $stopwatch->start('send_email');
    
    try {
        $emailService->sendTransactionalEmail($email);
    } catch (ApiException $e) {
        if ($e->getCode() === 429) { // Too Many Requests
            $event->stop();
            sleep($event->getDuration() * 2); // Exponential backoff
            retry();
        }
    }
    
  5. SMTP vs. API: The SMTP service is a wrapper but may not support all API features (e.g., transactional templates). Prefer the API service for advanced use cases.


Debugging Tips

  1. Enable API Debugging: Set debug: true in config:

    sendin_blue_api:
        api_key: "%env(SENDINBLUE_API_KEY)%"
        debug: true
    

    Logs will appear in var/log/sendinblue.log.

  2. Test API Key: Validate your API key with a simple test:

    $apiService = $this->get('sendinblue_api.api');
    $response = $apiService->get('/account');
    dump($response); // Should return account details
    
  3. Webhook Testing: Use SendinBlue’s webhook simulator to test locally. Mock the request in Symfony:

    // tests/Functional/WebhookTest.php
    public function testWebhook()
    {
        $client = static::createClient();
        $client->request('POST', '/webhook', [
            'headers' => ['X-Signature' => 'your_signature'],
            'content' => json_encode(['event' => 'bounce']),
        ]);
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
    

Extension Points

  1. Custom Services: Extend the bundle’s services by overriding them in config/services.yaml:

    services:
        App\Service\CustomEmailService:
            arguments:
                $emailService: '@sendinblue_api.transactional_email'
            tags: ['sendinblue_api.custom_service']
    
  2. Event Subscribers: Listen to SendinBlue events (e.g., sendinblue.api.response) to log or transform responses:

    // src/EventSubscriber/SendinBlueSubscriber.php
    class SendinBlueSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'sendinblue.api.response' => 'onApiResponse',
            ];
        }
    
        public function onApiResponse(GetResponseEvent $event)
        {
            $response = $event->getResponse();
            // Modify or log the response
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium