> ## Documentation Index
> Fetch the complete documentation index at: https://docs.staging.metronome.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Set up webhooks

See [webhook types](https://docs.staging.metronome.com/guides/platform-configuration/webhooks/webhook-types.md) for notification payloads. To inspect whether a notification was delivered, see [monitor webhooks](https://docs.staging.metronome.com/guides/platform-configuration/webhooks/monitor-webhooks.md).

## Handle Webhook Notifications

To receive Metronome webhooks, you need a webhook handler listening at a publicly accessible HTTPS URL that performs the below tasks.

### Acknowledge the Notification

Upon receiving a notification, your endpoint must return a successful status code, such as `200 OK`. If Metronome receives a status code >`299`, notification retries are attempted until a successful status code is returned.

If your webhook endpoint does not properly acknowledge the notification, Metronome continuously retries it with exponential backoff until it hits a 15-minute retry cadence. Once the retry process hits 15 minutes, Metronome repeats the notification until it is either accepted or two days have passed since the initial notification attempt (\~200 retries).

It is recommended that you process webhooks asynchronously: store the webhook payload in a queue, return a `200` response code, and only then validate or process the payload. Removing webhook processing from the receiving path reduces the likelihood of your systems getting blocked.

### Prepare for Duplicate Notifications

Under normal circumstances, Metronome sends each notification exactly once. However, there are a few situations that could cause you to receive the same notification multiple times:

* **Retries** — As mentioned above, if Metronome receives an error when attempting to deliver the notification to your webhook handler, we retry the notification. Depending on the nature of the error, it's possible that your endpoint receives a notification without acknowledging it, in which case your endpoint receives the same notification again.
* **Multiple webhook URLs** — If you configure Metronome to notify multiple webhook URLs, or even the same URL multiple times, notifications are sent multiple times. If you want to ensure duplicate notifications are ignored, you can use the notification's `id` field to deduplicate.

### Verify Notifications

Because your webhook endpoint is a public URL, anyone could send a request to it. Before you take actions based on the notification, you should verify the information it contains. You can do this in two ways: by fetching data from the Metronome API yourself or by verifying the webhook request's signature.

> [!NOTE]
>
> **INFO**
>
> Metronome may introduce backward-compatible changes to existing webhook shapes without notice, such as adding a new webhook field. Metronome recommends that you validate only fields that are expected to be present according to the documentation at time of integration.

#### Call the Metronome API

Webhook notifications contain only minimal information about the event that occurred. This means it's often useful to call the appropriate Metronome API endpoint to get the full details. For example, if you receive a webhook notification informing you that an invoice has been finalized, you can call the `/customers/{customer_id}/invoices/{invoice_id}` endpoint to fetch the details of the invoice mentioned in the notification. In this way, the notification serves as a hint that something has changed, but your code relies only on data obtained directly from the Metronome API.

#### Verify Signatures

If the above strategy doesn't work for your use case, Metronome also provides a method to verify the authenticity of notifications as you receive them by using the `Metronome-Webhook-Signature` HTTP header. The value of this header is a cryptographic signature of the HTTP request, using a secret key set up when you configure your webhook.

> [!TIP]
>
> **Secret keys are unique per webhook**
>
> If you have multiple webhooks configured on your Metronome account, each webhook has its own secret key.

To validate the signature, first concatenate the value of the request's `X-Metronome-Date` header and the exact bytes of the request body, separated by a newline character (`\n`). Then compute the HMAC-SHA256 of the resulting string, keyed by the webhook's secret key. Finally, compare the hexadecimal representation of the HMAC you computed with the one found in the `Metronome-Webhook-Signature` header. If they don't match, the webhook notification did not come from Metronome.

```
HMAC_SHA256(secret_key, X_METRONOME_DATE_HEADER + "\n" + BODY)
```

> [!TIP]
>
> **Use `X-Metronome-Date` instead of `Date`**
>
> Metronome sends both an `X-Metronome-Date` header and a standard `Date` header with the same value. Prefer `X-Metronome-Date` for signature verification: it's preserved end-to-end and isn't rewritten by intermediaries (load balancers, proxies, or frameworks) that may overwrite the standard `Date` header, which would otherwise cause signature verification to fail. The `Date` header is still supported for backward compatibility, but isn't recommended.

The `X-Metronome-Date` header is included to aid in deduplication. You should ignore webhook requests that are older than five minutes, which means your webhook handler only needs to store recent notification IDs to prevent duplicates.

> [!WARNING]
>
> **THE BODY MUST BE TREATED AS BYTES**
>
> When computing the signature, Metronome uses the exact bytes sent in the request body. Be careful to do the same in your code. If you try to use the parsed JSON body for verification purposes, you'll likely fail signature verification because serializing the data again is not guaranteed to produce the same JSON.

The following code example shows how to perform signature validation:

```bash bash theme={null}
echo -n "$X_METRONOME_DATE_HEADER\n$BODY" | openssl dgst -sha256 -hmac $KEY
```

```javascript JavaScript theme={null}
crypto
  .createHmac("sha256", KEY)
  .update(`${headers["X-Metronome-Date"]}\n${body}`)
  .digest("hex");
```

```go Go theme={null}
func isSignatureValid(r *http.Request, body []byte, webhookSecret string) bool {
	signatureHeader := r.Header.Get("Metronome-Webhook-Signature")
	date := r.Header.Get("X-Metronome-Date")

	buff := bytes.NewBufferString(date)
	buff.WriteByte('\n')
	buff.Write(body)

	mac := hmac.New(sha256.New, []byte(webhookSecret))

	mac.Write(buff.Bytes())
	expectedMac := hex.EncodeToString(mac.Sum(nil))

	if !hmac.Equal([]byte(expectedMac), []byte(signatureHeader)) {
		return false
	}
	return true
}
```

To test this, consider the following example webhook notification. The secret key for verification is `correct-horse-battery-staple`:

```http theme={null}
POST /webhook HTTP/1.1
Host: example.com
User-Agent: Metronome
Content-Type: application/json
Date: Mon, 02 Jan 2006 22:04:05 GMT
X-Metronome-Date: Mon, 02 Jan 2006 22:04:05 GMT
Metronome-Webhook-Signature: b82652fa2246cf1d8a27e591f155c865f68b46c19b9213fd9c052f2419b4742b

{
  "id": "b2c9e307-624e-4e7d-a5a4-1b74107d78c4",
  "type": "widget_created",
  "properties": {
    "customer_id": "5f794d50-085a-4db6-8d15-286e518b7225",
    "widget_id": "0891458d-b6f0-4fdd-a41e-380aae1a1e38"
  }
}
```

## Webhook IP Addresses

Webhook notifications may come from the following IP addresses. This list may change, but if it does we'll give at least 30 days notice.

```
52.39.198.29
44.241.254.184
52.42.224.184
52.89.217.131
44.231.139.128
54.245.125.92
3.134.178.31
3.12.62.53
3.140.90.67
3.142.231.113
3.131.206.70
3.132.225.181
```

## Send Webhooks to Slack

If you want to receive Metronome notifications in Slack without building a custom webhook handler, you can configure Metronome to send notifications directly to a Slack channel. From there, you can triage and act on them. To send Metronome webhooks to Slack:

1. [Create an incoming webhook in Slack](https://api.slack.com/messaging/webhooks) and copy the generated webhook URL. It'll look something like: `https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX`
2. Create a webhook destination in Metronome for your Slack channel. In the Metronome app, go to **Developer** > **Notifications** > **Webhooks** > **Add** and paste your Slack webhook URL.
3. Set up a test notification to verify the integration. In the Metronome app, go to **Developer** > **Notifications** > **Create Notification** and create a notification like **Low credit balance reached**.
4. Verify the integration by testing the webhook connection. Trigger your test notification and check your Slack channel for a message from Metronome.

When properly configured, you'll receive Slack messages that look like this:

```json theme={null}
{
  "id": "445b849e-1366-4580-a6cc-f488e27c059f",
  "properties": {
    "customer_id": "ac39ecc3-87ee-4d58-8ec0-24041464dddd",
    "alert_id": "445b849e-1366-4580-a6cc-f488e27c059f",
    "timestamp": "2024-10-07T15:08:44.865Z",
    "threshold": 20000,
    "alert_name": "Credit balance low",
    "credit_type_id": "2714e483-4ff1-48e4-9e25-ac732e8f24f2",
    "remaining_balance": 5000,
    "triggered_by": "usage"
  },
  "type": "alerts.low_remaining_credit_balance_reached"
}
```
