Skip to Content
AffFast

Webhooks

Get the events of your workspace as signed HTTPS requests, and verify the signature.

A webhook endpoint is an HTTPS URL on your server. The API sends a request to it for each event that you choose, for example conversion.created. The requests follow the Standard Webhooks specification. You can use a Standard Webhooks library, or the code on this page.

Make an endpoint

You need an API key with the scope webhooks:write.

curl -X POST https://api.afffast.com/v1/webhook_endpoints \
  -H "Authorization: Bearer $AFFFAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://hooks.example.com/ans",
    "events": ["conversion.created", "conversion.status_changed"]
  }'

The response has the signing secret in secret. It starts with whsec_. The API shows the secret one time. Save it now. A live endpoint must use https. A test endpoint can use http. The URL must not point to a private or internal address.

Each workspace can have 20 endpoints in each mode.

Event types

Use * to get all event types.

Event typeWhen
conversion.createdThe API saves a new conversion.
conversion.updatedA conversion changes (for example its amount), or the click context is joined to it.
conversion.status_changedThe status of a conversion changes.
click.attributedThe API stores the click_id of a conversion. click_context is null in this event.
program.status_changedYour status in a program changes.
commission.changedThe commission of a program changes.
payout.createdA payout is new.
payout.updatedA payout changes.
connection.syncedA sync of a connection ends.
connection.failedA connection fails and needs your action.
destination.failedA destination stops after repeated failures.

The body of a request is the event object. It is the same object as GET /v1/events returns. data.object is the object at the time of the change. Use id of the event to remove duplicates. The API keeps events for 30 days.

The click context

A conversion has click_id when the network sends our click ID back. The API joins the click context (the page, the site, the link code, the country and the device) later. The join runs after the sync, so the context is not in conversion.created or in click.attributed. In both events click_context is null.

When the join stores the context, the API sends one conversion.updated event. In this event, data.object.click_context has the context and data.previous_attributes.click_context is null. This usually happens within minutes. A click can reach the API after its conversion, so the join can take up to 48 hours. If the click is unknown, the conversion never gets a context and you get no such event.

If you need the context and you did not get the event, call GET /v1/conversions/{id}. It always shows the current click_context.

The headers

Each request has these headers:

HeaderValue
webhook-idThe event ID. It is the same for each retry.
webhook-timestampThe time of this attempt, in seconds since 1970.
webhook-signaturev1,<signature>. The signature is the base64 text of the HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<body>.

The key of the HMAC is the secret without the prefix whsec_, decoded from base64. Use the raw body of the request. Do not parse the body and write it again.

After you rotate the secret, the header has two signatures, separated by a space. Accept the request when one of them is correct.

Verify the signature

Do these steps in your receiver:

  1. Read the raw body.
  2. Check that webhook-timestamp is not older than 5 minutes. This stops a replay of an old request.
  3. Calculate the signature with your secret.
  4. Compare it with each signature of the header. Use a constant-time comparison.
  5. If no signature is correct, answer 400.

Node.js

import { createHmac, timingSafeEqual } from "node:crypto";

export function verify(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const header = headers["webhook-signature"];
  if (!id || !timestamp || !header) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();

  return header.split(" ").some((part) => {
    const [version, signature] = part.split(",");
    if (version !== "v1" || !signature) return false;
    const received = Buffer.from(signature, "base64");
    return received.length === expected.length && timingSafeEqual(received, expected);
  });
}

Python

import base64, hashlib, hmac, time

def verify(secret: str, headers: dict, raw_body: bytes) -> bool:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    header = headers.get("webhook-signature")
    if not (msg_id and timestamp and header):
        return False
    if abs(time.time() - int(timestamp)) > 300:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()

    for part in header.split(" "):
        version, _, signature = part.partition(",")
        if version == "v1" and hmac.compare_digest(base64.b64decode(signature), expected):
            return True
    return False

PHP

function verify(string $secret, array $headers, string $rawBody): bool
{
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $header = $headers['webhook-signature'] ?? '';
    if ($id === '' || $timestamp === '' || $header === '') {
        return false;
    }
    if (abs(time() - (int) $timestamp) > 300) {
        return false;
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
    $expected = hash_hmac('sha256', "$id.$timestamp.$rawBody", $key, true);

    foreach (explode(' ', $header) as $part) {
        [$version, $signature] = array_pad(explode(',', $part, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, base64_decode($signature))) {
            return true;
        }
    }
    return false;
}

Go

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"math"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func Verify(secret string, h http.Header, rawBody []byte) bool {
	id := h.Get("webhook-id")
	timestamp := h.Get("webhook-timestamp")
	header := h.Get("webhook-signature")
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if id == "" || header == "" || err != nil {
		return false
	}
	if math.Abs(float64(time.Now().Unix()-seconds)) > 300 {
		return false
	}

	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + timestamp + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)

	for _, part := range strings.Split(header, " ") {
		version, signature, _ := strings.Cut(part, ",")
		received, err := base64.StdEncoding.DecodeString(signature)
		if version == "v1" && err == nil && hmac.Equal(received, expected) {
			return true
		}
	}
	return false
}

Answer the request

Answer with a 2xx status code in 10 seconds. Do the slow work after you answer. The API does not follow redirects. A 3xx answer is a failed attempt. The API reads 1024 bytes of your response at most.

Retries

A failed attempt is a status code other than 2xx, a timeout or a refused connection. The API tries again after 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, and then 14 hours (four times). The API makes 11 attempts in about 73 hours.

The API disables an endpoint when the series of failures since the last success has at least 10 failed attempts and starts at least 72 hours ago. The status of the endpoint is then disabled and disabled_reason is failures. The owners and admins get an email. Enable the endpoint again with PATCH /v1/webhook_endpoints/{id} and "status": "enabled".

Test and replay

  • POST /v1/webhook_endpoints/{id}/test sends a test event (webhook_endpoint.test) now. The response shows the answer of your server. A test send does not retry.
  • GET /v1/webhook_endpoints/{id}/deliveries lists the deliveries with each attempt. The API keeps them for 30 days.
  • POST /v1/webhook_endpoints/{id}/deliveries/{delivery_id}/retry sends the same event again. The new request has a new timestamp and a new signature.
  • In test mode, POST /v1/test/conversions makes a conversion, and POST /v1/test/conversions/{id}/status changes its status. Use them to get real events. See Test mode.

Rotate the secret

POST /v1/webhook_endpoints/{id}/rotate makes a new secret. The new secret signs all new requests. The old secret also signs for 24 hours. Update your receiver in this time. Your receiver then accepts the requests with the old and with the new secret.

On this page