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

cors/mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require welp/mailchimp-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Welp\MailchimpBundle\WelpMailchimpBundle::class => ['all' => true],
    ];
    
  2. Configure .env Add MailChimp API credentials:

    MAILCHIMP_API_KEY=your_api_key_here
    MAILCHIMP_SERVER=us12  # or your region
    MAILCHIMP_LIST_ID=your_list_id
    
  3. Basic Usage Inject the MailchimpClient service in a controller or service:

    use Welp\MailchimpBundle\Service\MailchimpClient;
    
    public function __construct(private MailchimpClient $mailchimp) {}
    
    public function syncSubscriber(User $user) {
        $this->mailchimp->syncSubscriber($user);
    }
    
  4. First Use Case Sync a user on registration (assuming FosUserBundle):

    // src/EventListener/UserRegistrationListener.php
    use Welp\MailchimpBundle\EventListener\MailchimpSyncListener;
    
    public function onUserRegistered(UserEvent $event) {
        $this->mailchimp->syncSubscriber($event->getUser());
    }
    

Implementation Patterns

Core Workflows

1. Subscriber Synchronization

  • Default Provider: Use the built-in FosSubscriberProvider for FosUserBundle:
    # config/packages/welp_mailchimp.yaml
    welp_mailchimp:
        user_provider: welp_mailchimp.user_provider.fos_subscriber
    
  • Custom Provider: Implement Welp\MailchimpBundle\Provider\UserProviderInterface:
    class CustomUserProvider implements UserProviderInterface {
        public function getSubscriberData(User $user): array {
            return [
                'email' => $user->email,
                'merge_fields' => [
                    'FNAME' => $user->firstName,
                    'LNAME' => $user->lastName,
                ],
            ];
        }
    }
    
    Register in services:
    services:
        welp_mailchimp.user_provider.custom:
            class: App\Service\CustomUserProvider
            tags: ['welp_mailchimp.user_provider']
    

2. List Management

  • Doctrine List Provider: Fetch lists from a database entity:
    // src/Entity/NewsletterList.php
    #[ORM\Entity]
    class NewsletterList {
        #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column]
        private ?int $id = null;
    
        #[ORM\Column]
        private string $mailchimpListId;
    }
    
    Configure in welp_mailchimp.yaml:
    welp_mailchimp:
        list_provider: welp_mailchimp.list_provider.doctrine
    

3. Lifecycle Events

  • Trigger syncs via Symfony events:
    // src/EventSubscriber/MailchimpSubscriber.php
    use Welp\MailchimpBundle\Event\MailchimpSyncEvent;
    
    public static function getSubscribedEvents(): array {
        return [
            UserEvents::REGISTERED => 'onUserRegistered',
            UserEvents::UPDATED => 'onUserUpdated',
        ];
    }
    
    public function onUserRegistered(UserEvent $event) {
        $this->mailchimp->syncSubscriber($event->getUser());
    }
    

4. Merge Fields

  • Define merge fields in config:
    welp_mailchimp:
        merge_fields:
            FNAME: first_name
            LNAME: last_name
            CUSTOM_FIELD: custom_attribute
    
  • Access via getMergeFields() in custom providers.

5. Webhooks

  • Register a webhook endpoint:
    welp_mailchimp:
        webhooks:
            - url: /mailchimp/webhook
              events: ['subscribe', 'unsubscribe', 'cleaned']
    
  • Handle webhooks in a controller:
    public function handleWebhook(Request $request, MailchimpClient $mailchimp) {
        $payload = json_decode($request->getContent(), true);
        $mailchimp->processWebhook($payload);
    }
    

6. Raw API Access

  • Use the underlying Mailchimp client for custom requests:
    $lists = $this->mailchimp->getClient()->lists->getAllLists();
    

Integration Tips

Laravel-Specific Adaptations

  1. Service Container Bind the bundle’s services to Laravel’s container in config/services.php:

    'mailchimp' => \Welp\MailchimpBundle\Service\MailchimpClient::class,
    
  2. Event Dispatcher Use Laravel’s event system alongside Symfony events:

    use Illuminate\Support\Facades\Event;
    
    Event::listen(UserRegistered::class, function ($user) {
        app('mailchimp')->syncSubscriber($user);
    });
    
  3. Configuration Merge bundle config with Laravel’s .env:

    // config/mailchimp.php
    return [
        'api_key' => env('MAILCHIMP_API_KEY'),
        'server' => env('MAILCHIMP_SERVER'),
        'list_id' => env('MAILCHIMP_LIST_ID'),
        'merge_fields' => [
            'FNAME' => 'first_name',
            // ...
        ],
    ];
    
  4. Middleware for Webhooks Protect webhook endpoints with Laravel middleware:

    Route::post('/mailchimp/webhook', [MailchimpController::class, 'handleWebhook'])
        ->middleware('signed'); // Laravel's signed middleware
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • MailChimp enforces rate limits. Cache API responses aggressively:
      $this->mailchimp->getClient()->setCache(new FilesystemCache('/tmp/mailchimp'));
      
  2. Merge Field Conflicts

    • Ensure merge field keys in config match MailChimp’s valid tags. Use uppercase for standard fields (e.g., FNAME).
  3. Webhook Verification

    • Always verify webhook signatures. Use the MailchimpWebhookVerifier service:
      if (!$this->mailchimp->verifyWebhook($request)) {
          abort(403, 'Invalid webhook signature');
      }
      
  4. User Provider Mismatch

    • If using a custom UserProvider, ensure getSubscriberData() returns an array with:
      • email (required)
      • merge_fields (optional but recommended)
      • status (e.g., 'subscribed', 'unsubscribed').
  5. List ID Mismatch

    • Double-check MAILCHIMP_LIST_ID in .env. Syncs will fail silently if the ID is incorrect.
  6. Doctrine List Provider Caching

    • If using DoctrineListProvider, cache the list ID to avoid repeated DB queries:
      $listId = $this->mailchimp->getListProvider()->getListId();
      $this->mailchimp->getClient()->lists->getList($listId);
      

Debugging

  1. Enable API Logging Configure the Mailchimp client to log requests:

    $client = $this->mailchimp->getClient();
    $client->setLogger(new MonologLogger([
        new StreamHandler(__DIR__.'/../logs/mailchimp.log', Monolog\Logger::DEBUG),
    ]));
    
  2. Test Webhooks Locally Use ngrok to expose a local endpoint for testing webhooks:

    ngrok http 8000
    

    Configure the webhook URL in MailChimp to point to your ngrok endpoint.

  3. Validate Subscriber Data Use the validateSubscriberData() method to check data before syncing:

    if (!$this->mailchimp->validateSubscriberData($user)) {
        throw new \RuntimeException('Invalid subscriber data');
    }
    

Extension Points

  1. Custom Sync Logic Extend the MailchimpClient to add custom sync logic:
    class CustomMailchimpClient extends MailchimpClient {
        public function syncWithCustomLogic(User $user) {
            $data = $this->getUserProvider()->getSubscriberData($user);
            // Add custom logic (e.g., tagging)
            $data['tags'] = ['vip'];
            $this->getClient()->lists->addOrUpdateMember(
                $this->getListId(),
                $
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity