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 Api Laravel Package

drewm/mailchimp-api

PHP wrapper for the Mailchimp API. Subscribe/unsubscribe users, manage lists, campaigns, templates and reports with simple calls. Designed for quick integration in Laravel or any PHP app, with minimal setup and practical examples.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require drewm/mailchimp-api
    

    Add to composer.json if using a monorepo or custom package structure.

  2. First Use Case: Sending a Campaign

    use Drewm\MailChimp\MailChimp;
    
    $mailchimp = new MailChimp('your-dc-mailchimp-api-key', 'us12'); // Replace with your DC and API key
    $response = $mailchimp->campaigns->create([
        'type' => 'regular',
        'recipients' => ['list_id' => 'your-list-id'],
        'settings' => [
            'subject_line' => 'Hello, world!',
            'from_name' => 'Your Name',
            'reply_to' => 'reply@example.com',
            'template_id' => 12345,
        ],
    ]);
    
  3. Where to Look First


Implementation Patterns

Common Workflows

1. List Management

  • Fetching Lists:
    $lists = $mailchimp->lists->getAll();
    
  • Creating a Subscriber:
    $mailchimp->lists->subscribe('list-id', [
        'email_address' => 'user@example.com',
        'merge_fields' => ['FNAME' => 'John', 'LNAME' => 'Doe'],
    ]);
    

2. Campaigns

  • Sending a Campaign:
    $campaign = $mailchimp->campaigns->create([...]);
    $mailchimp->campaigns->send($campaign['id']);
    
  • Scheduling:
    $mailchimp->campaigns->schedule($campaign['id'], '2023-12-31T12:00:00');
    

3. Automations (Marketing Automation)

  • Triggering a Journey:
    $mailchimp->automations->trigger('journey-id', 'user@example.com');
    

4. Webhooks

  • Listening for Events:
    $webhook = $mailchimp->webhooks->create([
        'url' => 'https://your-app.com/webhook',
        'events' => ['subscribe', 'unsubscribe'],
    ]);
    

Integration Tips

  • Rate Limiting: The package respects MailChimp’s rate limits. Handle Drewm\MailChimp\Exceptions\RateLimitException gracefully.
  • Error Handling:
    try {
        $response = $mailchimp->lists->get('list-id');
    } catch (\Drewm\MailChimp\Exceptions\ApiException $e) {
        // Log or notify (e.g., Slack, Sentry)
        logger()->error($e->getMessage());
    }
    
  • Testing: Use the MailChimpTestCase from the tests folder as a template for unit/integration tests. Mock the API responses with Guzzle’s MockHandler.

Gotchas and Tips

Pitfalls

  1. API Key and DC Misconfiguration

    • Issue: Incorrect datacenter (e.g., us12 vs. eu1) or API key causes 401 Unauthorized errors.
    • Fix: Verify your MailChimp account’s DC and ensure the key is correct.
      $mailchimp = new MailChimp('us12_your-api-key', 'us12'); // Correct format
      
  2. Deprecated Endpoints

    • Issue: The package was last updated in 2018 and may not support newer MailChimp API v3 endpoints (e.g., transactional or ecommerce).
    • Fix: Check the MailChimp API changelog and extend the package if needed (see "Extension Points" below).
  3. Webhook Verification

    • Issue: MailChimp webhooks require verification. The package doesn’t handle this automatically.
    • Fix: Implement a verification endpoint in your app:
      Route::post('/mailchimp-webhook', function (Request $request) {
          $signature = $request->header('X-Mailchimp-Signature');
          $payload = $request->getContent();
          // Verify using MailChimp's webhook signature logic
          // https://developer.mailchimp.com/documentation/mailchimp/guides/webhook-signature-verification/
      });
      
  4. Merge Fields and Segmentation

    • Issue: Merge fields (e.g., FNAME, LNAME) must match MailChimp’s exact naming.
    • Fix: Use the MailChimp UI to confirm field names or fetch them via:
      $mergeFields = $mailchimp->lists->mergeFields('list-id');
      

Debugging Tips

  • Enable Guzzle Debugging:
    $mailchimp = new MailChimp('key', 'dc', [
        'debug' => true, // Logs requests/responses to `storage/logs/mailchimp.log`
    ]);
    
  • Inspect Raw Responses:
    $response = $mailchimp->lists->get('list-id');
    logger()->debug($response->getBody()->getContents());
    

Extension Points

  1. Custom Endpoints Add support for unsupported endpoints by extending the MailChimp class:

    class CustomMailChimp extends \Drewm\MailChimp\MailChimp {
        public function customEndpoint($method, $path, $data = []) {
            return $this->request($method, $path, $data);
        }
    }
    
  2. Middleware for Requests Override the request method to add headers or logging:

    $mailchimp->setClient(new \GuzzleHttp\Client([
        'headers' => [
            'User-Agent' => 'YourApp/1.0',
        ],
    ]));
    
  3. Batch Operations The package doesn’t natively support batch operations (e.g., bulk unsubscribes). Use the MailChimp API’s batch endpoints and wrap them in a custom service:

    $mailchimp->request('POST', '/lists/list-id/actions/unsubscribe', [
        'batch_size' => 1000,
        'data' => ['emails' => ['user1@example.com', 'user2@example.com']],
    ]);
    

Config Quirks

  • Timeouts: Default Guzzle timeout is 10s. Increase for large operations:
    $mailchimp->setClient(new \GuzzleHttp\Client(['timeout' => 30]));
    
  • SSL Verification: Disable only for testing (never in production):
    $mailchimp->setClient(new \GuzzleHttp\Client(['verify' => false]));
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport