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

coderbyheart/mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require coderbyheart/mailchimp-bundle
    
  2. Enable Bundle in config/bundles.php (Laravel 5.4+):
    Coderbyheart\MailChimpBundle\CoderbyheartMailChimpBundle::class => true,
    
  3. Configure in .env (or config/services.php for Laravel):
    MAILCHIMP_API_KEY=123-us1
    MAILCHIMP_RETURN_TYPE=object  # or 'array'
    
  4. First Use Case: Inject the service and fetch lists:
    use Coderbyheart\MailChimpBundle\MailChimp;
    
    public function __construct(MailChimp $mailchimp) {
        $this->mailchimp = $mailchimp;
    }
    
    public function getLists() {
        return $this->mailchimp->listsList();
    }
    

Implementation Patterns

Core Workflows

  1. List Management:

    // Create a list
    $list = $this->mailchimp->listsCreate([
        'name' => 'Newsletter Subscribers',
        'contact' => ['company' => 'Acme Corp']
    ]);
    
    // Add a subscriber
    $this->mailchimp->listsSubscribe('list-id', [
        'email_address' => 'user@example.com',
        'merge_fields' => ['FNAME' => 'John']
    ]);
    
  2. Campaigns:

    // Create a campaign
    $campaign = $this->mailchimp->campaignsCreate([
        'type' => 'regular',
        'settings' => ['subject_line' => 'Hello!']
    ]);
    
    // Send a campaign
    $this->mailchimp->campaignsSend($campaign['id']);
    
  3. Batch Operations:

    // Sync users from DB to MailChimp
    foreach ($users as $user) {
        $this->mailchimp->listsUpsert('list-id', [
            'email_address' => $user->email,
            'merge_fields' => $user->toMailchimpMergeFields()
        ]);
    }
    

Integration Tips

  • Event Listeners: Trigger MailChimp actions on user events (e.g., registration):
    // app/Listeners/UserRegistered.php
    public function handle(UserRegistered $event) {
        $this->mailchimp->listsSubscribe('newsletter', [
            'email_address' => $event->user->email,
            'merge_fields' => ['FNAME' => $event->user->name]
        ]);
    }
    
  • Commands: Schedule syncs via Artisan:
    // app/Console/Commands/SyncMailchimp.php
    public function handle() {
        $this->mailchimp->listsSync('list-id', $this->getUsers());
    }
    
  • API Rate Limiting: Handle 429 Too Many Requests by implementing retry logic:
    try {
        $response = $this->mailchimp->listsList();
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        if ($e->getCode() === 429) {
            sleep(30); // Wait 30 seconds
            return $this->mailchimp->listsList();
        }
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated API:

    • The bundle uses MailChimp API 2.0, which is outdated. Some endpoints (e.g., listsUpsert) may behave differently than expected. Prefer listsBatchSubscribe or listsBatchUpsert for bulk operations.
    • Workaround: Use raw API calls via Guzzle for unsupported endpoints:
      $client = $this->mailchimp->getClient();
      $response = $client->post('lists/{list-id}/members', [
          'json' => ['email_address' => 'test@example.com']
      ]);
      
  2. Authentication:

    • API keys are not encrypted by default. Store them securely in .env and restrict file permissions.
    • Tip: Rotate keys periodically via MailChimp’s dashboard.
  3. Response Handling:

    • The return_type config (object/array) applies globally. Override per-call if needed:
      $this->mailchimp->setReturnType('array');
      $lists = $this->mailchimp->listsList();
      
  4. Idempotency:

    • listsSubscribe may fail if the email already exists. Use listsUpsert or check first:
      $members = $this->mailchimp->listsMembersList('list-id', ['email_address' => 'test@example.com']);
      if (empty($members)) {
          $this->mailchimp->listsSubscribe('list-id', [...]);
      }
      

Debugging

  • Enable Guzzle Middleware for request/response logging:
    $this->mailchimp->getClient()->getConfig()->set('debug', true);
    
  • Validate API Key: Test connectivity early:
    try {
        $this->mailchimp->ping();
    } catch (\Exception $e) {
        throw new \RuntimeException('MailChimp API key invalid or server unreachable.');
    }
    

Extension Points

  1. Custom Endpoints:
    • Extend the service to wrap unsupported endpoints:
      // app/Services/ExtendedMailChimp.php
      public function listsBatchUpsert($listId, array $members) {
          $client = $this->mailchimp->getClient();
          return $client->post("lists/{$listId}/members", [
              'json' => ['members' => $members]
          ]);
      }
      
  2. Event Dispatching:
    • Hook into MailChimp webhooks (e.g., subscribe, unsubscribe) via Laravel events:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'mailchimp.subscribed' => [MailchimpSubscriberHandler::class, 'handle'],
      ];
      
  3. Testing:
    • Mock the service in tests:
      $mailchimp = Mockery::mock(MailChimp::class);
      $mailchimp->shouldReceive('listsSubscribe')->once();
      $this->app->instance(MailChimp::class, $mailchimp);
      
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