Installation
composer require beelab/mailchimp-bundle
Register the bundle in config/app.php under providers:
BeeLab\MailchimpBundle\BeeLabMailchimpBundle::class,
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.
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',
]);
}
Where to Look First
Resources/doc/index.md for API endpoints and usage.src/Service/ for available services (e.g., Lists, Campaigns, Members).Tests/ or Examples/ directories in the bundle for usage patterns.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
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
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
}
}
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}");
}
Extend the bundle to support unsupported endpoints:
$this->mailchimp->customRequest('GET', '/lists/{listId}/segments', ['listId' => $listId]);
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
}
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
}
}
]));
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);
});
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);
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;
});
.env or a secure secrets manager.throttle middleware or implement exponential backoff.$response = $this->mailchimp->customRequest('GET', '/lists/{listId}/segments');
Route::post('/mailchimp-webhook', function (Request $request) {
$payload = $request->json()->all();
// Validate and process webhook
});
$client->setHttpClient(new GuzzleHttpClient([
'timeout' => 30,
'retries' => 3,
'connect_timeout' => 5,
]));
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),
]));
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']);
}
Test endpoints manually in Postman using your API key to verify responses before integrating.
Mailchimp deprecates endpoints. Check the bundle’s src/ for hardcoded paths and update them:
// Example: Replace deprecated endpoint
$client->setBaseUri('https://' . $dc . '.api.mailchimp
How can I help you explore Laravel packages today?