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

Simple PHP wrapper for the Mailchimp API. Send campaigns, manage lists/audiences, subscribers and members, view reports, and handle API calls with minimal setup. Lightweight, Composer-friendly, and easy to integrate into existing PHP/Laravel apps.

View on GitHub
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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