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

Mailchimp Api Connector Bundle Laravel Package

dcsg/mailchimp-api-connector-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require dcsg/mailchimp-api-connector-bundle:~2.0
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Dcsg\MailchimpApiConnectorBundle\DcsgMailchimpApiConnectorBundle::class => ['all' => true],
    ];
    
  2. Configure Mailchimp API Key Add your Mailchimp API key to config/packages/dcsg_mailchimp_api_connector.yaml:

    dcsg_mailchimp_api_connector:
        api_key: 'your-mailchimp-api-key-us12'  # Replace with your key (e.g., 'us12' for US region)
    
  3. First Use Case: Fetching Lists Inject the MailchimpApiConnector service and fetch a list of Mailchimp lists:

    use Dcsg\MailchimpApiConnectorBundle\Service\MailchimpApiConnector;
    
    class MailchimpService
    {
        public function __construct(private MailchimpApiConnector $mailchimp)
        {
        }
    
        public function getLists()
        {
            return $this->mailchimp->getLists();
        }
    }
    

Implementation Patterns

Common Workflows

  1. Subscribing Users to a List

    $this->mailchimp->subscribe('list-id', [
        'email' => 'user@example.com',
        'merge_fields' => [
            'FNAME' => 'John',
            'LNAME' => 'Doe',
        ],
    ]);
    
  2. Fetching Subscribers

    $subscribers = $this->mailchimp->getSubscribers('list-id', ['status' => 'subscribed']);
    
  3. Sending Campaigns

    $campaign = $this->mailchimp->createCampaign([
        'type' => 'regular',
        'recipients' => ['list_id' => 'list-id'],
        'settings' => [
            'subject_line' => 'Hello from Laravel!',
            'from_name' => 'Your App',
            'reply_to' => 'noreply@example.com',
        ],
    ]);
    
  4. Handling Webhooks (Legacy) Use Symfony’s event system to process Mailchimp webhooks (e.g., subscriber updates):

    # config/packages/dcsg_mailchimp_api_connector.yaml
    dcsg_mailchimp_api_connector:
        webhook:
            enabled: true
            secret: 'your-webhook-secret'
            events: ['subscribe', 'unsubscribe']
    

Integration Tips

  • Laravel-Specific: Use Symfony’s ContainerInterface to access the service in Laravel:
    $mailchimp = app('mailchimp_api_connector');
    
  • Error Handling: Wrap API calls in try-catch blocks to handle Mailchimp API errors:
    try {
        $this->mailchimp->getLists();
    } catch (\Dcsg\MailchimpApiConnector\Exception\MailchimpException $e) {
        Log::error('Mailchimp API error: ' . $e->getMessage());
    }
    
  • Batch Operations: For large datasets, use pagination:
    $subscribers = [];
    $offset = 0;
    do {
        $batch = $this->mailchimp->getSubscribers('list-id', ['offset' => $offset, 'limit' => 100]);
        $subscribers = array_merge($subscribers, $batch);
        $offset += 100;
    } while (!empty($batch));
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle: The last release was in 2014. Ensure compatibility with:

    • Symfony 2.x (likely 2.3–2.7).
    • PHP 5.4–5.6 (Laravel 5.x may require polyfills).
    • Mailchimp API v3.0: This bundle may not support newer endpoints (e.g., /ecommerce/stores). Use the official Mailchimp PHP SDK for v3+.
  2. Webhook Limitations:

    • The webhook system is Symfony2-specific and may not work out-of-the-box in Laravel.
    • Use Laravel’s Http facade or a queue worker to poll for updates instead.
  3. API Key Format:

    • Keys must include the datacenter suffix (e.g., us12, eu1). Omitting this will cause 401 Unauthorized errors.
  4. Rate Limiting:

    • Mailchimp throttles requests (30 calls/second). Implement retries with exponential backoff:
      use Symfony\Component\HttpKernel\Exception\RateLimitExceededHttpException;
      
      try {
          $this->mailchimp->getLists();
      } catch (RateLimitExceededHttpException $e) {
          sleep(1); // Wait before retrying
          retry();
      }
      

Debugging Tips

  1. Enable Verbose Logging:

    # config/packages/monolog.yaml
    handlers:
        mailchimp:
            type: stream
            path: "%kernel.logs_dir%/mailchimp.log"
            level: debug
    

    Log raw API responses to debug payloads or errors.

  2. Test with a Sandbox Account:

  3. Check HTTP Headers:

    • Ensure the Authorization: Basic header is correctly formatted:
      // Example of manual auth (if bundle fails)
      $client = new \GuzzleHttp\Client([
          'base_uri' => 'https://us12.admin.mailchimp.com/3.0/',
          'headers' => [
              'Authorization' => 'Basic ' . base64_encode('api_key:'),
          ],
      ]);
      

Extension Points

  1. Custom API Endpoints: Override the MailchimpApiConnector service to extend functionality:

    # config/services.yaml
    services:
        App\Service\CustomMailchimpService:
            arguments:
                $connector: '@mailchimp_api_connector'
    
    class CustomMailchimpService
    {
        public function __construct(private MailchimpApiConnector $connector)
        {
        }
    
        public function customEndpoint()
        {
            return $this->connector->makeRequest('GET', '/custom/endpoint');
        }
    }
    
  2. Event Listeners: Subscribe to Mailchimp events (e.g., mailchimp.subscriber.created) via Symfony’s event dispatcher:

    use Dcsg\MailchimpApiConnectorBundle\Event\SubscriberEvent;
    
    class MailchimpSubscriberListener
    {
        public function onSubscriberCreated(SubscriberEvent $event)
        {
            // Handle new subscriber
        }
    }
    

    Register the listener in services.yaml:

    services:
        App\EventListener\MailchimpSubscriberListener:
            tags:
                - { name: kernel.event_listener, event: mailchimp.subscriber.created, method: onSubscriberCreated }
    
  3. Mocking for Tests: Use a mock MailchimpApiConnector in PHPUnit:

    $mock = $this->createMock(MailchimpApiConnector::class);
    $mock->method('getLists')->willReturn(['list1', 'list2']);
    $this->container->set('mailchimp_api_connector', $mock);
    
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