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 Bundle2 Laravel Package

djamadeus/mailchimp-bundle2

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require wunderdata/mailchimp-bundle
    
  2. Configure in config/packages/wunderdata_mailchimp.yaml (Symfony 5+):

    wunderdata_mailchimp:
        apikey: "your_api_key-usX"  # Replace with your Mailchimp API key (e.g., "abc123-us1")
        opts:
            debug: true  # Enable for debugging API calls
            timeout: 600 # Timeout in seconds
    

    For Symfony <5, use app/config/config.yml as shown in the README.

  3. First Use Case: Inject the client in a controller/service and call a basic API method:

    use Wunderdata\MailchimpBundle\Client\Client;
    
    public function listCampaigns(Client $mailchimpClient)
    {
        $campaigns = $mailchimpClient->call('campaigns', 'get');
        return json_encode($campaigns);
    }
    

Implementation Patterns

Core Workflows

  1. API Calls: Use the call() method to interact with Mailchimp’s v2.0 API:

    // Get lists
    $lists = $mailchimpClient->call('lists', 'get');
    
    // Create a subscriber
    $subscriber = $mailchimpClient->call(
        'lists/' . $listId . '/members',
        'post',
        ['email_address' => 'user@example.com', 'status' => 'subscribed']
    );
    
  2. Export API (v1.0): Use ExportClient for batch exports (e.g., subscribers):

    $exportClient = $this->get('wunderdata_mailchimp.export_client');
    $export = $exportClient->createExport($listId, 'subscribers', 'csv');
    $exportClient->pollExport($export['id']); // Wait for completion
    $exportClient->downloadExport($export['id']); // Stream/download file
    
  3. Dependency Injection: Prefer injecting the client via constructor (Symfony best practice):

    public function __construct(private Client $mailchimpClient) {}
    
  4. Error Handling: Wrap API calls in try-catch blocks to handle Mailchimp errors:

    try {
        $result = $mailchimpClient->call('lists', 'get');
    } catch (\Exception $e) {
        // Log or handle error (e.g., rate limit, invalid API key)
        $this->addFlash('error', $e->getMessage());
    }
    

Integration Tips

  1. Environment Variables: Store apikey in .env and reference it in config:

    wunderdata_mailchimp:
        apikey: "%env(MAILCHIMP_API_KEY)%"
    
  2. Rate Limiting: Mailchimp’s API has rate limits. Implement retries with exponential backoff:

    use Symfony\Component\HttpKernel\Exception\RateLimitedHttpException;
    
    try {
        $mailchimpClient->call('lists', 'get');
    } catch (RateLimitedHttpException $e) {
        sleep(2 ** $retryCount); // Exponential backoff
        $retryCount++;
    }
    
  3. Webhooks: Use the webhooks API endpoint to subscribe to Mailchimp events (e.g., subscribe, unsubscribe):

    $webhook = $mailchimpClient->call('webhooks', 'post', [
        'url' => 'https://your-app.com/mailchimp-webhook',
        'events' => ['subscribe', 'unsubscribe'],
    ]);
    
  4. Testing: Mock the client in tests using Symfony’s ContainerInterface:

    $container->set('wunderdata_mailchimp.client', $mockClient);
    

Gotchas and Tips

Pitfalls

  1. API Key Format: The API key must include the datacenter suffix (e.g., abc123-us1). Omitting this will cause 401 Unauthorized errors.

  2. Deprecated Methods: The bundle uses Mailchimp’s v2.0 API, which is deprecated. Plan to migrate to v3.0 soon.

  3. Export API Limitations:

    • The Export API (ExportClient) is not officially supported by Mailchimp. Use at your own risk.
    • Exports may fail silently or time out. Implement robust polling/download logic.
  4. Debugging: Enable debug: true in config to log raw API requests/responses to var/log/dev.log.

  5. CORS/CSRF: If using webhooks, ensure your endpoint:

    • Validates the X-Mailchimp-Signature header.
    • Uses HTTPS (Mailchimp requires it for webhooks).

Tips

  1. Batch Operations: Use batch endpoints for bulk actions (e.g., updating subscribers):

    $batch = $mailchimpClient->call('lists/' . $listId . '/members/batch', 'post', [
        'ops' => [
            ['method' => 'PUT', 'path' => 'user@example.com', 'body' => ['status' => 'unsubscribed']],
        ],
    ]);
    
  2. Pagination: Handle paginated responses manually (v2.0 API lacks built-in pagination):

    $offset = 0;
    $limit = 100;
    do {
        $subscribers = $mailchimpClient->call(
            'lists/' . $listId . '/members',
            'get',
            ['offset' => $offset, 'limit' => $limit]
        );
        $offset += $limit;
    } while (!empty($subscribers));
    
  3. Configuration Overrides: Override bundle config per environment (e.g., config/packages/dev/wunderdata_mailchimp.yaml):

    wunderdata_mailchimp:
        opts:
            debug: true
    
  4. Custom Clients: Extend the Client class to add domain-specific methods:

    class CustomMailchimpClient extends Client {
        public function syncList($listId, array $members) {
            foreach ($members as $member) {
                $this->call("lists/$listId/members/{$member['email']}", 'put', [
                    'email_address' => $member['email'],
                    'status' => $member['status'] ?? 'subscribed',
                ]);
            }
        }
    }
    
  5. Logging: Log critical API calls for auditing:

    $this->logger->info('Mailchimp API call', [
        'endpoint' => 'lists/' . $listId . '/members',
        'method' => 'post',
        'data' => $subscriberData,
    ]);
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
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