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

Hype Mailchimp Bundle Laravel Package

ahmedsamy/hype-mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ahmedsamy/hype-mailchimp-bundle:dev-master
    

    Add to config/bundles.php (Symfony 4+):

    Hype\MailchimpBundle\HypeMailchimpBundle::class => ['all' => true],
    
  2. Configure (config/packages/hype_mailchimp.yaml):

    hype_mailchimp:
        api_key: "YOUR_API_KEY-usX"  # Replace with your Mailchimp API key
        default_list: "YOUR_LIST_ID"  # Default list ID for operations
        ssl: true                    # Enable SSL for secure connections
    
  3. First Use Case: Subscribe a user to the default list:

    $mailchimp = $this->get('hype_mailchimp');
    $response = $mailchimp->getList()->subscribe('user@example.com');
    

Implementation Patterns

Core Workflows

  1. Campaign Management:

    • Create a campaign:
      $mailchimp->getCampaign()->create('regular', [
          'list_id' => 'LIST_ID',
          'subject' => 'Welcome',
          'from_email' => 'noreply@example.com',
      ], [
          'html' => '<h1>Hello!</h1>',
          'text' => 'Plain text content',
      ]);
      
    • Send a campaign:
      $mailchimp->getCampaign()
          ->setCi('CAMPAIGN_ID')
          ->send();
      
  2. List Operations:

    • Subscribe/Unsubscribe:
      $mailchimp->getList()
          ->setListId('LIST_ID')
          ->addMergeVars(['FNAME' => 'John'])
          ->subscribe('john@example.com');
      
      $mailchimp->getList()
          ->setListId('LIST_ID')
          ->unsubscribe('john@example.com');
      
    • Batch operations (e.g., segment testing):
      $mailchimp->getList()
          ->setListId('LIST_ID')
          ->segmentTest(['segment_id' => 'SEG_ID']);
      
  3. Templates:

    • Add/Delete templates:
      $mailchimp->getTemplate()
          ->add('template_name', '<html>...</html>');
      
      $mailchimp->getTemplate()
          ->setTemplateId('TEMPLATE_ID')
          ->del();
      
  4. Export Data:

    • Fetch subscriber activity:
      $mailchimp->getExport()
          ->campaignSubscriberActivity('CAMPAIGN_ID');
      

Integration Tips

  • Service Injection: Use dependency injection for cleaner code:
    public function __construct(HypeMailchimp $mailchimp) {
        $this->mailchimp = $mailchimp;
    }
    
  • Error Handling: Wrap calls in try-catch blocks to handle Mailchimp API errors:
    try {
        $response = $mailchimp->getCampaign()->send();
    } catch (\Exception $e) {
        // Log or handle error (e.g., retry logic)
    }
    
  • Chaining Methods: Leverage method chaining for fluent operations:
    $mailchimp->getList()
        ->setListId('LIST_ID')
        ->addMergeVars(['CUSTOM_FIELD' => 'value'])
        ->subscribe('email@example.com');
    

Gotchas and Tips

Pitfalls

  1. API Key Format:

    • Ensure the API key includes the -usX suffix (e.g., abc123-us5). Missing this causes authentication failures.
    • Fix: Verify the key in Mailchimp’s API settings (under "Extras > API Keys").
  2. List ID Scope:

    • Operations default to default_list in config. Override per-call with setListId() to avoid confusion:
      $mailchimp->getList()->setListId('NEW_LIST_ID')->subscribe('email@example.com');
      
  3. Campaign IDs:

    • setCi() requires the Mailchimp campaign ID (not Laravel’s auto-increment ID). Retrieve it via:
      $campaigns = $mailchimp->getCampaign()->list();
      $ci = $campaigns['data'][0]['id'];
      
  4. SSL Requirements:

    • If ssl: false in config, the bundle uses HTTP (insecure). Always set ssl: true in production.
  5. Rate Limiting:

    • Mailchimp enforces rate limits. Cache responses for frequent calls (e.g., list subscriptions).

Debugging

  • Enable Debug Mode: Add to config to log raw API responses:

    hype_mailchimp:
        debug: true
    

    Check logs in var/log/dev.log for raw responses/errors.

  • Common Errors:

    • 401 Unauthorized: Invalid API key or missing -usX suffix.
    • 404 Not Found: Incorrect list_id or campaign_id.
    • 400 Bad Request: Invalid payload (e.g., malformed HTML in templates).

Extension Points

  1. Custom Endpoints: The bundle uses Buzz HTTP client under the hood. Extend by creating a custom service:

    // src/Service/CustomMailchimp.php
    class CustomMailchimp extends \Hype\MailchimpBundle\Service\Mailchimp
    {
        public function customEndpoint($method, $params)
        {
            return $this->callApi('custom/endpoint', $method, $params);
        }
    }
    

    Register as a service in services.yaml:

    services:
        App\Service\CustomMailchimp:
            arguments: ['@hype_mailchimp']
    
  2. Event Listeners: Hook into Mailchimp events (e.g., campaign sent) using Symfony’s event system. Example:

    // src/EventListener/MailchimpListener.php
    class MailchimpListener
    {
        public function onCampaignSent($event)
        {
            // Logic after campaign is sent
        }
    }
    

    Bind to the hype.mailchimp.campaign.sent event in services.yaml.

  3. Testing: Use a sandbox API key (from Mailchimp’s API settings) for testing. Mock the service in PHPUnit:

    $this->mailchimp = $this->createMock(HypeMailchimp::class);
    $this->mailchimp->method('getCampaign')->willReturnSelf();
    $this->mailchimp->expects($this->once())
        ->method('create')
        ->willReturn(['id' => 'test_campaign']);
    

Configuration Quirks

  • Default List: If default_list is omitted, the bundle throws an exception. Always specify it in config.

  • Merge Vars: Use Mailchimp’s merge field syntax (e.g., FNAME, LNAME). Custom fields require prefixing with CUSTOM_ (e.g., CUSTOM_field_name).

  • Template Limits: Free Mailchimp accounts have template limits. Handle 429 Too Many Requests gracefully.

Performance Tips

  • Batch Subscriptions: Use Mailchimp’s batch operations for bulk imports:
    $mailchimp->getList()
        ->setListId('LIST_ID')
        ->batchSubscribe([
            ['email' => 'user1@example.com', 'merge_vars' => ['FNAME' => 'User1']],
            ['email' => 'user2@example.com', 'merge_vars' => ['FNAME' => 'User2']],
        ]);
    
  • Async Processing: Offload long-running tasks (e.g., exports) to queues (e.g., Symfony Messenger or Laravel Queues) to avoid timeouts.
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle