Install via Composer
composer require ekyna/mailchimp-bundle
(Note: Since the README mentions "TODO" for installation, verify compatibility with your Laravel version—likely requires Symfony components or a bridge layer. Check composer.json for dependencies like guzzlehttp/guzzle or symfony/http-client.)
Publish Configuration
php artisan vendor:publish --provider="Ekyna\MailchimpBundle\MailchimpBundle" --tag="config"
(Edit config/mailchimp.php with your Mailchimp API key and default list/subscriber settings.)
First Use Case: Subscribe a User
use Ekyna\MailchimpBundle\MailchimpManager;
$mailchimp = app(MailchimpManager::class);
$mailchimp->subscribe('user@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe']);
(Assumes the bundle follows Laravel’s service container conventions. Verify the MailchimpManager class exists in src/Ekyna/MailchimpBundle/.)
Subscriber Management
$mailchimp->subscribe('email@example.com', ['MERGE_FIELDS' => ['EMAIL' => ['email@example.com']]]);
$mailchimp->unsubscribe('email@example.com');
$mailchimp->batchSubscribe([
'email1@example.com' => ['FNAME' => 'Alice'],
'email2@example.com' => ['FNAME' => 'Bob'],
]);
List Integration
$lists = $mailchimp->getLists();
$mailchimp->createList('My Newsletter', 'newsletter@example.com');
Campaigns
$mailchimp->sendCampaign($campaignId, ['subject' => 'Hello!']);
$campaigns = $mailchimp->getCampaigns();
Event Webhooks
$mailchimp->onSubscribe(function ($data) {
Log::info('New subscriber:', $data);
});
Laravel Service Provider:
Bind the manager to the container in AppServiceProvider:
$this->app->bind(MailchimpManager::class, function ($app) {
return new \Ekyna\MailchimpBundle\MailchimpManager($app['config']['mailchimp.api_key']);
});
Form Requests:
Use Laravel’s FormRequest to validate emails before subscribing:
public function rules() {
return ['email' => 'required|email'];
}
Queue Delayed Tasks:
Offload Mailchimp calls to queues (e.g., subscribeAfterRegistration job):
SubscribeAfterRegistration::dispatch($user->email, $user->name)->delay(now()->addMinutes(5));
API Key Security
.env. Use Laravel’s env() or a dedicated secrets manager.lists, subscribers).Rate Limits
throttle middleware or implement exponential backoff:
try {
$mailchimp->subscribe(...);
} catch (RateLimitException $e) {
sleep($e->getRetryAfter());
retry();
}
Merge Fields
FNAME) are case-sensitive. Validate against your Mailchimp list’s defined fields.EMAIL):
$mailchimp->subscribe('email@example.com', [
'MERGE_FIELDS' => [
'EMAIL' => ['email@example.com'],
'FNAME' => ['John'], // Optional
]
]);
Error Handling
title, detail, and status keys. Normalize errors:
try {
$mailchimp->subscribe(...);
} catch (\Exception $e) {
$error = json_decode($e->getMessage(), true);
Log::error("Mailchimp error: {$error['title']} - {$error['detail']}");
}
Testing
Mockery or PHPUnit to stub Mailchimp calls:
$mock = Mockery::mock(MailchimpManager::class);
$mock->shouldReceive('subscribe')->once();
$this->app->instance(MailchimpManager::class, $mock);
Custom Merge Fields
Extend the bundle by adding a MergeField trait or service:
class CustomMailchimpManager extends MailchimpManager {
public function addCustomField($email, $fieldName, $value) {
$this->callApi('patch', "/lists/{listId}/members/{$email}", [
'merge_fields' => [$fieldName => $value],
]);
}
}
Event Dispatching
Trigger Laravel events (e.g., Subscribed) after Mailchimp operations:
$mailchimp->subscribe($email, $data);
event(new Subscribed($email, $data));
Webhook Validation
If using webhooks, validate signatures with Mailchimp’s webhook-signature header:
$signature = hash_hmac('sha256', $payload, env('MAILCHIMP_WEBHOOK_SECRET'));
if (!hash_equals($request->header('webhook-signature'), $signature)) {
abort(403);
}
Fallback for Offline
Cache failed operations (e.g., using database or redis) and retry later:
$mailchimp->withRetry()->subscribe($email, $data);
Enable Guzzle Debugging:
Add to config/mailchimp.php:
'debug' => env('MAILCHIMP_DEBUG', false),
(If the bundle uses Guzzle, this may log requests/responses to storage/logs/mailchimp.log.)
API Explorer: Test endpoints manually via Mailchimp’s API Explorer to verify payloads.
Check HTTP Status Codes:
200: Success.400: Invalid payload (validate merge fields).401: API key invalid.404: Resource not found (e.g., list ID).How can I help you explore Laravel packages today?