Skip to content

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

  1. You register a webhook endpoint in the AdvocateLoop dashboard (Admin → Developers → Webhooks), providing a public https:// URL and choosing which event types you want.
  2. We give you a signing secret. Save it somewhere safe.
  3. When a matching event happens, we send a POST request to your URL with a JSON body and signature headers.
  4. Your server verifies the signature, processes the event, and returns a 2xx response within 10 seconds.
  5. 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:

EventWhen it fires
claim.createdA new claim is recorded against a referral code
conversion.createdA conversion (purchase or other tracked outcome) is recorded
conversion.refundedAn 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

HeaderDescription
Content-TypeAlways application/json
X-AL-Event-TypeThe event type, e.g. conversion.created
X-AL-Event-IDA stable unique ID for this event. Use it for idempotency (see below).
X-AL-TimestampUNIX timestamp (seconds) of when the request was signed. Part of the signature.
X-AL-SignatureHMAC-SHA256 signature of <timestamp>.<raw body>, hex-encoded. See Verifying signatures.
User-AgentAdvocateLoop-Webhooks/1.0

Body

A JSON envelope with metadata plus the event payload:

json
{
"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

FieldTypeDescription
idstringConversion ID
order_idstring | nullYour order identifier, if you sent one
customer_emailstringCustomer’s email
advocate_idstring | nullAdvocate ID
advocate_codestring | nullThe referral code that drove the conversion
claim_idnumber | nullAssociated claim ID, if any
order_valuenumberMerchandise value after discounts — the basis rewards are calculated from
order_subtotalnumberThe total the customer paid, all-in
total_discountnumberTotal discount applied to the order
advocate_reward_paidnumber | nullReward credited to the advocate for this conversion
referee_reward_paidnumber | nullReward or discount credited to the customer
typestringConversion type, e.g. referral
statusstringConversion status, e.g. completed
itemsarrayLine items — see Line items
converted_atstringWhen the purchase occurred (ISO 8601)

claim.created

FieldTypeDescription
idstringClaim ID
referral_codestringThe referral code
customer_emailstringCustomer’s email
customer_namestring | nullCustomer’s name, if provided
claim_valuenumberClaim value
claim_typestringreferral (a friend’s first purchase) or advocate (an advocate redeeming their reward)
advocate_idstring | nullAdvocate ID
statusstringClaim status, e.g. pending
itemsarrayLine items — see Line items
created_atstringWhen the claim was created (ISO 8601)

conversion.refunded

FieldTypeDescription
idstringConversion ID
conversion_idnumberConversion ID (mirrors id)
order_idstring | nullYour order identifier
claim_idnumber | nullAssociated claim ID, if any
advocate_idstring | nullAdvocate ID
refund_idstring | nullYour refund identifier, if you sent one
refund_typestringpartial or full
refund_amountnumberAmount refunded in this event
original_order_valuenumberThe conversion’s value before any refunds
remaining_order_valuenumberValue remaining after this refund
total_refunded_to_datenumberCumulative amount refunded for this conversion
reward_reversedbooleanWhether the associated reward was reversed
refunded_atstringWhen the refund posted (ISO 8601)

Line items

When present, each entry in an items array uses this shape:

FieldTypeDescription
namestringItem or service name
skustring | nullSKU, plan code, or service code
quantitynumberUnits
unit_pricenumber | nullPrice per unit
line_totalnumber | nullTotal for the line
category_pathstring[] | nullOrdered category path, top level first
image_urlstring | nullImage URL for the item
typestring | nullItem 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

python
import hmac
import hashlib
import 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)
javascript
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)
php
<?php
function 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 verify callback on express.json(), Django needs request.body not request.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 Unauthorized and 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:

javascript
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

StatusMeaning to us
200 – 299Success. We mark the delivery complete.
400, 422 and other 4xx not listed belowYou 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 redirectThe endpoint looks misconfigured. We don’t retry, and it counts toward automatic disabling. We never follow redirects: use the final URL.
429You’re rate limiting us. We retry later.
5xx, timeout, or network errorTemporary 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:

javascript
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:

AttemptSent
1Right away
230 seconds after attempt 1
35 minutes later
430 minutes later
52 hours later
612 hours later
724 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:

  1. 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 like localhost or private networks are refused.
  2. Click Send test on the endpoint. We send a signed webhook.test event right away and show you the response. Test events never count toward automatic disabling, and you can’t subscribe to them.
  3. To see real payloads, subscribe to an event (e.g. claim.created) and make a test referral.
  4. 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://, never http://
  • 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 Unauthorized and 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-2xx if 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.