Install via Composer:
composer require wunderdata/mailchimp-bundle
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.
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);
}
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']
);
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
Dependency Injection: Prefer injecting the client via constructor (Symfony best practice):
public function __construct(private Client $mailchimpClient) {}
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());
}
Environment Variables:
Store apikey in .env and reference it in config:
wunderdata_mailchimp:
apikey: "%env(MAILCHIMP_API_KEY)%"
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++;
}
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'],
]);
Testing:
Mock the client in tests using Symfony’s ContainerInterface:
$container->set('wunderdata_mailchimp.client', $mockClient);
API Key Format:
The API key must include the datacenter suffix (e.g., abc123-us1). Omitting this will cause 401 Unauthorized errors.
Deprecated Methods: The bundle uses Mailchimp’s v2.0 API, which is deprecated. Plan to migrate to v3.0 soon.
Export API Limitations:
ExportClient) is not officially supported by Mailchimp. Use at your own risk.Debugging:
Enable debug: true in config to log raw API requests/responses to var/log/dev.log.
CORS/CSRF: If using webhooks, ensure your endpoint:
X-Mailchimp-Signature header.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']],
],
]);
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));
Configuration Overrides:
Override bundle config per environment (e.g., config/packages/dev/wunderdata_mailchimp.yaml):
wunderdata_mailchimp:
opts:
debug: true
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',
]);
}
}
}
Logging: Log critical API calls for auditing:
$this->logger->info('Mailchimp API call', [
'endpoint' => 'lists/' . $listId . '/members',
'method' => 'post',
'data' => $subscriberData,
]);
How can I help you explore Laravel packages today?