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

Mailgunwebhooks Bundle Laravel Package

azine/mailgunwebhooks-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    "azine/mailgunwebhooks-bundle": "dev-master"
    

    Run composer update.

  2. Register the Bundle Add to config/bundles.php:

    return [
        // ...
        Azine\MailgunWebhooksBundle\AzineMailgunWebhooksBundle::class => ['all' => true],
    ];
    
  3. Configure Mailgun Webhook Endpoint Run:

    php bin/console debug:router | grep mailgunevent_webhook
    

    Copy the generated URL (e.g., /mailgun-webhook) and add it to your Mailgun Webhooks settings under Settings > Webhooks.

  4. Configure Bundle Add to config/packages/azine_mailgun_webhooks.yaml:

    azine_mailgun_webhooks:
        api_key: "%env(MAILGUN_API_KEY)%"
        email_domain: "yourdomain.com"
        no_reply_email: "no-reply@yourdomain.com"
        no_reply_name: "Your App Name"
    
  5. Test the Webhook Send a test email via Mailgun and verify the event appears in the admin panel at /admin/mailgun.


Implementation Patterns

Core Workflow: Capturing and Processing Events

  1. Webhook Endpoint Mailgun POSTs event data to /mailgun-webhook. The bundle automatically:

    • Validates the signature (using api_key).
    • Stores raw event data in the MailgunEvent entity (Doctrine ORM).
    • Dispatches a MailgunWebhookEvent for custom logic (e.g., notifications).
  2. Admin Interface

    • List Events: Filter/search via /admin/mailgun (Twig templates).
    • View Details: Click an event to see raw JSON payload.
    • Delete Events: Use the CLI or admin UI to purge old data.
  3. Event-Driven Extensions Subscribe to MailgunWebhookEvent in a service:

    // src/EventListener/CustomMailgunListener.php
    namespace App\EventListener;
    
    use Azine\MailgunWebhooksBundle\Event\MailgunWebhookEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CustomMailgunListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                MailgunWebhookEvent::NAME => 'onMailgunEvent',
            ];
        }
    
        public function onMailgunEvent(MailgunWebhookEvent $event)
        {
            $eventData = $event->getEvent();
            if ($eventData->getEvent() === 'failed') {
                // Trigger custom logic (e.g., Slack alert)
            }
        }
    }
    
  4. CLI Automation

    • Delete Old Events:
      php bin/console mailgun:delete-events --date="30 days ago"
      
    • Check IP Blacklists:
      php bin/console mailgun:check-ip-in-blacklist --numberOfAttempts=3
      
      Configure hetrixtools_service in config/packages/azine_mailgun_webhooks.yaml for API access.

Integration Tips

  1. SwiftMailer Integration Use SwiftMailerMailgunWebhookEventListener (if available in future updates) to auto-notify admins of critical events (e.g., bounces).

  2. Database Optimization

    • Add indexes to MailgunEvent for frequently queried fields (e.g., event, timestamp).
    • Schedule mailgun:delete-events via cron (e.g., weekly):
      0 3 * * 1 php /path/to/bin/console mailgun:delete-events --date="90 days ago"
      
  3. Monolog Filtering Exclude non-critical 404s from Mailgun logs to avoid clutter:

    monolog:
        handlers:
            main:
                type: fingers_crossed
                excluded_404s:
                    - ".*/api/.*"  # Example: Ignore API 404s
    
  4. Spam Alerts Enable spam notifications in config:

    spam_alerts:
        enabled: true
        alerts_recipient_email: "admin@example.com"
    

    Mailgun will email admins if your sending IP is blacklisted (via HetrixTools).


Gotchas and Tips

Pitfalls

  1. Webhook Signature Validation

    • Ensure api_key in config matches your Mailgun API key.
    • Test locally by sending a POST to /mailgun-webhook with a valid signature:
      curl -X POST http://yourdomain.test/mailgun-webhook \
           -H "Content-Type: application/json" \
           -H "X-Mailgun-Signature: YOUR_SIGNATURE" \
           -d '{"event":"sent", "timestamp":123456789}'
      
  2. Database Bloat

    • Free Mailgun accounts purge logs after 48 hours, but this bundle persists data indefinitely.
    • Fix: Schedule mailgun:delete-events to avoid storage issues.
  3. HetrixTools API Limits

    • Free tier allows ~3 blacklist checks/day. Exceeding this may trigger rate limits.
    • Fix: Set repeat_notification_after_days to avoid redundant checks:
      hetrixtools_service:
          repeat_notification_after_days: 7
      
  4. Event Overload

    • High-traffic apps may receive thousands of events/hour, slowing down the webhook endpoint.
    • Fix: Use a queue (e.g., Symfony Messenger) to process events asynchronously:
      // src/MessageHandler/MailgunEventHandler.php
      use Azine\MailgunWebhooksBundle\Entity\MailgunEvent;
      use Symfony\Component\Messenger\Attribute\AsMessageHandler;
      
      #[AsMessageHandler]
      public function __invoke(MailgunEvent $event)
      {
          // Process event (e.g., save to DB)
      }
      
  5. Symfony 2.x to 4+/5+/6+ Migration

    • The bundle supports Symfony 2.x but may need adjustments for newer versions (e.g., AppKernelbundles.php).
    • Fix: Update routing (YAML → PHP) and dependency injection (XML → YAML).

Debugging Tips

  1. Webhook Failures

    • Check Symfony logs (var/log/dev.log) for validation errors.
    • Verify the X-Mailgun-Signature header matches Mailgun’s calculation:
      # Test signature locally
      echo -n "timestamp=123456789" | openssl dgst -sha1 -hmac "YOUR_API_KEY" -binary | openssl enc -base64 -A
      
  2. CLI Command Issues

    • For mailgun:check-ip-in-blacklist, ensure hetrixtools_service.api_key is set and the IP is resolvable.
    • Debug with:
      php bin/console debug:container Azine\MailgunWebhooksBundle\Command\CheckIpInBlacklistCommand
      
  3. Admin UI Glitches

    • Clear cache if templates fail to render:
      php bin/console cache:clear
      
    • Check Twig errors in var/log/dev.log.

Extension Points

  1. Custom Event Handlers Extend the MailgunWebhookEvent subscriber pattern to add logic for specific events (e.g., "clicked" → update user analytics):

    // src/EventListener/AnalyticsListener.php
    public function onMailgunEvent(MailgunWebhookEvent $event)
    {
        if ($event->getEvent()->getEvent() === 'clicked') {
            $this->analyticsService->track($event->getEvent()->getRecipient());
        }
    }
    
  2. Custom Blacklist Providers Replace HetrixTools with another service (e.g., Spamhaus) by implementing Azine\MailgunWebhooksBundle\Service\BlacklistCheckerInterface.

  3. Webhook Retries Add retry logic for failed webhook deliveries using Symfony Messenger or a queue system.

  4. Event Enrichment Join MailgunEvent with other entities (e.g., users) in the admin list view:

    {# templates/mailgun/event/list.html.twig #}
    <td>{{ event.recipient|split('@')[0] }} {# Extract email local part #}</td>
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle