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

beelab/mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require beelab/mailchimp-bundle
    

    Register the bundle in config/app.php under providers:

    BeeLab\MailchimpBundle\BeeLabMailchimpBundle::class,
    
  2. Configuration Publish the bundle’s config and set your API credentials:

    php artisan vendor:publish --provider="BeeLab\MailchimpBundle\BeeLabMailchimpBundle" --tag="config"
    

    Update .env:

    MAILCHIMP_API_KEY=your_api_key_here
    MAILCHIMP_DATACENTER=us12  # e.g., us12, eu1, etc.
    
  3. First Use Case: Add a Subscriber Inject the MailchimpClient service into a controller or command:

    use BeeLab\MailchimpBundle\Service\MailchimpClient;
    
    public function __construct(private MailchimpClient $mailchimp)
    {
    }
    
    public function subscribeUser(string $email, string $listId)
    {
        $this->mailchimp->lists()->members()->create($listId, [
            'email_address' => $email,
            'status' => 'subscribed',
        ]);
    }
    
  4. Where to Look First

    • Documentation: Resources/doc/index.md for API endpoints and usage.
    • Service Container: Check src/Service/ for available services (e.g., Lists, Campaigns, Members).
    • Examples: Look for Tests/ or Examples/ directories in the bundle for usage patterns.

Implementation Patterns

Core Usage Patterns

1. Service Injection

The bundle provides a fluent interface for Mailchimp API endpoints. Inject the MailchimpClient and chain methods:

$this->mailchimp
    ->lists()
    ->members()
    ->get($listId, $email);  // Get a member

2. Laravel Integration

Service Provider Binding Override or extend the bundle’s service bindings in your AppServiceProvider:

public function register()
{
    $this->app->extend(MailchimpClient::class, function ($app, $client) {
        $client->setLogger($app->make(LoggerInterface::class));
        return $client;
    });
}

Configuration Overrides Customize the bundle’s behavior via config/packages/beelab_mailchimp.yaml:

bee_lab_mailchimp:
    api_key: '%env(MAILCHIMP_API_KEY)%'
    dc: '%env(MAILCHIMP_DATACENTER)%'
    timeout: 30  # Custom timeout in seconds
    retries: 3   # Number of retries on failure

3. Queuing API Calls

Offload long-running Mailchimp operations to Laravel queues:

use Illuminate\Support\Facades\Queue;

Queue::push(new SyncMailchimpLists($this->mailchimp));

Example Job:

class SyncMailchimpLists implements ShouldQueue
{
    public function handle(MailchimpClient $mailchimp)
    {
        $mailchimp->lists()->getAll(); // Process in background
    }
}

4. Event-Driven Workflows

Trigger Laravel events after Mailchimp operations:

event(new SubscriberAdded($email, $listId));

// In an event listener:
public function handle(SubscriberAdded $event)
{
    Log::info("New subscriber: {$event->email} added to list {$event->listId}");
}

5. Custom API Endpoints

Extend the bundle to support unsupported endpoints:

$this->mailchimp->customRequest('GET', '/lists/{listId}/segments', ['listId' => $listId]);

Integration Tips

1. Handling API Errors

Catch exceptions thrown by the bundle and log/notify:

try {
    $this->mailchimp->lists()->members()->create($listId, $data);
} catch (MailchimpApiException $e) {
    Log::error("Mailchimp API Error: " . $e->getMessage());
    // Notify support or retry
}

2. Rate Limiting

Implement Laravel’s throttle middleware or use Guzzle’s retry logic:

$client = new MailchimpClient($apiKey, $dc);
$client->setHttpClient(new GuzzleHttpClient([
    'timeout' => 30,
    'headers' => ['Accept' => 'application/json'],
    'on_stats' => function (TransferStats $stats) {
        if ($stats->getHandlerStats()->getLastTransferTime() > 2) {
            sleep(1); // Throttle manually
        }
    }
]));

3. Caching Responses

Cache frequent API calls (e.g., lists, campaigns) using Laravel’s cache:

$cacheKey = "mailchimp_lists_{$listId}";
$lists = Cache::remember($cacheKey, now()->addHours(1), function () use ($mailchimp, $listId) {
    return $mailchimp->lists()->get($listId);
});

4. Testing

Mock the MailchimpClient in tests:

$mailchimpMock = Mockery::mock(MailchimpClient::class);
$mailchimpMock->shouldReceive('lists->members->create')
    ->once()
    ->andReturn(['id' => 'abc123']);

$this->app->instance(MailchimpClient::class, $mailchimpMock);

Gotchas and Tips

Pitfalls

1. Symfony Dependencies

  • The bundle may rely on Symfony components (e.g., HttpClient, OptionsResolver). Replace them with Laravel equivalents:
    // Replace Symfony HttpClient with Guzzle
    $this->app->bind(MailchimpClient::class, function ($app) {
        $client = new MailchimpClient($app['config']['mailchimp.api_key'], $app['config']['mailchimp.dc']);
        $client->setHttpClient(new GuzzleHttpClient());
        return $client;
    });
    

2. API Key Management

  • Never hardcode API keys. Use Laravel’s .env or a secure secrets manager.
  • Rotate keys periodically and update the config.

3. Rate Limits

  • Mailchimp enforces 10 calls/second. Exceeding this may result in temporary bans.
  • Tip: Use Laravel’s throttle middleware or implement exponential backoff.

4. Undocumented Endpoints

  • The bundle may not support all Mailchimp v3 endpoints. Check the Mailchimp API docs and extend as needed:
    $response = $this->mailchimp->customRequest('GET', '/lists/{listId}/segments');
    

5. Webhook Limitations

  • The bundle likely does not support webhooks. Implement a custom solution:
    Route::post('/mailchimp-webhook', function (Request $request) {
        $payload = $request->json()->all();
        // Validate and process webhook
    });
    

6. Timeouts and Retries

  • Mailchimp API calls may time out. Configure retries in the client:
    $client->setHttpClient(new GuzzleHttpClient([
        'timeout' => 30,
        'retries' => 3,
        'connect_timeout' => 5,
    ]));
    

Debugging Tips

1. Enable Logging

Configure the bundle to log API requests/responses:

bee_lab_mailchimp:
    debug: true

Or manually:

$client->setLogger(new MonologLogger([
    new StreamHandler(storage_path('logs/mailchimp.log'), Logger::DEBUG),
]));

2. Validate API Responses

Always check the response structure:

$response = $this->mailchimp->lists()->get($listId);
if (isset($response['errors'])) {
    throw new \RuntimeException("Mailchimp API Error: " . $response['errors'][0]['message']);
}

3. Use Postman for Testing

Test endpoints manually in Postman using your API key to verify responses before integrating.

4. Handle Deprecated Endpoints

Mailchimp deprecates endpoints. Check the bundle’s src/ for hardcoded paths and update them:

// Example: Replace deprecated endpoint
$client->setBaseUri('https://' . $dc . '.api.mailchimp
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