# Campaign and agent webhooks (/webhooks/campaign-agent-webhooks)

A campaign or an agent can have its own webhook URL. CallMitra sends that call's results there as flat JSON signed with `X-Signature-SHA256`. These URLs send fewer events than [webhook endpoints](/webhooks/endpoints), have no delivery log, and use a simpler signature. Use webhook endpoints for new integrations, and see [Move to webhook endpoints](#move-to-webhook-endpoints) to switch.

<Callout title="No workspace URL">
The workspace CRM webhook (`/api/v1/merchant/crm-webhook`) was retired on 2026-11-16. Saved workspace URLs were moved to webhook endpoints with a new secret. See the [changelog](/changelog).
</Callout>

<Callout title="Both systems fire">
Campaign and agent URLs and webhook endpoints are independent. If a call has a campaign or agent URL **and** you have an endpoint subscribed to `call.completed`, both get a copy.
</Callout>

## The two URLs [#the-two-urls]

| URL | Where you set it | Signing secret |
| --- | --- | --- |
| **Campaign webhook** | `crmWebhookUrl` and `crmWebhookSecret` on [`POST /api/v1/campaigns/`](/api-reference/campaigns/createCampaign), [`PUT /api/v1/campaigns/{campaign_id}`](/api-reference/campaigns/updateCampaign), or inside `campaignData` on [`POST /api/v1/campaigns/create-with-leads`](/api-reference/campaigns/createCampaignWithLeads) | The campaign's `crmWebhookSecret` |
| **Agent post-call webhook** | [`PUT /api/v1/agents/{agent_id}/post-call-webhook`](/api-reference/webhooks/setAgentPostCallWebhook) | The agent's webhook `secret` |

Campaign and agent URLs can be `http://` or `https://`, but they must point to a public internet address. The secret is optional. Without one, deliveries have no `X-Signature-SHA256` header.

### Agent post-call webhook [#agent-post-call-webhook]

```bash
curl -X PUT https://api.callmitra.ai/api/v1/agents/3f0c2a9e-6a51-4c6e-9a3e-2d1b7c4e8f10/post-call-webhook \
  -H "X-API-Key: $CALLMITRA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/hooks/calls", "secret": "a-long-random-secret", "trigger": "completed"}'
```

| Field | Description |
| --- | --- |
| `url` | Where to send call results. Send `""` to turn the webhook off. A URL that is not a public internet address is refused with [`agent_state_blocked`](/errors/agent_state_blocked). |
| `secret` | Signing secret. Leave it out to keep the current one. It is never returned; the response has `hasSecret`. |
| `trigger` | Which calls are sent: `every` (default), `completed` (the call connected: status `completed`, or an outcome other than `no_answer`, `busy` or `call_failed`), or `voicemail` (outcome `voicemail`). |

The change applies to the live agent at once. `trigger` only applies when this agent webhook is the URL chosen for the call (see below).

## Which URL a call uses [#which-url-a-call-uses]

For `call.completed` and `call.escalated`, CallMitra picks **one** URL per call. The first match wins:

1. The call's **campaign** webhook.
2. The call's **agent** post-call webhook. Its `trigger` can skip the call.

If neither is set, the call is sent only to your webhook endpoints.

## Which events go where [#which-events-go-where]

| Event | Campaign or agent URL |
| --- | --- |
| `call.completed` | The URL picked above. |
| `call.escalated` | The URL picked above. The agent's `trigger` is not applied. |
| `transfer.failed`, `callback.scheduled`, `callback.completed`, `callback.failed` | The campaign webhook, else the agent webhook. Only while **CRM webhook** alerts are on in **Settings → Notifications** for that event. They are on by default. |
| `call.failed`, `ticket.*`, `lead.*`, `campaign.*`, `whatsapp.message.received` | Not sent. Use a webhook endpoint. |

## Delivery format [#delivery-format]

```http
POST /hooks/call-results HTTP/1.1
Content-Type: application/json
X-Webhook-Id: 3f2b8c1e-6a4d-4f7e-9b1a-2c5d8e9f0a1b:call.completed
X-Webhook-Event: call.completed
X-Signature-SHA256: 5d41402abc4b2a76b9719d911017c592ae0e5f3e8c2a1b9f0d7e6c5b4a392817
```

| Header | Meaning |
| --- | --- |
| `X-Webhook-Id` | Stays the same across retries. For `call.completed` and `call.escalated` it is `{callId}:{event}`. For other events it is a job UUID. Use it to drop duplicates. |
| `X-Webhook-Event` | The event type. |
| `X-Signature-SHA256` | Hex HMAC-SHA256 of the raw body, keyed with the secret. Only when a secret is set. |

The body is flat JSON. It has the same fields as the event's `data` in [Event types](/webhooks/events), plus two more:

- `event`: the event type, for example `call.completed`.
- `timestamp`: when this attempt was sent, in Unix seconds. It changes on every retry.

The JSON is compact, with keys sorted alphabetically and non-ASCII characters escaped (`\u0928`). A `call.completed` body, shown here with line breaks:

```json title="call.completed (campaign or agent URL)"
{
  "agentId": "5c4b3a29-1807-4f6e-9d8c-7b6a59483726",
  "callAnalysis": { "summary": "…" },
  "callId": "3f2b8c1e-6a4d-4f7e-9b1a-2c5d8e9f0a1b",
  "campaignId": "8a7d9c2b-1e3f-4a5b-8c6d-7e8f9a0b1c2d",
  "crmPayload": { "callAnalysis": { "summary": "…" } },
  "customerNumber": "+919876543210",
  "direction": "outbound",
  "duration": 94,
  "endTime": "2026-11-15T05:31:46+00:00",
  "endedReason": "customer-ended-call",
  "event": "call.completed",
  "extractedFields": { "preferredCallbackDay": "Monday" },
  "lead": { "company": "", "customFields": { "plan": "Gold" }, "email": "", "externalId": "crm-1042", "id": "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", "name": "Asha Rao", "phone": "+919876543210" },
  "leadId": "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed",
  "merchantOutcome": "callback",
  "outcome": "callback_requested",
  "outcomeCategory": "positive",
  "phone": "+919876543210",
  "providerCallId": "CA1234567890abcdef",
  "recommendedLeadStatus": "follow_up",
  "recordingUrl": "https://api.callmitra.ai/api/v1/calls/3f2b8c1e-6a4d-4f7e-9b1a-2c5d8e9f0a1b/recording",
  "sentiment": "positive",
  "startTime": "2026-11-15T05:30:12+00:00",
  "status": "completed",
  "summary": "Customer wants to renew the Gold plan and asked for a callback on Monday.",
  "timestamp": 1763184710,
  "transcript": "Agent: Namaste Asha ji…"
}
```

## Retries and pausing [#retries-and-pausing]

These deliveries use the same rules as endpoints: answer `2xx` within **10 seconds**. `408`, `409`, `425`, `429`, `5xx`, timeouts and connection errors are retried up to **12 attempts**, starting at 30 seconds and doubling. Other `4xx` answers are not retried. Unlike endpoints, a delivery still not sent **24 hours** after it was queued expires.

If **20 call events in a row** to the same URL are rejected for good (a non-retryable `4xx`, or all attempts used), CallMitra **pauses** that URL. Rejected `callback.*` events do not count. While a URL is paused, new events for it are skipped. You get a "CRM webhook paused" notification in the console, and by email or WhatsApp if those alerts are on.

To resume, fix your receiver, open **Settings → Developers → Webhooks** in the console, and send a test from the **Campaign and agent webhooks** card. The test re-sends the newest finished call that used the URL, with its real `X-Webhook-Id`. If your server accepts it, the URL resumes.

There is no delivery log or redelivery for campaign and agent URLs.

## Verify X-Signature-SHA256 [#verify-x-signature-sha256]

`X-Signature-SHA256` is the lowercase hex HMAC-SHA256 of the raw body bytes, keyed with the secret as UTF-8 text.

1. Read the **raw body bytes** exactly as received. Do not parse and re-serialize the JSON first.
2. Compute `HMAC-SHA256(secret, rawBody)` and hex-encode it.
3. Compare it with `X-Signature-SHA256` using a **constant-time** comparison. Reject the request with `401` if they differ.
4. Parse the JSON and reject it if `timestamp` is more than **5 minutes** old. This stops someone replaying a captured request later.
5. Skip the event if you already handled its `X-Webhook-Id`.

<Tabs groupId="language" persist items={["Node.js","Python","PHP","Go","Java"]}>
<Tab value="Node.js">
```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const secret = process.env.CALLMITRA_WEBHOOK_SECRET;

app.post('/hooks/call-results', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = crypto.createHmac('sha256', secret).update(req.body).digest('hex');
  const received = req.get('X-Signature-SHA256') ?? '';
  const valid =
    received.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
  if (!valid) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString('utf8'));
  if (!Number.isInteger(event.timestamp) || Math.abs(Date.now() / 1000 - event.timestamp) > 300) {
    return res.sendStatus(401);
  }

  // Look up req.get('X-Webhook-Id') in your store and skip duplicates, then queue the work.
  res.sendStatus(204);
});
```
</Tab>

<Tab value="Python">
```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["CALLMITRA_WEBHOOK_SECRET"].encode()

@app.post("/hooks/call-results")
def callmitra_webhook():
    raw = request.get_data()  # raw bytes, before any JSON parsing
    expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    received = request.headers.get("X-Signature-SHA256", "")
    if not hmac.compare_digest(expected, received):
        abort(401)

    event = json.loads(raw)
    if abs(time.time() - event["timestamp"]) > 300:
        abort(401)

    # Skip duplicates by request.headers["X-Webhook-Id"], then queue the work.
    return "", 204
```
</Tab>

<Tab value="PHP">
```php
<?php
$secret = getenv('CALLMITRA_WEBHOOK_SECRET');
$raw = file_get_contents('php://input');

$expected = hash_hmac('sha256', $raw, $secret);
$received = $_SERVER['HTTP_X_SIGNATURE_SHA256'] ?? '';
if (!hash_equals($expected, $received)) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
if (abs(time() - (int) $event['timestamp']) > 300) {
    http_response_code(401);
    exit;
}

// Skip duplicates by $_SERVER['HTTP_X_WEBHOOK_ID'], then queue the work.
http_response_code(204);
```
</Tab>

<Tab value="Go">
```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"net/http"
	"os"
	"time"
)

var secret = []byte(os.Getenv("CALLMITRA_WEBHOOK_SECRET"))

func callmitraWebhook(w http.ResponseWriter, r *http.Request) {
	raw, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "bad body", http.StatusBadRequest)
		return
	}
	mac := hmac.New(sha256.New, secret)
	mac.Write(raw)
	expected := hex.EncodeToString(mac.Sum(nil))
	if !hmac.Equal([]byte(expected), []byte(r.Header.Get("X-Signature-SHA256"))) {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	var event struct {
		Event     string `json:"event"`
		Timestamp int64  `json:"timestamp"`
	}
	if json.Unmarshal(raw, &event) != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	if d := time.Now().Unix() - event.Timestamp; d > 300 || d < -300 {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	// Skip duplicates by r.Header.Get("X-Webhook-Id"), then queue the work.
	w.WriteHeader(http.StatusNoContent)
}
```
</Tab>

<Tab value="Java">
```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class CallMitraSignature {
  /** True when signatureHeader is the hex HMAC-SHA256 of rawBody with secret. */
  public static boolean isValid(byte[] rawBody, String signatureHeader, String secret) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String expected = HexFormat.of().formatHex(mac.doFinal(rawBody));
    byte[] received = signatureHeader == null ? new byte[0] : signatureHeader.getBytes(StandardCharsets.UTF_8);
    return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), received);
  }
}
// After isValid(...) returns true, parse the JSON, reject a `timestamp` older than 300 seconds,
// and skip X-Webhook-Id values you have already handled.
```
</Tab>
</Tabs>

**Use the right secret.** A campaign webhook is signed with the campaign's `crmWebhookSecret` and an agent webhook with the agent's secret.

### On webhook endpoint deliveries [#on-webhook-endpoint-deliveries]

Deliveries to [webhook endpoints](/webhooks/endpoints) also carry `X-Signature-SHA256`, so you can point an existing campaign or agent receiver at an endpoint. Some things differ:

- The key is the **whole** endpoint secret as text, including the `whsec_` prefix. It is not base64-decoded.
- It is computed with the **current** secret only. After you [rotate the secret](/webhooks/endpoints#rotate-the-signing-secret), it uses the new one at once, with no overlap.
- The envelope body has no `timestamp` field. Check the `webhook-timestamp` header instead, but note that `X-Signature-SHA256` does not cover it.

For these reasons, verify `webhook-signature` on endpoint deliveries. See [Verify signatures](/webhooks/verify-signatures).

## Move to webhook endpoints [#move-to-webhook-endpoints]

<Steps>
<Step>
### Create an endpoint [#create-an-endpoint]

[Create a webhook endpoint](/webhooks/endpoints#create-an-endpoint) for your receiver's URL (it must be `https://`), subscribed to the events you use today, for example `call.completed` and `call.escalated`. Store the `whsec_…` secret.
</Step>

<Step>
### Update your receiver [#update-your-receiver]

Read the event from the envelope: the type is in `type` and the fields are in `data`. Verify `webhook-signature` as in [Verify signatures](/webhooks/verify-signatures), and drop duplicates by `webhook-id`. If you build ids from `X-Webhook-Id`, note that endpoint ids are `evt_…` values.
</Step>

<Step>
### Run both for a while [#run-both-for-a-while]

Both systems deliver while the campaign or agent URL is set, so your receiver gets two copies of each call event with different ids. Dedupe on `data.callId` plus the event type until you clear that URL.
</Step>

<Step>
### Clear the campaign and agent URLs [#clear-the-campaign-and-agent-urls]

Send `""` as the campaign's `crmWebhookUrl` and the agent's `url`.
</Step>
</Steps>