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

V3 Mailchimp Api Php Laravel Package

beelab/v3-mailchimp-api-php

Lightweight PHP wrapper for MailChimp API v3. Provides convenient functions on top of the REST endpoints using Guzzle, installable via Composer. Includes a PHPUnit test suite. Requires PHP 5.5+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install via Composer

    composer require beelab/v3-mailchimp-api-php
    
  2. Configure API Key Add your MailChimp API key (found in Account → Extras → API Keys) to Laravel's .env:

    MAILCHIMP_API_KEY=your_dc_usX_api_key_here
    MAILCHIMP_SERVER=usX  # Replace with your server (e.g., us1, eu1)
    
  3. Initialize the Client In a service provider (e.g., AppServiceProvider):

    use BeeLab\Mailchimp\Mailchimp;
    
    public function register()
    {
        $mailchimp = new Mailchimp(config('mailchimp.api_key'), config('mailchimp.server'));
        $this->app->singleton('mailchimp', function () use ($mailchimp) {
            return $mailchimp;
        });
    }
    
  4. First Use Case: List Campaigns

    $campaigns = app('mailchimp')->call('campaigns', 'get');
    dd($campaigns);
    

Implementation Patterns

Common Workflows

  1. CRUD Operations Use the call() method with the endpoint and HTTP method:

    // Create a subscriber
    $subscriber = app('mailchimp')->call('lists/{list_id}/members', 'post', [
        'email_address' => 'user@example.com',
        'status' => 'subscribed',
    ]);
    
    // Update a subscriber
    $subscriber = app('mailchimp')->call(
        'lists/{list_id}/members/{subscriber_hash}',
        'patch',
        ['status' => 'unsubscribed']
    );
    
  2. Pagination Handle paginated responses (e.g., listing subscribers):

    $subscribers = [];
    $offset = 0;
    $batch = app('mailchimp')->call('lists/{list_id}/members', 'get', [
        'offset' => $offset,
        'count' => 100,
    ]);
    
    while (!empty($batch)) {
        $subscribers = array_merge($subscribers, $batch['members']);
        $offset += 100;
        $batch = app('mailchimp')->call('lists/{list_id}/members', 'get', [
            'offset' => $offset,
            'count' => 100,
        ]);
    }
    
  3. Webhooks Validate incoming webhooks using the verifyWebhook method:

    $isValid = app('mailchimp')->verifyWebhook(
        request()->header('X-Mailchimp-Signature'),
        request()->getContent(),
        config('mailchimp.webhook_secret')
    );
    
  4. Batch Operations Use the batch() method for bulk actions (e.g., deleting subscribers):

    $batch = app('mailchimp')->batch();
    $batch->add('lists/{list_id}/members/{hash1}', 'delete');
    $batch->add('lists/{list_id}/members/{hash2}', 'delete');
    $batch->execute();
    

Integration Tips

  • Laravel Service Container: Bind the client to the container for dependency injection.
  • Events: Dispatch Laravel events (e.g., Subscribed, Unsubscribed) after API calls.
  • Logging: Wrap API calls in a try-catch to log errors:
    try {
        $response = app('mailchimp')->call('endpoint', 'method', $data);
    } catch (\Exception $e) {
        \Log::error("Mailchimp API Error: " . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Format Ensure the API key includes the DC (data center) prefix (e.g., usX_abc123). Without it, requests will fail with 401 Unauthorized.

  2. Rate Limits Mailchimp enforces rate limits. Cache responses or implement exponential backoff:

    if ($response->getStatusCode() === 429) {
        sleep(1); // Retry after 1 second
    }
    
  3. Webhook Signatures Webhook secrets must match exactly (case-sensitive). Regenerate secrets in Mailchimp’s Account → Extras → Settings → Webhooks.

  4. Deprecated Endpoints Some v2 endpoints (e.g., /lists/subscribe) are not supported. Use v3 equivalents (e.g., /lists/{list_id}/members).

Debugging

  • Enable Guzzle Debugging Add this to your AppServiceProvider to log raw API requests/responses:

    $mailchimp->getClient()->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request, $next) {
            \Log::debug('Mailchimp Request:', [
                'url' => (string) $request->getUri(),
                'method' => $request->getMethod(),
                'body' => $request->getBody(),
            ]);
            return $next($request);
        })
    );
    
  • Validate Responses Check for Mailchimp-specific errors in the errors array:

    if (isset($response['errors'])) {
        throw new \Exception($response['errors'][0]['message']);
    }
    

Extension Points

  1. Custom Endpoints Extend the Mailchimp class to add private methods for frequently used endpoints:

    class ExtendedMailchimp extends \BeeLab\Mailchimp\Mailchimp {
        public function getListMembers($listId, $status = 'subscribed') {
            return $this->call("lists/{$listId}/members", 'get', [
                'status' => $status,
            ]);
        }
    }
    
  2. Middleware Add middleware to the Guzzle client for authentication or logging:

    $mailchimp->getClient()->getMiddleware()->prepend(
        new \GuzzleHttp\Middleware::mapRequest(function ($request) {
            $request->getHeaders()->add('Authorization', 'Basic ' . base64_encode(config('mailchimp.api_key')));
            return $request;
        })
    );
    
  3. Testing Mock the client in tests using Laravel’s Mockery:

    $mock = Mockery::mock('BeeLab\Mailchimp\Mailchimp');
    $mock->shouldReceive('call')
         ->with('lists/123/members', 'get')
         ->andReturn(['members' => []]);
    $this->app->instance('mailchimp', $mock);
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony