# Guide to Mailcoach Webhooks: Features and Best Practices

Mailcoach is an email marketing tool from Spatie, the Laravel package maintainers, available as a hosted service or as a package you run inside your own Laravel app. It manages lists, subscribers and campaigns. Its webhooks exist so your application can keep its own user or contact records in sync with Mailcoach as people subscribe, confirm and unsubscribe, and know when a campaign has finished sending.

This guide covers Mailcoach's four documented events, what changes between hosted and self-hosted installs, verifying the optional `Signature` header, and how to deduplicate without an event ID.

## What are Mailcoach webhooks?

You create webhooks on the **Webhooks** screen in Mailcoach's settings, each with a URL, an optional secret and (where enabled) a choice of event types. Mailcoach sends them with Spatie's own `laravel-webhook-server` package as JSON `POST` requests.

The body is flat: an `event` field holding the PHP event class name, such as `SubscribedEvent`, alongside the subscriber's or campaign's fields. No header names the event.

When you set a secret, Mailcoach adds a `Signature` header: a hex HMAC-SHA256 of the body. Without a secret there's no header, and no way to authenticate the request.

## Mailcoach webhook features

| Feature | Details |
| --- | --- |
| Configuration | Settings **Webhooks** screen |
| Signature | hex HMAC-SHA256 |
| Signature header | `signature` |
| Signed content | The raw request body |
| Key | A secret you enter on the webhook details page. No header without one |
| Body | JSON, flat |
| Event routing | Body field `event` |
| Event filter | Per webhook (self-hosted: `selectable_event_types_enabled`) |
| Auto-disable | After consecutive failures (self-hosted: `maximum_attempts` with `disable_failed_webhooks`) |
| Retries and timeout | Not documented |

## Events and payloads

| Event | Triggered When | Common Use Cases |
| --- | --- | --- |
| `UnconfirmedSubscriberCreatedEvent` | A person is added to a list that uses confirmation; not yet confirmed | Show a "pending" state, send your own follow-up |
| `SubscribedEvent` | A subscriber is confirmed | Create or update the user or contact in your database |
| `UnsubscribedEvent` | Someone unsubscribes | Stop marketing sync, update consent flags |
| `CampaignSentEvent` | A campaign has been fully sent | Record the send and its statistics |

Mailcoach's introduction also says webhooks fire when a tag is added or removed, but the Payloads section doesn't document those events, so their `event` values are unknown. Log any value you don't recognise and still respond with `2xx`.

### Event Payload Structure

Subscriber events carry `event` plus the subscriber: `email_list_uuid`, `email`, first and last name, `tags` and timestamps. `CampaignSentEvent` carries the campaign's fields and its sending statistics. Mailcoach lists the field names but publishes no example bodies, so capture a real delivery from each event before relying on exact types.

There's no event ID or delivery ID in the documented payload.

## Setting up Mailcoach webhooks

### Prerequisites

* A Mailcoach account (hosted) or install (self-hosted) with access to settings
* A public HTTPS endpoint

### Get Your Secret

You choose the secret yourself:

1. In Mailcoach, open the **Webhooks** screen in settings.
2. Create a webhook, or open an existing one, and go to its details page.
3. Enter a long random string as the secret and store it as `WEBHOOK_SECRET`.

Set a secret on the Mailcoach webhook. Without one, deliveries are unsigned and fail verification.

### Register Your Endpoint

1. Enter your server URL, or a Hookdeck source URL.
2. On the details page, choose which events this webhook receives, if you don't want all of them.
3. Save. For a Hookdeck source, paste the same secret into its verification settings; Hookdeck manages the method as `POST`.

### Self-hosted options

Self-hosted installs have extra settings in `config/mailcoach.php`, each of which needs its migrations published and run:

* `webhooks.logs` keeps a log of webhook calls.
* `webhooks.selectable_event_types_enabled` turns on per-webhook event selection.
* `webhooks.maximum_attempts` (for example 5), together with `opt_in_features.disable_failed_webhooks`, disables a webhook after that many consecutive failures. Retries don't count towards the limit.

### Test a delivery

Start a local receiver and forward requests with the [Hookdeck CLI](/docs/cli):

```bash
npx hookdeck-cli listen 3000 mailcoach --path /webhooks/mailcoach

```

Point a webhook at the CLI's URL, then subscribe a test address to a list. If the list uses confirmation, you'll see `UnconfirmedSubscriberCreatedEvent` first and `SubscribedEvent` after confirming.

## Securing Mailcoach webhooks

Compute HMAC-SHA256 of the raw body with the secret, hex-encode it and compare it with `Signature` in constant time. Mailcoach's guide shows PHP's `hash_hmac('sha256', json_encode($payload), $secret)`. That `json_encode` call is the same one `laravel-webhook-server` uses to build the body it sends and signs, so in other languages, hash the raw body rather than re-encoding parsed JSON. See the [webhook documentation](https://www.mailcoach.app/resources/learn-mailcoach/advanced/webhooks/).

```javascript
const crypto = require('node:crypto');

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const signature = headers['signature'];
  if (typeof signature !== 'string') return false;
  const key = Buffer.from(secret, 'utf8');
  const message = rawBody;
  const candidates = [signature];
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
    const received = Buffer.from(candidate, 'hex');
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

```

Mailcoach sends no ID, so the handler below uses a SHA-256 of the raw body as its dedup key. A retry resends the same bytes, while a genuinely new event (a later subscription for the same address, say) has different timestamps and therefore a different hash.

```javascript
const express = require('express');

function createMailcoachApp({ claimKey, contacts, campaigns }) {
  const app = express();
  app.post('/webhooks/mailcoach', express.raw({ type: '*/*' }), async (req, res) => {
    const secret = process.env.WEBHOOK_SECRET;
    if (!secret) return res.sendStatus(500);
    if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(401);
    let payload;
    try {
      payload = JSON.parse(req.body.toString('utf8'));
    } catch {
      return res.sendStatus(400);
    }
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
      return res.sendStatus(400);
    }
    if (typeof payload.event !== 'string') return res.sendStatus(400);
    try {
      const bodyHash = crypto.createHash('sha256').update(req.body).digest('hex');
      const firstTime = await claimKey(bodyHash);
      if (!firstTime) return res.sendStatus(200);
      switch (payload.event) {
        case 'UnconfirmedSubscriberCreatedEvent':
          await contacts.markPending(payload.email_list_uuid, payload.email);
          break;
        case 'SubscribedEvent':
          await contacts.subscribe(payload.email_list_uuid, payload);
          break;
        case 'UnsubscribedEvent':
          await contacts.unsubscribe(payload.email_list_uuid, payload.email);
          break;
        case 'CampaignSentEvent':
          await campaigns.recordSent(payload);
          break;
        default:
          console.log('Unhandled Mailcoach event', payload.event);
      }
    } catch {
      return res.sendStatus(503);
    }
    return res.sendStatus(200);
  });
  return app;
}

```

Only the body is signed, with no timestamp, so the signature doesn't expire. The dedup key is what makes a repeated request harmless.

Hookdeck's Mailcoach source type checks `Signature` as a hex HMAC-SHA256 of the raw body with your secret. Mailcoach gets a `200` regardless, so verification failures don't count towards an auto-disable limit; Hookdeck records each one as failed and doesn't forward it. There's no timestamp tolerance. If a webhook deliberately has no secret, leave verification off on the source.

> **Make Mailcoach webhooks production-ready.** [Hookdeck Event Gateway](/event-gateway) verifies each Mailcoach delivery, keeps a full log with bodies on hosted and self-hosted plans alike, and lets you replay subscriber changes after an outage.

## Mailcoach webhook limitations and pain points

### Unsigned unless you add a secret

**The Problem:** Anyone who finds the URL can unsubscribe or subscribe addresses in your database.

**Why It Happens:** The secret is optional, and a webhook without one sends no `Signature` header.

**Workarounds:**

* Set a secret on every webhook.
* Reject requests that lack the header.

**How Hookdeck Can Help:** With verification enabled, Hookdeck records unsigned requests as failed and never forwards them.

### No event or delivery ID

**The Problem:** Retried deliveries can apply the same change twice.

**Why It Happens:** The documented payload has no identifier for the event.

**Workarounds:**

* Use a hash of the raw body, or `event` plus the list UUID, email and a timestamp, as the key.
* Make subscribe and unsubscribe operations set state rather than toggle it.

**How Hookdeck Can Help:** Hookdeck deduplication can match on chosen body fields to drop repeats within a time window.

### Undocumented retries and success criteria

**The Problem:** You can't tell how long Mailcoach keeps trying after a failure, or what response it treats as success.

**Why It Happens:** The docs mention retries but give no schedule, timeout or success definition.

**Workarounds:**

* Return `2xx` quickly and process afterwards.
* On self-hosted installs, enable `webhooks.logs` to see what Mailcoach sent and how your endpoint answered.

**How Hookdeck Can Help:** Hookdeck accepts every delivery straight away and applies its own retry policy to your service, with the history visible in its dashboard.

### Auto-disable after failures

**The Problem:** A short outage turns the webhook off, and sync silently stops.

**Why It Happens:** With `disable_failed_webhooks` on, a webhook is disabled after `maximum_attempts` consecutive failures.

**Workarounds:**

* Monitor the webhook's status and re-enable it after incidents.
* Set `maximum_attempts` high enough to ride out deploys.

**How Hookdeck Can Help:** Hookdeck answers Mailcoach even while your service is down, so failures on your side don't count towards the limit.

### Undocumented tag events

**The Problem:** Tag changes may arrive with an `event` value your code doesn't expect.

**Why It Happens:** Tag events are mentioned in the introduction but missing from the Payloads section.

**Workarounds:**

* Log and acknowledge unknown events, then add handlers once you've seen their names.

**How Hookdeck Can Help:** Hookdeck's request log shows the exact `event` value and body of any tag delivery as soon as it arrives.

## Best practices

### Mind the header name

The header is literally `Signature`, with no `X-` prefix and no `sha256=` prefix on the value. Header lookups are case-insensitive.

### Choose events per webhook

Where event selection is available, give each webhook only the events its consumer needs, and use separate webhooks (and secrets) for separate systems.

### Respond quickly

Mailcoach's docs don't state a timeout. Store the request, return `2xx`, and update your database in a background job, as the [asynchronous processing guide](/webhooks/guides/why-implement-asynchronous-processing-webhooks) recommends.

### Make updates idempotent

Without an event ID, idempotency depends on your own key and on state-setting updates. The [idempotency guide](/webhooks/guides/implement-webhook-idempotency) covers storing the key with the change.

## Conclusion

Mailcoach's webhooks are a simple way to mirror subscriber state into your own app, and the signature is easy to check once you've set a secret. What the docs leave out (event IDs, retry timing, tag event names and example bodies) is where a Mailcoach receiver needs its own safeguards.

[Hookdeck Event Gateway](https://hookdeck.com) adds a verified, logged and replayable layer in front of Mailcoach, whether you use the hosted service or run it yourself.

[Get started with Hookdeck](https://dashboard.hookdeck.com/signup) for free and handle Mailcoach webhooks reliably in minutes.