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

cubicmushroom/mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cubicmushroom/mailchimp-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        CubicMushroom\MailchimpBundle\CubicMushroomMailchimpBundle::class => ['all' => true],
    ];
    
  2. Configuration Add MailChimp API key and DC (datacenter) to .env:

    MAILCHIMP_API_KEY=your_api_key-us1
    MAILCHIMP_DC=us1
    

    Publish the default config (optional):

    php bin/console config:dump-reference CubicMushroom\MailchimpBundle\Resources\config\services.yaml
    
  3. First Use Case: Subscribe a User

    use CubicMushroom\MailchimpBundle\Service\MailchimpService;
    
    class UserController extends AbstractController
    {
        public function subscribe(User $user): Response
        {
            $mailchimp = $this->get('mailchimp.service');
            $mailchimp->subscribe($user->email, 'your_list_id');
    
            return $this->json(['status' => 'subscribed']);
        }
    }
    

Implementation Patterns

Common Workflows

  1. List Management

    • Fetch lists:
      $lists = $mailchimp->getLists();
      
    • Create/update a list:
      $mailchimp->createList('Newsletter', 'newsletter@example.com');
      
  2. Campaigns

    • Trigger an email campaign:
      $mailchimp->sendCampaign($campaignId, ['email' => $user->email]);
      
    • Schedule a campaign:
      $mailchimp->scheduleCampaign($campaignId, '2024-12-31T12:00:00');
      
  3. Segmentation

    • Add tags to subscribers:
      $mailchimp->addTagToSubscriber($listId, $subscriberHash, 'vip');
      
    • Filter subscribers by tag:
      $subscribers = $mailchimp->getSubscribersByTag($listId, 'vip');
      
  4. Webhooks

    • Register a webhook endpoint (Symfony route + service):
      // In a controller
      $payload = $this->getRequest()->getContent();
      $mailchimp->handleWebhook($payload);
      

Integration Tips

  • Dependency Injection: Inject MailchimpService directly into controllers/services.
  • Event Dispatching: Extend the bundle by dispatching events (e.g., SubscriberAddedEvent) after API calls.
  • Async Processing: Use Symfony Messenger to queue MailChimp API calls for background processing.
  • Testing: Mock MailchimpService in tests:
    $this->mock(MailchimpService::class)
         ->shouldReceive('subscribe')
         ->once()
         ->with($user->email, 'list_id');
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • MailChimp enforces rate limits. Cache responses aggressively:
      $cache = $this->container->get('cache.app');
      $lists = $cache->get('mailchimp_lists', function() use ($mailchimp) {
          return $mailchimp->getLists();
      });
      
  2. Subscriber Hashes

    • Subscriber hashes (MD5 of email + API key) are not portable across environments. Store them in your DB if needed.
  3. Webhook Verification

    • Always verify webhook signatures:
      $isValid = $mailchimp->verifyWebhook($payload, $this->getRequest()->headers->get('X-Mailchimp-Signature'));
      
  4. DC-Specific Endpoints

    • The bundle abstracts DC routing, but ensure your .env MAILCHIMP_DC matches your MailChimp account’s DC.

Debugging

  • Enable Debug Mode: Set debug: true in config to log API responses.
  • Raw API Calls: Access the underlying Guzzle client for debugging:
    $client = $mailchimp->getClient();
    $response = $client->request('GET', '/lists');
    

Extension Points

  1. Custom API Endpoints Override the service definition to add custom methods:

    # config/services.yaml
    CubicMushroom\MailchimpBundle\Service\MailchimpService:
        arguments:
            $client: '@mailchimp.http_client'
            $customMethods: ['customMethod' => ['GET', '/custom-endpoint']]
    
  2. Event Listeners Extend the bundle by listening to events (e.g., mailchimp.subscriber.added):

    // src/EventListener/MailchimpSubscriberListener.php
    public function onSubscriberAdded(SubscriberAddedEvent $event)
    {
        // Log or trigger side effects
    }
    
  3. Custom Response Transformers Override the default response handling:

    $mailchimp->setResponseTransformer(function($response) {
        return json_decode($response->getBody(), true);
    });
    

Config Quirks

  • Default List ID: The bundle does not enforce a default list ID. Define it in config or pass it explicitly.
  • Async API Calls: The bundle does not support async calls by default. Use Symfony Messenger or a queue system for long-running tasks.
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