beelab/v3-mailchimp-api-php
Lightweight PHP wrapper for MailChimp API v3. Provides convenient functions on top of the REST endpoints using Guzzle, installable via Composer. Includes a PHPUnit test suite. Requires PHP 5.5+.
Install via Composer
composer require beelab/v3-mailchimp-api-php
Configure API Key
Add your MailChimp API key (found in Account → Extras → API Keys) to Laravel's .env:
MAILCHIMP_API_KEY=your_dc_usX_api_key_here
MAILCHIMP_SERVER=usX # Replace with your server (e.g., us1, eu1)
Initialize the Client
In a service provider (e.g., AppServiceProvider):
use BeeLab\Mailchimp\Mailchimp;
public function register()
{
$mailchimp = new Mailchimp(config('mailchimp.api_key'), config('mailchimp.server'));
$this->app->singleton('mailchimp', function () use ($mailchimp) {
return $mailchimp;
});
}
First Use Case: List Campaigns
$campaigns = app('mailchimp')->call('campaigns', 'get');
dd($campaigns);
CRUD Operations
Use the call() method with the endpoint and HTTP method:
// Create a subscriber
$subscriber = app('mailchimp')->call('lists/{list_id}/members', 'post', [
'email_address' => 'user@example.com',
'status' => 'subscribed',
]);
// Update a subscriber
$subscriber = app('mailchimp')->call(
'lists/{list_id}/members/{subscriber_hash}',
'patch',
['status' => 'unsubscribed']
);
Pagination Handle paginated responses (e.g., listing subscribers):
$subscribers = [];
$offset = 0;
$batch = app('mailchimp')->call('lists/{list_id}/members', 'get', [
'offset' => $offset,
'count' => 100,
]);
while (!empty($batch)) {
$subscribers = array_merge($subscribers, $batch['members']);
$offset += 100;
$batch = app('mailchimp')->call('lists/{list_id}/members', 'get', [
'offset' => $offset,
'count' => 100,
]);
}
Webhooks
Validate incoming webhooks using the verifyWebhook method:
$isValid = app('mailchimp')->verifyWebhook(
request()->header('X-Mailchimp-Signature'),
request()->getContent(),
config('mailchimp.webhook_secret')
);
Batch Operations
Use the batch() method for bulk actions (e.g., deleting subscribers):
$batch = app('mailchimp')->batch();
$batch->add('lists/{list_id}/members/{hash1}', 'delete');
$batch->add('lists/{list_id}/members/{hash2}', 'delete');
$batch->execute();
Subscribed, Unsubscribed) after API calls.try-catch to log errors:
try {
$response = app('mailchimp')->call('endpoint', 'method', $data);
} catch (\Exception $e) {
\Log::error("Mailchimp API Error: " . $e->getMessage());
}
API Key Format
Ensure the API key includes the DC (data center) prefix (e.g., usX_abc123). Without it, requests will fail with 401 Unauthorized.
Rate Limits Mailchimp enforces rate limits. Cache responses or implement exponential backoff:
if ($response->getStatusCode() === 429) {
sleep(1); // Retry after 1 second
}
Webhook Signatures Webhook secrets must match exactly (case-sensitive). Regenerate secrets in Mailchimp’s Account → Extras → Settings → Webhooks.
Deprecated Endpoints
Some v2 endpoints (e.g., /lists/subscribe) are not supported. Use v3 equivalents (e.g., /lists/{list_id}/members).
Enable Guzzle Debugging
Add this to your AppServiceProvider to log raw API requests/responses:
$mailchimp->getClient()->getEmitter()->attach(
new \GuzzleHttp\Middleware::tap(function ($request, $next) {
\Log::debug('Mailchimp Request:', [
'url' => (string) $request->getUri(),
'method' => $request->getMethod(),
'body' => $request->getBody(),
]);
return $next($request);
})
);
Validate Responses
Check for Mailchimp-specific errors in the errors array:
if (isset($response['errors'])) {
throw new \Exception($response['errors'][0]['message']);
}
Custom Endpoints
Extend the Mailchimp class to add private methods for frequently used endpoints:
class ExtendedMailchimp extends \BeeLab\Mailchimp\Mailchimp {
public function getListMembers($listId, $status = 'subscribed') {
return $this->call("lists/{$listId}/members", 'get', [
'status' => $status,
]);
}
}
Middleware Add middleware to the Guzzle client for authentication or logging:
$mailchimp->getClient()->getMiddleware()->prepend(
new \GuzzleHttp\Middleware::mapRequest(function ($request) {
$request->getHeaders()->add('Authorization', 'Basic ' . base64_encode(config('mailchimp.api_key')));
return $request;
})
);
Testing
Mock the client in tests using Laravel’s Mockery:
$mock = Mockery::mock('BeeLab\Mailchimp\Mailchimp');
$mock->shouldReceive('call')
->with('lists/123/members', 'get')
->andReturn(['members' => []]);
$this->app->instance('mailchimp', $mock);
How can I help you explore Laravel packages today?