Outbound Webhooks
Outbound webhooks let your systems react to events as they happen in AdvocateLoop. Instead of polling our API on a schedule, you give us a URL and we POST a JSON payload to it whenever something relevant occurs. Each request is signed with a shared secret so you can verify it came from us.
Typical uses:
- Sync conversions to your data warehouse or analytics tool
- Trigger a CRM update when a claim is created
- Send a Slack/Discord notification when a conversion completes
- Process refunds in a downstream billing system
- Power a custom dashboard or internal tool
If you’re sending events into AdvocateLoop from an external system (Zapier, Make, a CRM), you want the Connecting Zapier, Make, and Custom Backends page instead. This page covers the opposite direction: receiving events from AdvocateLoop.
How it works at a glance
- You register a webhook endpoint in the AdvocateLoop dashboard (Admin → Developers → Webhooks), providing a public
https://URL and choosing which event types you want. - We give you a signing secret. Save it somewhere safe.
- When a matching event happens, we send a
POSTrequest to your URL with a JSON body and signature headers. - Your server verifies the signature, processes the event, and returns a
2xxresponse within 10 seconds. - If the delivery fails temporarily, we retry on a schedule over about a day and a half. If your endpoint keeps failing, it’s automatically disabled and you’re notified.
Available events
Each webhook delivery has a type field identifying what happened (also sent in the X-AL-Event-Type header). The currently available types:
| Event | When it fires |
|---|---|
claim.created | A new claim is recorded against a referral code |
conversion.created | A conversion (purchase or other tracked outcome) is recorded |
conversion.refunded | An existing conversion is partially or fully refunded |
When subscribing, you choose any subset of these. Subscribing to all events from one endpoint is fine.
Request format
Every webhook delivery is a POST to your endpoint URL with this shape:
Headers
| Header | Description |
|---|---|
Content-Type | Always application/json |
X-AL-Event-Type | The event type, e.g. conversion.created |
X-AL-Event-ID | A stable unique ID for this event. Use it for idempotency (see below). |
X-AL-Timestamp | UNIX timestamp (seconds) of when the request was signed. Part of the signature. |
X-AL-Signature | HMAC-SHA256 signature of <timestamp>.<raw body>, hex-encoded. See Verifying signatures. |
User-Agent | AdvocateLoop-Webhooks/1.0 |
Body
A JSON envelope with metadata plus the event payload:
{ "id": "evt_a1b2c3d4-e5f6-7890-abcd-ef1234567890", "type": "conversion.created", "created_at": "2026-03-15T18:23:45.123Z", "data": { "id": "8821", "order_id": "ORD-1001", "customer_email": "customer@example.com", "advocate_id": "0b7e3c2a-5f1d-4c8e-9a6b-2d4f8e1c7a90", "advocate_code": "V2AVMRDJ", "claim_id": 5567, "order_value": 110.58, "order_subtotal": 129.00, "total_discount": 13.00, "advocate_reward_paid": 10.00, "referee_reward_paid": 13.00, "type": "referral", "status": "completed", "items": [ { "name": "Vitamin C Serum", "sku": "VITC-30", "quantity": 2, "unit_price": 32.00, "category_path": ["Skincare", "Serums"], "type": "product" } ], "converted_at": "2026-03-15T18:23:45.000Z" }}The fields inside data vary by event type — see Event payloads below. We never remove fields without notice; new fields may be added over time, so write your parser to ignore unknown fields.
Event payloads
The data object differs per event type. The claim.created and conversion.created payloads include the order’s line items (see Line items); conversion.refunded does not.
All monetary values are numbers in your account’s currency. Timestamps are ISO 8601 strings. Fields marked nullable may be absent or null.
conversion.created
| Field | Type | Description |
|---|---|---|
id | string | Conversion ID |
order_id | string | null | Your order identifier, if you sent one |
customer_email | string | Customer’s email |
advocate_id | string | null | Advocate ID |
advocate_code | string | null | The referral code that drove the conversion |
claim_id | number | null | Associated claim ID, if any |
order_value | number | Merchandise value after discounts — the basis rewards are calculated from |
order_subtotal | number | The total the customer paid, all-in |
total_discount | number | Total discount applied to the order |
advocate_reward_paid | number | null | Reward credited to the advocate for this conversion |
referee_reward_paid | number | null | Reward or discount credited to the customer |
type | string | Conversion type, e.g. referral |
status | string | Conversion status, e.g. completed |
items | array | Line items — see Line items |
converted_at | string | When the purchase occurred (ISO 8601) |
claim.created
| Field | Type | Description |
|---|---|---|
id | string | Claim ID |
referral_code | string | The referral code |
customer_email | string | Customer’s email |
customer_name | string | null | Customer’s name, if provided |
claim_value | number | Claim value |
claim_type | string | referral (a friend’s first purchase) or advocate (an advocate redeeming their reward) |
advocate_id | string | null | Advocate ID |
status | string | Claim status, e.g. pending |
items | array | Line items — see Line items |
created_at | string | When the claim was created (ISO 8601) |
conversion.refunded
| Field | Type | Description |
|---|---|---|
id | string | Conversion ID |
conversion_id | number | Conversion ID (mirrors id) |
order_id | string | null | Your order identifier |
claim_id | number | null | Associated claim ID, if any |
advocate_id | string | null | Advocate ID |
refund_id | string | null | Your refund identifier, if you sent one |
refund_type | string | partial or full |
refund_amount | number | Amount refunded in this event |
original_order_value | number | The conversion’s value before any refunds |
remaining_order_value | number | Value remaining after this refund |
total_refunded_to_date | number | Cumulative amount refunded for this conversion |
reward_reversed | boolean | Whether the associated reward was reversed |
refunded_at | string | When the refund posted (ISO 8601) |
Line items
When present, each entry in an items array uses this shape:
| Field | Type | Description |
|---|---|---|
name | string | Item or service name |
sku | string | null | SKU, plan code, or service code |
quantity | number | Units |
unit_price | number | null | Price per unit |
line_total | number | null | Total for the line |
category_path | string[] | null | Ordered category path, top level first |
image_url | string | null | Image URL for the item |
type | string | null | Item type, e.g. product or service |
Only the fields you supplied when recording the claim or conversion are included; any you omit are left out of the item.
Verifying signatures
Every webhook is signed. Always verify the signature before trusting the payload — without verification, anyone who guesses your endpoint URL could send fake events.
The signature is an HMAC-SHA256, keyed by your endpoint’s signing secret, of the timestamp and the raw request body joined by a dot:
<X-AL-Timestamp>.<raw body>It’s sent in the X-AL-Signature header as a lowercase hex string. Including the timestamp means a captured request can’t be replayed later: reject any request whose timestamp is more than 5 minutes from your server’s clock.
Verification recipe
import hmacimport hashlibimport time
def verify_webhook(raw_body: bytes, timestamp: str, signature: str, secret: str) -> bool: if abs(time.time() - int(timestamp)) > 300: return False # too old (or clock skew): possible replay signed = timestamp.encode('utf-8') + b'.' + raw_body expected = hmac.new(secret.encode('utf-8'), signed, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature)const crypto = require('crypto');
function verifyWebhook(rawBody, timestamp, signature, secret) { if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; // possible replay const expected = crypto .createHmac('sha256', secret) .update(`${timestamp}.${rawBody}`) .digest('hex'); // Use timingSafeEqual to prevent timing attacks const a = Buffer.from(expected, 'hex'); const b = Buffer.from(String(signature), 'hex'); return a.length === b.length && crypto.timingSafeEqual(a, b);}
// verifyWebhook(req.rawBody, req.headers['x-al-timestamp'], req.headers['x-al-signature'], SECRET)<?phpfunction verify_webhook($raw_body, $timestamp, $signature, $secret) { if (abs(time() - intval($timestamp)) > 300) { return false; // possible replay } $expected = hash_hmac('sha256', $timestamp . '.' . $raw_body, $secret); return hash_equals($expected, $signature);}Important verification rules
- Use the raw request body, not a re-serialized version. If your framework parses JSON automatically, you’ll need to access the raw bytes separately (e.g. Express needs a
verifycallback onexpress.json(), Django needsrequest.bodynotrequest.POST). - Sign the timestamp too. Hashing the body alone will never match.
- Use a constant-time comparison (
hmac.compare_digest,crypto.timingSafeEqual,hash_equals). Plain==is vulnerable to timing attacks. - Reject the request if verification fails. Return a
401 Unauthorizedand do nothing else.
Idempotency
We may deliver the same event more than once. This happens if:
- Your endpoint returned an error and we retried
- Your endpoint accepted the event but the connection was lost before we received the response
- A network condition caused a duplicate delivery
To handle this safely, use X-AL-Event-ID as an idempotency key. The simplest pattern: record event IDs you’ve already processed (e.g. in a database table with a unique index) and skip any duplicates:
async function handleWebhook(req, res) { // ... verify signature first ...
const eventId = req.headers['x-al-event-id'];
const existing = await db.processedEvents.findUnique({ where: { id: eventId } }); if (existing) { // Already processed; acknowledge and move on return res.status(200).send('already processed'); }
// Do your processing await processEvent(req.body);
// Mark as processed await db.processedEvents.create({ data: { id: eventId } });
res.status(200).send('ok');}The same event ID is shared across all endpoints that subscribe to that event, so if you have multiple endpoints for redundancy, dedupe by event ID across all of them.
Responding to webhooks
Return status codes
| Status | Meaning to us |
|---|---|
200 – 299 | Success. We mark the delivery complete. |
400, 422 and other 4xx not listed below | You deliberately rejected this event. We don’t retry it, and it doesn’t count against the endpoint. |
401, 403, 404, 405, 410, or any 3xx redirect | The endpoint looks misconfigured. We don’t retry, and it counts toward automatic disabling. We never follow redirects: use the final URL. |
429 | You’re rate limiting us. We retry later. |
5xx, timeout, or network error | Temporary failure. We retry. |
A simple 200 OK with an empty body is the recommended success response.
Respond quickly
You have 10 seconds to respond before we time out and treat the attempt as a temporary failure.
Best practice: acknowledge immediately, process asynchronously. If your processing takes longer than a couple seconds (sending emails, updating a CRM, syncing to a warehouse), put the event on a queue and process it in a background worker. Your webhook handler should be:
async function handleWebhook(req, res) { // 1. Verify signature if (!verifyWebhook(req.rawBody, req.headers['x-al-signature'], SECRET)) { return res.status(401).send('invalid signature'); }
// 2. Idempotency check (quick — just a DB lookup) const eventId = req.headers['x-al-event-id']; if (await alreadyProcessed(eventId)) { return res.status(200).send('already processed'); }
// 3. Enqueue for background processing await queue.add('process-webhook', { event: req.body, eventId });
// 4. Respond immediately res.status(200).send('ok');}This pattern is more resilient — slow downstream systems (a flaky CRM, a high-latency analytics endpoint) can’t take down your webhook handler.
Retries
Temporary failures (5xx, 429, timeouts and network errors) are retried, each retry spaced further apart to give your system time to recover:
| Attempt | Sent |
|---|---|
| 1 | Right away |
| 2 | 30 seconds after attempt 1 |
| 3 | 5 minutes later |
| 4 | 30 minutes later |
| 5 | 2 hours later |
| 6 | 12 hours later |
| 7 | 24 hours later |
If all seven attempts fail, the delivery is marked as permanently failed, about 39 hours after the event.
An endpoint is automatically disabled after 20 events in a row end in failure (permanently failed, or rejected as misconfigured). A success resets the count. You’ll be emailed when this happens; fix whatever broke, then switch the endpoint back on under Admin → Developers → Webhooks.
Testing your endpoint
The fastest way to verify your handler works end-to-end:
- Create a test webhook endpoint pointing at a service like webhook.site or ngrok tunneling to your local dev server. The URL must be public
https://; addresses likelocalhostor private networks are refused. - Click Send test on the endpoint. We send a signed
webhook.testevent right away and show you the response. Test events never count toward automatic disabling, and you can’t subscribe to them. - To see real payloads, subscribe to an event (e.g.
claim.created) and make a test referral. - Inspect the delivery in your tool, then in the endpoint’s delivery log in the AdvocateLoop dashboard.
For local development, ngrok is the standard choice — it gives you a public HTTPS URL that tunnels to localhost, which lets you receive real webhook traffic on your dev machine.
Security checklist
Before going live with a production webhook handler:
- Endpoint URL uses
https://, neverhttp:// - Signature verification implemented and tested, over
<timestamp>.<raw body> - Requests with a timestamp more than 5 minutes off are rejected
- Verification uses a constant-time comparison function
- Verification reads the raw request body, not a re-serialized version
- Failed verifications return
401 Unauthorizedand do not process the payload - Signing secret stored in environment variables / secrets manager, never in source control
- Idempotency keyed on
X-AL-Event-ID - Handler responds within 10 seconds (use a queue if needed)
- Errors during processing don’t return non-
2xxif the event itself was valid (you’ll get retries you don’t need)
Common issues
“Signatures don’t match.” Almost always one of: (a) you’re hashing the body without the <timestamp>. prefix, (b) you’re hashing the parsed/re-serialized JSON instead of the raw body, (c) extra whitespace was added by a middleware, or (d) the wrong secret is being used. Log the raw body bytes you’re hashing and compare lengths against the Content-Length header — if they differ, something is mutating the body before you see it.
“Webhooks stopped arriving.” Check the dashboard for your endpoint status. Auto-disabled endpoints stop receiving events until manually re-enabled. The delivery log will show the failures that led to disabling.
“I’m getting duplicates.” Expected occasionally — use X-AL-Event-ID for idempotency. If it’s happening on every event (not just occasional retries), it usually means your endpoint isn’t returning 2xx quickly enough and we’re treating successful deliveries as failed.
“My local handler works but production doesn’t.” Most commonly: a reverse proxy or framework middleware in production is consuming or modifying the body before your handler sees it. Verify by logging Content-Length vs the bytes you actually receive.