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

ekyna/mailchimp-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer

    composer require ekyna/mailchimp-bundle
    

    (Note: Since the README mentions "TODO" for installation, verify compatibility with your Laravel version—likely requires Symfony components or a bridge layer. Check composer.json for dependencies like guzzlehttp/guzzle or symfony/http-client.)

  2. Publish Configuration

    php artisan vendor:publish --provider="Ekyna\MailchimpBundle\MailchimpBundle" --tag="config"
    

    (Edit config/mailchimp.php with your Mailchimp API key and default list/subscriber settings.)

  3. First Use Case: Subscribe a User

    use Ekyna\MailchimpBundle\MailchimpManager;
    
    $mailchimp = app(MailchimpManager::class);
    $mailchimp->subscribe('user@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe']);
    

    (Assumes the bundle follows Laravel’s service container conventions. Verify the MailchimpManager class exists in src/Ekyna/MailchimpBundle/.)


Implementation Patterns

Core Workflows

  1. Subscriber Management

    • Subscribe/Unsubscribe:
      $mailchimp->subscribe('email@example.com', ['MERGE_FIELDS' => ['EMAIL' => ['email@example.com']]]);
      $mailchimp->unsubscribe('email@example.com');
      
    • Batch Operations:
      $mailchimp->batchSubscribe([
          'email1@example.com' => ['FNAME' => 'Alice'],
          'email2@example.com' => ['FNAME' => 'Bob'],
      ]);
      
  2. List Integration

    • Fetch Lists:
      $lists = $mailchimp->getLists();
      
    • Create/Update Lists:
      $mailchimp->createList('My Newsletter', 'newsletter@example.com');
      
  3. Campaigns

    • Trigger Campaigns:
      $mailchimp->sendCampaign($campaignId, ['subject' => 'Hello!']);
      
    • Fetch Campaigns:
      $campaigns = $mailchimp->getCampaigns();
      
  4. Event Webhooks

    • Register Callbacks (if supported):
      $mailchimp->onSubscribe(function ($data) {
          Log::info('New subscriber:', $data);
      });
      

Integration Tips

  • Laravel Service Provider: Bind the manager to the container in AppServiceProvider:

    $this->app->bind(MailchimpManager::class, function ($app) {
        return new \Ekyna\MailchimpBundle\MailchimpManager($app['config']['mailchimp.api_key']);
    });
    
  • Form Requests: Use Laravel’s FormRequest to validate emails before subscribing:

    public function rules() {
        return ['email' => 'required|email'];
    }
    
  • Queue Delayed Tasks: Offload Mailchimp calls to queues (e.g., subscribeAfterRegistration job):

    SubscribeAfterRegistration::dispatch($user->email, $user->name)->delay(now()->addMinutes(5));
    

Gotchas and Tips

Pitfalls

  1. API Key Security

    • Never hardcode keys in .env. Use Laravel’s env() or a dedicated secrets manager.
    • Restrict API Key Permissions: In Mailchimp, limit the key to only necessary endpoints (e.g., lists, subscribers).
  2. Rate Limits

    • Mailchimp throttles requests (typically 10 calls/second). Use Laravel’s throttle middleware or implement exponential backoff:
      try {
          $mailchimp->subscribe(...);
      } catch (RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  3. Merge Fields

    • Case Sensitivity: Mailchimp merge fields (e.g., FNAME) are case-sensitive. Validate against your Mailchimp list’s defined fields.
    • Default Values: Always provide defaults for required fields (e.g., EMAIL):
      $mailchimp->subscribe('email@example.com', [
          'MERGE_FIELDS' => [
              'EMAIL' => ['email@example.com'],
              'FNAME' => ['John'], // Optional
          ]
      ]);
      
  4. Error Handling

    • Parse API Responses: Mailchimp returns JSON with title, detail, and status keys. Normalize errors:
      try {
          $mailchimp->subscribe(...);
      } catch (\Exception $e) {
          $error = json_decode($e->getMessage(), true);
          Log::error("Mailchimp error: {$error['title']} - {$error['detail']}");
      }
      
  5. Testing

    • Mock the Manager: Use Laravel’s Mockery or PHPUnit to stub Mailchimp calls:
      $mock = Mockery::mock(MailchimpManager::class);
      $mock->shouldReceive('subscribe')->once();
      $this->app->instance(MailchimpManager::class, $mock);
      

Extension Points

  1. Custom Merge Fields Extend the bundle by adding a MergeField trait or service:

    class CustomMailchimpManager extends MailchimpManager {
        public function addCustomField($email, $fieldName, $value) {
            $this->callApi('patch', "/lists/{listId}/members/{$email}", [
                'merge_fields' => [$fieldName => $value],
            ]);
        }
    }
    
  2. Event Dispatching Trigger Laravel events (e.g., Subscribed) after Mailchimp operations:

    $mailchimp->subscribe($email, $data);
    event(new Subscribed($email, $data));
    
  3. Webhook Validation If using webhooks, validate signatures with Mailchimp’s webhook-signature header:

    $signature = hash_hmac('sha256', $payload, env('MAILCHIMP_WEBHOOK_SECRET'));
    if (!hash_equals($request->header('webhook-signature'), $signature)) {
        abort(403);
    }
    
  4. Fallback for Offline Cache failed operations (e.g., using database or redis) and retry later:

    $mailchimp->withRetry()->subscribe($email, $data);
    

Debugging

  • Enable Guzzle Debugging: Add to config/mailchimp.php:

    'debug' => env('MAILCHIMP_DEBUG', false),
    

    (If the bundle uses Guzzle, this may log requests/responses to storage/logs/mailchimp.log.)

  • API Explorer: Test endpoints manually via Mailchimp’s API Explorer to verify payloads.

  • Check HTTP Status Codes:

    • 200: Success.
    • 400: Invalid payload (validate merge fields).
    • 401: API key invalid.
    • 404: Resource not found (e.g., list ID).
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware