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

Statamic Mailcoach Laravel Package

spatie/statamic-mailcoach

Statamic addon for Mailcoach: view campaign and list summaries in the Statamic control panel, and automatically add subscribers from form submissions or newly registered users. Integrates Mailcoach data into your CMS workflow.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require spatie/statamic-mailcoach
    php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-config"
    
    • Publish the config file to customize settings like default sender email, Mailcoach API key, and list defaults.
  2. Configure Mailcoach:

    • Set your Mailcoach API key in .env:
      MAILCOACH_API_KEY=your_api_key_here
      
    • Ensure your Mailcoach API is accessible from your Statamic instance (same domain or CORS-configured).
  3. First Use Case:

    • View Campaigns/Lists: Navigate to Control Panel > Mailcoach to see a summary of your campaigns and subscriber lists.
    • Add Subscribers via Forms:
      • Use the subscribe helper in your form submission logic:
        use Spatie\Mailcoach\Facades\Mailcoach;
        
        Mailcoach::subscribe($email, $listId); // $listId is the Mailcoach list ID
        
      • Example in a Statamic form handler:
        public function handle()
        {
            $email = $this->data['email'];
            Mailcoach::subscribe($email, 1); // Subscribe to list with ID 1
        }
        
  4. Verify Integration:

    • Check the Mailcoach control panel to confirm subscribers were added.
    • Test sending a campaign to ensure the integration works end-to-end.

Implementation Patterns

Core Workflows

  1. Subscriber Management:

    • Dynamic Subscriptions: Use the subscribe and unsubscribe methods in form handlers, user registration, or API endpoints.
      // Subscribe a user after registration
      event(Registered::class, function ($user) {
          Mailcoach::subscribe($user->email, config('mailcoach.lists.default'));
      });
      
    • Bulk Imports: Use the import method for large-scale subscriber additions (e.g., migrating from another system):
      $emails = ['user1@example.com', 'user2@example.com'];
      Mailcoach::import($emails, 1); // Import to list ID 1
      
  2. Campaign Management:

    • Trigger Campaigns: Use the trigger method to send campaigns programmatically (e.g., after an order is placed):
      Mailcoach::trigger(1); // Trigger campaign with ID 1
      
    • Schedule Campaigns: Configure campaigns in Mailcoach’s UI and use the getCampaigns method to fetch and display them in Statamic:
      $campaigns = Mailcoach::getCampaigns();
      
      Render them in a Statamic blade template:
      @foreach($campaigns as $campaign)
          <div>{{ $campaign->name }} (Status: {{ $campaign->status }})</div>
      @endforeach
      
  3. List Management:

    • Create/Update Lists: Use the createList method to dynamically manage lists (e.g., for segmented audiences):
      $list = Mailcoach::createList([
          'name' => 'Premium Users',
          'description' => 'Users with premium subscriptions',
      ]);
      
    • Fetch Lists: Retrieve lists to populate dropdowns or dynamic forms:
      $lists = Mailcoach::getLists();
      
  4. Integration with Statamic Features:

    • User Registration/Profile Updates: Hook into Statamic’s users.created or users.updated events to sync subscribers:
      event(Users\Events\UserCreated::class, function ($user) {
          Mailcoach::subscribe($user->email, config('mailcoach.lists.default'));
      });
      
    • Form Builder Integration: Add a hidden field to your Statamic forms to capture Mailcoach list preferences:
      <input type="hidden" name="mailcoach_list" value="{{ $listId }}">
      
      Then handle it in your form handler:
      $listId = $this->data['mailcoach_list'] ?? config('mailcoach.lists.default');
      Mailcoach::subscribe($this->data['email'], $listId);
      
  5. API-Driven Workflows:

    • Webhooks: Use Mailcoach’s webhook system to trigger Statamic actions (e.g., update user tags or send notifications):
      // Example: Verify webhook signature in a Statamic route
      $payload = request()->json()->all();
      $signature = request()->header('X-Mailcoach-Signature');
      if (Mailcoach::verifyWebhook($payload, $signature)) {
          // Process webhook (e.g., update user status)
      }
      

Integration Tips

  1. Statamic Blueprints:

    • Extend Statamic’s blueprints to include Mailcoach-specific fields (e.g., for campaigns or lists):
      fields:
          mailcoach_campaign:
              type: number
              display: Mailcoach Campaign ID
              help: ID of the Mailcoach campaign to trigger.
      
    • Use the afterSave hook to trigger campaigns:
      public function afterSave($model)
      {
          if ($model->mailcoach_campaign) {
              Mailcoach::trigger($model->mailcoach_campaign);
          }
      }
      
  2. Antlers Tags:

    • Create custom Antlers tags to fetch and display Mailcoach data:
      // In a service provider
      Antlers::extend('mailcoachCampaigns', function ($expression) {
          return Mailcoach::getCampaigns();
      });
      
      Usage in a template:
      {{ mailcoachCampaigns }}
      
  3. Scheduling:

    • Use Laravel’s task scheduling to sync subscribers or clean up inactive lists:
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule)
      {
          $schedule->call(function () {
              Mailcoach::syncSubscribers(); // Custom method to sync
          })->daily();
      }
      
  4. Testing:

    • Mock the Mailcoach API in tests to avoid hitting the real service:
      Mailcoach::shouldReceive('subscribe')->once()->with($email, $listId);
      
    • Use Statamic’s testing helpers to simulate form submissions:
      $response = $this->post('/form', ['email' => 'test@example.com']);
      $response->assertSessionHasNoErrors();
      

Gotchas and Tips

Pitfalls

  1. API Key Security:

    • Never expose the API key in client-side code. Always validate and use it server-side.
    • Restrict API access: Configure Mailcoach’s API to allow requests only from your Statamic domain/IP.
    • Environment variables: Store the key in .env and never commit it to version control.
  2. Rate Limiting:

    • Mailcoach may throttle requests during bulk operations. Implement retries with exponential backoff:
      try {
          Mailcoach::import($emails, $listId);
      } catch (\GuzzleHttp\Exception\RequestException $e) {
          if ($e->getCode() === 429) {
              sleep(2); // Wait before retrying
              retry();
          }
      }
      
  3. Subscriber Duplication:

    • Mailcoach does not automatically deduplicate subscribers. Handle this in your code:
      if (!Mailcoach::isSubscribed($email, $listId)) {
          Mailcoach::subscribe($email, $listId);
      }
      
  4. Time Zones and Scheduling:

    • Campaign schedules in Mailcoach use UTC. Ensure your Statamic timestamps are also in UTC to avoid misalignment.
    • Display scheduled times to users in their local time zone:
      $campaign->scheduled_at->setTimezone($user->timezone);
      
  5. List Permissions:

    • Ensure your Mailcoach API user has permissions to create, read, update, and delete lists/campaigns as needed.
    • Test list operations in a staging environment first to avoid permission errors in production.
  6. Webhook Delays:

    • Webhook deliveries may be delayed. Implement a fallback mechanism (e.g., periodic polling) for critical actions:
      if (!$webhookProcessed) {
          Mailcoach::pollForUpdates(); // Custom method to check for missed updates
      }
      

Debugging

  1. Enable Logging:

    • Configure the mailcoach logging channel in config/logging.php to debug API interactions:
      'channels' => [
          'mailcoach' => [
              'driver' => 'single',
              'path' => storage_path('logs/mailcoach.log'),
              'level' => 'debug',
          ],
      ],
      
    • Add the channel to the mailcoach config:
      'log_channel' => 'mailcoach',
      
  2. API Response Inspection:

    • Use Laravel’s tap method to inspect raw API responses:
      Mail
      
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