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

dx-solutions/mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require welp/mailchimp-bundle
    

    Enable the bundle in config/bundles.php:

    Welp\MailchimpBundle\WelpMailchimpBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference WelpMailchimpBundle
    

    Update config/packages/welp_mailchimp.yaml with your MailChimp API key and list ID:

    welp_mailchimp:
        api_key: 'your_api_key-us12'  # Format: key-usXX
        list_id: 'your_list_id'
        merge_fields: ['FNAME', 'LNAME', 'EMAIL']  # Optional
    
  3. First Use Case: Sync a User Use the MailchimpSubscriberManager service to sync a user:

    use Welp\MailchimpBundle\Manager\MailchimpSubscriberManager;
    
    public function subscribeUser(User $user)
    {
        $manager = $this->container->get(MailchimpSubscriberManager::class);
        $manager->subscribe($user);
    }
    

Implementation Patterns

Core Workflows

  1. Subscriber Synchronization

    • Default Provider: Use FosSubscriberProvider (if using FOSUserBundle) or implement a custom UserProvider:
      class CustomUserProvider implements UserProviderInterface
      {
          public function getEmail(User $user): string { ... }
          public function getMergeFields(User $user): array { ... }
      }
      
    • Register the provider in config/packages/welp_mailchimp.yaml:
      welp_mailchimp:
          user_provider: 'App\Service\CustomUserProvider'
      
  2. List Management

    • Fetch lists dynamically with DoctrineListProvider (requires Doctrine):
      welp_mailchimp:
          list_provider: 'Welp\MailchimpBundle\Provider\DoctrineListProvider'
      
    • Or hardcode the list ID in config (as shown above).
  3. Lifecycle Events

    • Trigger syncs via Doctrine events (e.g., postPersist, postUpdate):
      // In a Doctrine listener
      $manager->subscribe($user); // On user creation/update
      $manager->unsubscribe($user); // On user deletion
      
  4. Merge Fields

    • Sync custom fields (e.g., FNAME, LNAME) from your user model:
      welp_mailchimp:
          merge_fields:
              FNAME: 'first_name'  # Maps to user property
              LNAME: 'last_name'
      
  5. Webhooks

    • Register a webhook endpoint in config/routes.yaml:
      welp_mailchimp_webhook:
          path: /mailchimp/webhook
          controller: Welp\MailchimpBundle\Controller\WebhookController::handle
      
    • Verify webhook signatures in WebhookController:
      public function handle(Request $request): Response
      {
          $this->mailchimpWebhook->verify($request);
          // Process webhook data...
      }
      

Integration Tips

  • Laravel-Specific Adaptation Replace Symfony’s UserProvider with Laravel’s User model:

    class LaravelUserProvider implements UserProviderInterface
    {
        public function getEmail(User $user): string
        {
            return $user->email;
        }
    
        public function getMergeFields(User $user): array
        {
            return [
                'FNAME' => $user->first_name,
                'LNAME' => $user->last_name,
            ];
        }
    }
    
  • Service Container Binding Bind the MailchimpSubscriberManager in Laravel’s AppServiceProvider:

    public function register()
    {
        $this->app->bind(MailchimpSubscriberManager::class, function ($app) {
            return new MailchimpSubscriberManager(
                $app->make(MailchimpApi::class),
                $app->make(UserProviderInterface::class),
                $app->make(ListProviderInterface::class)
            );
        });
    }
    
  • Batch Processing Use Laravel’s chunk() for large subscriber lists:

    User::chunk(100, function ($users) {
        foreach ($users as $user) {
            $manager->subscribe($user);
        }
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Format

    • Error: Invalid API Key or 401 Unauthorized.
    • Fix: Ensure the key follows key-usXX format (e.g., abc123-us12). Check MailChimp’s datacenter.
  2. Merge Field Mismatches

    • Error: Merge fields not syncing or throwing 400 Bad Request.
    • Fix: Verify field names match MailChimp’s list settings exactly (case-sensitive). Use the MailchimpApi service to fetch list fields:
      $list = $mailchimpApi->get('lists/' . config('welp_mailchimp.list_id'));
      dd($list['merge_fields']); // Debug available fields
      
  3. Webhook Verification

    • Error: Webhook requests failing with 403 Forbidden.
    • Fix: Ensure the webhook_signature header matches MailChimp’s signature. Use the MailchimpWebhook service:
      $this->mailchimpWebhook->verify($request, config('welp_mailchimp.webhook_secret'));
      
  4. Duplicate Subscribers

    • Error: Member exists errors during sync.
    • Fix: Use upsert (update if exists, insert if not) via the MailchimpSubscriberManager:
      $manager->upsert($user); // Instead of $manager->subscribe()
      
  5. Rate Limits

    • Error: 429 Too Many Requests.
    • Fix: Implement retries with exponential backoff or use MailChimp’s batch endpoints.

Debugging Tips

  1. Enable API Debugging Add this to config/packages/welp_mailchimp.yaml:

    welp_mailchimp:
        debug: true
    

    Logs will appear in var/log/dev.log (Symfony) or Laravel’s storage/logs.

  2. Test API Connection Use the MailchimpApi service directly:

    $api = $this->container->get(MailchimpApi::class);
    dd($api->get('lists')); // Test connection
    
  3. Symfony vs. Laravel Quirks

    • Service Container: Laravel’s app() or resolve() may need adjustments for Symfony services.
    • Events: Replace Symfony’s EventDispatcher with Laravel’s Events facade if using lifecycle hooks.

Extension Points

  1. Custom API Requests Extend the MailchimpApi service to add custom endpoints:

    $api->post('lists/' . $listId . '/members', [
        'email_address' => $email,
        'status' => 'subscribed',
        'merge_fields' => $mergeFields,
    ]);
    
  2. Custom List Provider Implement ListProviderInterface for dynamic list selection:

    class DynamicListProvider implements ListProviderInterface
    {
        public function getListId(): string
        {
            return request()->input('list_id') ?? config('welp_mailchimp.list_id');
        }
    }
    
  3. Webhook Handlers Extend the WebhookController to handle specific events (e.g., subscribe, unsubscribe):

    public function handle(Request $request): Response
    {
        $this->mailchimpWebhook->verify($request);
        $event = $request->request->get('type');
    
        if ($event === 'subscribe') {
            $this->handleSubscribe($request);
        }
    
        return new Response('OK');
    }
    
  4. Async Processing Use Laravel’s queues to offload sync tasks:

    dispatch(new SyncMailchimpSubscriber($user));
    

    Implement the job:

    class SyncMailchimpSubscriber implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable;
    
        public function handle()
        {
            $manager->subscribe($this->user);
        }
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky