Server-side tracking

Let your own server store the affiliate click and report the sale – so tracking holds up on iPhone, in Safari and with ad blockers.

View as Markdown

On a custom-built store, your own server can take over the two most important jobs from the script: storing the affiliate click and reporting the sale. You can use it in two ways: on its own, as your route for the sale with no script on the pages, or together with the script, as the most robust setup you can have. The snippets are also in Program → Setup with your store ID filled in – on the server route as steps in the setup, otherwise under For developers: even more precise tracking. Here, DIN_BUTIK stands in for it.

Why

  • Safari and iPhone. Safari deletes cookies and localStorage set by JavaScript after about 7 days without a visit to the site. A customer who clicks today and buys in two weeks is lost – even if the program's cookie period is 30 days. A cookie set by your own server isn't shortened in that way.
  • Ad blockers. A blocker can stop a tracking script and its requests. It can't stop your own server from setting a cookie or reporting a paid order.
  • The order confirmation. When the server reports the sale, it doesn't matter whether the customer ever sees the confirmation page – for example if the payment is confirmed later, or the customer closes the tab.

If you already have the script and the sale line, they can stay where they are. See How it works with the script.

Only from your server – no script

The server route can be used on its own. Then you need neither a script on the pages nor a line on the order confirmation: your server stores the click and reports the sale once the order is paid – also when the payment is only confirmed later. Refunds are reported the same way.

  1. Open Program → Setup and choose Custom-built store (or Other) under Where do you sell?.
  2. Press Use the server route next to From your server (API) – or choose From your server (API) under How the sale is reported.
  3. The setup shows three steps: create an API key, the click from your server and the sale from your server, with the snippets for Laravel, PHP, Node.js or Next.js and your store ID filled in. If you wait for consent, the script on every page is added as a fourth step. There is also a ready-made prompt for your AI coding assistant, and Send to developer emails it all.

Tracking runs – and the program becomes visible to affiliates – once your server has reported the first sale or test purchase with a click and the API key. Until then, Setup shows Waiting for the first sale from your server. See Test tracking.

  • Without the script we don't measure whether customers land on your site, so Tracking coverage in Setup has no numbers. If you want it, you can add the script to every page on top – it never overwrites the cookie your server has set, and the same order only counts once.
  • If you have a cookie banner that waits for consent, the script is required – on the server route too. When a customer lands from an affiliate link, the banner has not been answered yet, so your server must not store the click. The script stores it on a yes, and your server takes over the cookie afterwards. See Waiting for consent.

Many shops on the same platform

If you run several webshops on the same system, each shop has its own store in Affilyflow, with its own store ID, API key, program and invoice. The code is built once in the platform and picks the store ID and key from the shop the customer and the order belong to.

  • Each shop is created as a store with Add store in the store switcher – or Affilyflow can create many at once from a list of names and web addresses. Store list appears in the store switcher once the account has at least two stores, and there you can create a key for every store in one go. The keys are shown with each store's ID, and you can download them as CSV. Put them in the server configuration, for example as a table from shop to store ID and key, never in the code.
  • The click is stored on the domain of the shop the customer lands on. In the snippets below, DIN_BUTIK is that shop's store ID.
  • The sale and refund functions take the shop's store ID and key in the call, store and apiKey – in PHP for example affilyflow_sale(…, store: $shop->affilyflow_id, apiKey: $shop->affilyflow_key). Without them, the store ID at the top of the code and the key from the environment are used.
  • Each store becomes visible to affiliates once its server has reported a sale with a click – that proves both the click and the sale work in that very shop. A test sale with "test": true and no click only proves the key works.

Prove all shops in one go. It doesn't take a real purchase in every shop – only a test click and a sale from the server:

  1. Switch to the shop in the store switcher, go to Test tracking in Setup and press Open test link. You land on the shop's own domain with ?afid=, and the shop's click code stores af_click.
  2. Place a test order in the same browser – or let your server report a sale for the shop with the test link's afid as an ordinary sale (without "test": true). The test link makes it a test sale by itself: it shows with a test label, costs nothing and isn't counted.
  3. Repeat for each shop. The live test in Setup shows the click and the sale, and the shop shows Tracking is running.

With "test": true the afid is ignored, so such a call doesn't prove the click. See Test mode.

The click from your server

A small middleware stores ?afid= from the affiliate link as first-party cookies on your domain:

CookieContents
af_clickThe click ID from ?afid=
af_tWhen the click happened, in seconds
af_storeYour store ID
af_srv1 – tells the script that your server set the cookie
  • The cookies last 90 days from the click. On a return visit they are renewed with the time that's left – never beyond 90 days from the click, because the time of the click is in af_t. The program's own cookie period is still enforced on our server.
  • Only an afid that looks like ours (c_ followed by 4–64 characters: letters, digits, _ and -) is stored. If it is missing, the alias afy with the same value is used – some ad-blocker filter lists remove afid on every site.
  • Only when the page is opened as a whole page. If another site embeds your store hidden in an iframe, as an image or from a script to plant a click, the browser says so itself in the Sec-Fetch-Dest header, and nothing is stored. Browsers without the header are handled as before.
  • The cookies must not be HttpOnly: track.js reads them on the order confirmation.
  • Run the code on every page before any output is sent, so the click is stored whichever page the customer lands on.
  • Laravel encrypts cookies by default. Exclude the four cookies as shown at the bottom of the Laravel snippet – otherwise track.js can't read them.
  • If customers land on a different host name from the one they pay on – for example www.shop.dk and shop.dk or checkout.shop.dk – set AF_COOKIE_DOMAIN at the top of the snippet to your domain, for example '.shop.dk'. If you also have the script on your pages, give it the same domain with data-cookie-domain, so the two agree. Otherwise the cookies only apply on the host name the customer landed on.
  • Next.js 16 calls the file proxy.ts and the function proxy. In Next.js 15 and older they are called middleware.ts and middleware.
  • Is the site on a platform where you can't put code on the server, but with its DNS at Cloudflare? Then a Cloudflare Worker can set the same cookies from your own host.
PHP
<?php
// Affilyflow: gem affiliate-klikket fra jeres egen server, så det holder i hele perioden –
// også på iPhone/Safari og med annonceblokkere. Kald affilyflow_click() på hver side,
// før der sendes output. Cookierne må IKKE være HttpOnly (track.js læser dem).

// Lander kunden på www.shop.dk og betaler på shop.dk eller checkout.shop.dk? Så sæt domænet her –
// og samme domæne i scriptets data-cookie-domain, hvis det også ligger på siderne.
const AF_COOKIE_DOMAIN = null; // fx '.shop.dk'

function affilyflow_click(): void {
    $max = 90 * 86400;
    $set = function (string $name, string $value, int $expires): void {
        setcookie($name, $value, [
            'expires' => $expires, 'path' => '/', 'samesite' => 'Lax',
            'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
        ] + (AF_COOKIE_DOMAIN ? ['domain' => AF_COOKIE_DOMAIN] : []));
    };
    // afid, ellers aliasset afy (samme klik-id) – en filterliste fjerner afid på alle sider.
    $afid = (string) ($_GET['afid'] ?? '');
    if (!preg_match('/^c_[A-Za-z0-9_-]{4,64}$/', $afid)) $afid = (string) ($_GET['afy'] ?? '');
    // Kun når siden åbnes som hel side – aldrig i en iframe, som billede eller fra et script.
    $dest = (string) ($_SERVER['HTTP_SEC_FETCH_DEST'] ?? 'document');
    if (preg_match('/^c_[A-Za-z0-9_-]{4,64}$/', $afid) && $dest === 'document') {
        // Nyt klik fra et affiliate-link.
        foreach (['af_click' => $afid, 'af_t' => (string) time(), 'af_store' => 'DIN_BUTIK', 'af_srv' => '1'] as $k => $v) $set($k, $v, time() + $max);
        return;
    }
    // Genbesøg: forny cookien – men aldrig ud over 90 dage fra klikket.
    $click = (string) ($_COOKIE['af_click'] ?? '');
    $t = (int) ($_COOKIE['af_t'] ?? 0);
    $left = $max - (time() - $t);
    if ($t > 0 && $left > 0 && preg_match('/^c_[A-Za-z0-9_-]{4,64}$/', $click)) {
        foreach (['af_click' => $click, 'af_t' => (string) $t, 'af_store' => 'DIN_BUTIK', 'af_srv' => '1'] as $k => $v) $set($k, $v, time() + $left);
    }
}

// Laravel: kald den i en middleware (app/Http/Middleware/AffilyflowClick.php) …
//   public function handle($request, \Closure $next) { affilyflow_click(); return $next($request); }
// … og undtag cookierne fra Laravels kryptering i bootstrap/app.php:
//   ->withMiddleware(function ($middleware) {
//       $middleware->encryptCookies(except: ['af_click', 'af_t', 'af_store', 'af_srv']);
//       $middleware->web(append: [\App\Http\Middleware\AffilyflowClick::class]);
//   })

If Cookie banner is set to Wait for consent in Setup – it is also chosen when the scan finds Cookiebot or Cookie Information – the snippets in Setup get an extra function that reads the customer's choice from the banner's cookie:

  • Yes to marketing: the click is stored and renewed as described above.
  • An active no: nothing is stored, and a click that is already stored is deleted.
  • No answer yet: nothing is stored.

When a customer lands from an affiliate link, the banner has not been answered yet – so your server can't store the click on that page. That's why the script is required on every page when you wait for consent, on the server route too. It keeps ?afid= without storing anything, stores the click once the customer says yes, and on the next page your server takes over the cookie (af_srv=1), so Safari can't shorten it. Setup shows the script as its own step. Without the script, the click is lost for every new customer.

If you use a different banner, adapt the function to yours. See Consent and cookies.

The sale from your server

The sale is reported with your store's API key, so it shows as Confirmed by server in your dashboard – and nobody can send a sale in your name from a browser.

  1. Create an API key under Settings → API keys in the store dashboard. It is shown once. Put it in the environment variable AFFILYFLOW_API_KEY on your server – never in code, in the browser or in git.
  2. At checkout – while it's the customer's own browser calling you – store the value of the af_click cookie on the order, for example in an affilyflow_click column.
  3. When the order is paid – for example in the payment callback or webhook – report the order to the store API. If it is refunded later, in full or in part, report the refund the same way. Save the answer on the order – see When Affilyflow doesn't answer below.
PHP
<?php
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
// Affilyflow (DIN_BUTIK): meld salget fra jeres server, når ordren er BETALT – med jeres API-nøgle,
// så salget står som "Bekræftet af server". Opret nøglen under Indstillinger → API-nøgler, og læg
// den på serveren – aldrig i koden eller i git:
//      .env:                 AFFILYFLOW_API_KEY=afs_…
//      config/services.php:  'affilyflow' => ['key' => env('AFFILYFLOW_API_KEY')],
// 1) Ved checkout (kundens egen browser): gem klikket på ordren, fx i en kolonne affilyflow_click:
//      $order->affilyflow_click = $_COOKIE['af_click'] ?? null;
// 2) Når betalingen er bekræftet (fx i betalings-callbacken), læg meldingen i køen. Svarer
//    Affilyflow ikke, prøver køen igen i op til 72 timer (kræver en kø – ikke QUEUE_CONNECTION=sync):
//      AffilyflowReport::dispatch('sale', ['orderId' => $order->number, 'goodsExVat' => …,
//          'currency' => 'DKK', 'click' => $order->affilyflow_click, 'coupons' => […], 'email' => …,
//          'items' => […]]); // varelinjerne er valgfrie – se affilyflow_items() nederst
//    Ordrenummeret er Idempotency-Key, så et nyt forsøg tæller aldrig to gange.
// 3) Refunderes en meldt ordre helt eller delvist: AffilyflowReport::dispatch('refund', ['orderId' => …]);
// Læg koden i fx app/affilyflow.php, og indlæs den i composer.json under "autoload": {"files": […]},
// så både web og kø-worker kender funktionerne og jobbet.
// Flere shops på samme platform: giv shoppens butiks-id og API-nøgle med (store og apiKey).
const AFFILYFLOW_STORE = 'DIN_BUTIK'; // jeres butiks-id

function affilyflow_sale(string $orderId, float $goodsExVat, string $currency, ?string $click, ?array $coupons = [], ?string $email = null, ?\DateTimeInterface $placedAt = null, ?string $store = null, ?string $apiKey = null, ?array $items = null, ?string $subscriptionId = null, bool $renewal = false, ?string $period = null, ?string $leadId = null): string {
    // Kun personlige rabatkoder sendes med – en generel kode forlader aldrig jeres server.
    $codes = $renewal ? [] : affilyflow_personal_codes($coupons ?? [], $store ?? AFFILYFLOW_STORE);
    if (!$renewal && !$click && $codes === null) return 'retry'; // listen over personlige koder kunne ikke hentes
    // Uden klik, personlig rabatkode og lead er der intet at melde. En fornyelse finder affiliaten selv.
    if (!$renewal && !$click && !$codes && !$leadId) return 'skipped';
    $body = array_filter([
        'afid'         => $click,                 // klik-id'et fra ordren
        'order'        => $orderId,               // samme ordrenummer som kunden ser
        'total'        => round($goodsExVat, 2),  // varerne efter rabat, UDEN moms og fragt
        'currency'     => $currency,              // fx DKK
        'coupons'      => $codes ?? [],           // kun personlige rabatkoder (giver provision, også uden klik)
        // Fingeraftryk af e-mailen, så selvhenvisning kan afvises. E-mailen selv sendes aldrig.
        'buyer_hash'   => $email ? hash('sha256', strtolower(trim($email))) : null,
        'buyer_hash_n' => $email ? affilyflow_buyer_hash_n($email) : null, // samme, normaliseret
        // Hvornår ordren blev lagt: cookie-perioden måles derfra, også når betalingen kommer senere.
        'order_time'   => $placedAt ? $placedAt->format(DATE_ATOM) : null,
        // Varelinjerne (valgfrit): så ser I og affiliaten, hvilke varer der sælger.
        'items'        => affilyflow_items($items),
        // Abonnementer: første betaling med subscription_id, de næste med renewal = true og samme id.
        'subscription_id' => $subscriptionId,
        'renewal'      => $renewal ? true : null,
        'period'       => $period,                // fx '2026-11' – en fornyelse pr. periode
        'lead_id'      => $leadId,                // salget kom efter dette lead (affilyflow_lead)
    ], fn ($v) => $v !== null && $v !== '' && $v !== []);
    return affilyflow_post('/conversions', $body, $orderId, $apiKey);
}

// Et lead (fx en tilmelding eller en forespørgsel) – kun lead-programmer. $leadId er jeres eget id
// (aldrig en e-mail). Højst ét lead pr. klik, medmindre programmet tillader flere.
function affilyflow_lead(string $leadId, ?string $click, ?array $coupons = [], ?string $email = null, ?float $value = null, ?string $currency = null, ?\DateTimeInterface $occurredAt = null, ?string $store = null, ?string $apiKey = null): string {
    $codes = affilyflow_personal_codes($coupons ?? [], $store ?? AFFILYFLOW_STORE);
    if (!$click && $codes === null) return 'retry';
    if (!$click && !$codes) return 'skipped';
    $body = array_filter([
        'lead_id'      => $leadId,
        'afid'         => $click,
        'coupons'      => $codes ?? [],
        'value'        => $value !== null ? round($value, 2) : null, // valgfri anslået værdi
        'currency'     => $currency,
        'buyer_hash'   => $email ? hash('sha256', strtolower(trim($email))) : null,
        'buyer_hash_n' => $email ? affilyflow_buyer_hash_n($email) : null,
        'occurred_at'  => $occurredAt ? $occurredAt->format(DATE_ATOM) : null,
    ], fn ($v) => $v !== null && $v !== '' && $v !== []);
    return affilyflow_post('/leads', $body, 'lead-' . $leadId, $apiKey);
}

// E-mailen normaliseret, før den hashes: små bogstaver, +tag fjernes, og for Gmail også punktummer,
// så a.b+shop@gmail.com og ab@gmail.com giver samme fingeraftryk.
function affilyflow_buyer_hash_n(string $email): ?string {
    $e = mb_strtolower(trim($email), 'UTF-8');
    $at = strrpos($e, '@');
    if ($at === false) return null;
    $local = explode('+', substr($e, 0, $at), 2)[0];
    $domain = substr($e, $at + 1);
    if ($domain === 'gmail.com' || $domain === 'googlemail.com') {
        $local = str_replace('.', '', $local);
        $domain = 'gmail.com';
    }
    return $local !== '' && $domain !== '' ? hash('sha256', $local . '@' . $domain) : null;
}

// Varelinjer: [['product_id' => 'SKU-1', 'title' => 'Varens navn', 'qty' => 2, 'price' => 199.00,
//               'category' => 'Herre > Sko', 'brand' => 'Mærke'], …]
// price = stykprisen, kunden betalte. product_id = varens id i jeres katalog eller feed. 'name' og
// 'quantity' virker også. category, brand, sku og line_total (linjens beløb efter rabat) er valgfrie –
// de bruges til provision pr. kategori. Højst 50 linjer; en linje uden navn springes over.
function affilyflow_items(?array $items): array {
    $out = [];
    foreach (array_slice($items ?? [], 0, 50) as $it) {
        if (!is_array($it)) continue;
        $title = trim((string) ($it['title'] ?? $it['name'] ?? ''));
        if ($title === '') continue;
        $out[] = array_filter([
            'product_id' => isset($it['product_id']) ? (string) $it['product_id'] : null,
            'title'      => $title,
            'variant'    => isset($it['variant']) ? (string) $it['variant'] : null,
            'qty'        => max(1, (int) ($it['qty'] ?? $it['quantity'] ?? 1)),
            'price'      => isset($it['price']) ? round((float) $it['price'], 2) : null,
            'sku'        => isset($it['sku']) ? (string) $it['sku'] : null,
            'category'   => isset($it['category']) ? (is_array($it['category']) ? implode(' > ', $it['category']) : (string) $it['category']) : null,
            'brand'      => isset($it['brand']) ? (string) $it['brand'] : null,
            'line_total' => isset($it['line_total']) ? round((float) $it['line_total'], 2) : null,
        ], fn ($v) => $v !== null && $v !== '');
    }
    return $out;
}

// Hel refusion: udelad $amount. Delvis: $amount og $orderTotal på samme grundlag (fx begge med moms)
// OG altid $refundId (fx kreditnotaens nummer) – ellers kan to delvise refusioner ikke skelnes.
function affilyflow_refund(string $orderId, ?string $refundId = null, ?float $amount = null, ?float $orderTotal = null, ?string $currency = null, ?string $apiKey = null): string {
    if ($amount !== null && !$refundId) {
        logger()->warning('Affilyflow: delvis refusion af ' . $orderId . ' kræver $refundId');
        return 'rejected';
    }
    $body = array_filter([
        'refund_id' => $refundId, 'amount' => $amount, 'total' => $orderTotal, 'currency' => $currency,
    ], fn ($v) => $v !== null);
    $key = 'refund-' . $orderId . '-' . ($amount === null ? 'full' : $refundId);
    return affilyflow_post('/conversions/' . rawurlencode($orderId) . '/refunds', $body, $key, $apiKey);
}

// Køen prøver igen efter 1, 5 og 15 minutter, 1 og 3 timer – og derefter hver 3. time i op til 72 timer.
// Laravel 10: brug traits Dispatchable, InteractsWithQueue og Queueable i stedet for Queueable alene.
class AffilyflowReport implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $kind, public array $args) {}

    public function backoff(): array
    {
        return [60, 300, 900, 3600, 10800];
    }

    public function retryUntil(): \DateTimeInterface
    {
        return now()->addHours(72);
    }

    public function handle(): void
    {
        $result = match ($this->kind) {
            'refund' => affilyflow_refund(...$this->args),
            'lead' => affilyflow_lead(...$this->args),
            default => affilyflow_sale(...$this->args),
        };
        if ($result === 'retry') $this->release($this->backoff()[min($this->attempts(), 5) - 1]);
    }
}

// Svaret: 'sent', 'rejected' (fejl i data – se loggen) eller 'retry' (prøv igen senere).
function affilyflow_result(int $status): string {
    if ($status >= 200 && $status < 300) return 'sent';
    if ($status >= 400 && $status < 500 && !in_array($status, [404, 409, 429], true)) return 'rejected';
    return 'retry'; // ingen forbindelse, 404 (salget er ikke meldt endnu), 409, 429 og 5xx
}

function affilyflow_post(string $path, array $body, string $idempotencyKey, ?string $apiKey = null): string {
    // To forsøg med 1 sek. imellem – resten klarer køen. Kaster aldrig: en fejl hos Affilyflow må
    // ikke vælte jeres betalings-callback.
    try {
        $res = Http::withToken($apiKey ?? (string) config('services.affilyflow.key'))
            ->withHeaders(['Idempotency-Key' => $idempotencyKey])
            ->timeout(5)
            ->retry(2, 1000, fn ($e) => !$e instanceof \Illuminate\Http\Client\RequestException
                || affilyflow_result($e->response->status()) === 'retry', false)
            ->post('https://app.affilyflow.com/api/v1/store' . $path, $body);
        [$status, $answer] = [$res->status(), $res->body()];
    } catch (\Throwable $e) {
        [$status, $answer] = [0, $e->getMessage()]; // ingen forbindelse eller timeout
    }
    $result = affilyflow_result($status);
    if ($result !== 'sent') logger()->warning("Affilyflow $path: $status $answer ($result)");
    return $result;
}

function affilyflow_code_list(string $store): ?array {
    // Butikkens personlige rabatkoder som sha256-fingeraftryk, cachet i 5 minutter. null = kunne ikke hentes.
    try {
        return Cache::remember('affilyflow_codes_' . $store, 300, function () use ($store) {
            $list = Http::timeout(5)->get('https://app.affilyflow.com/api/track/codes', ['store' => $store])->throw()->json('h');
            if (!is_array($list)) throw new \RuntimeException('Ugyldig kodeliste');
            return $list;
        });
    } catch (\Throwable $e) {
        return null;
    }
}

// Kun koder, hvis fingeraftryk står på butikkens liste. null = listen kunne ikke hentes.
function affilyflow_personal_codes(array $coupons, string $store): ?array {
    $codes = [];
    foreach ($coupons as $c) {
        if (!is_string($c)) continue;
        // Samme form som hos Affilyflow: uden mellemrum, store bogstaver, højst 64 tegn.
        $c = preg_replace('/\s+/u', '', $c) ?? '';
        $c = function_exists('mb_strtoupper') ? mb_substr(mb_strtoupper($c, 'UTF-8'), 0, 64, 'UTF-8') : substr(strtoupper($c), 0, 64);
        if ($c !== '' && !in_array($c, $codes, true)) $codes[] = $c;
    }
    if (!$codes) return [];
    $list = affilyflow_code_list($store);
    if ($list === null) return null;
    return array_values(array_filter($codes, fn ($c) => in_array(hash('sha256', $c), $list, true)));
}

The fields

The sale is a POST with JSON to https://app.affilyflow.com/api/v1/store/conversions with Authorization: Bearer <your key> and Idempotency-Key: <order number>. The key decides the store, so store is not sent.

FieldRequiredMeaning
orderYesThe order number as the customer sees it. The same number is only counted once.
totalYesThe goods after discount, excluding VAT and shipping, as a machine number (540.00).
currencyYesCurrency code, e.g. DKK or EUR.
afidWhen there is a clickThe click ID you stored on the order at checkout.
couponsNoOnly the customer's personal discount codes as a list, e.g. ["ANNA10"]. They earn commission – even without a click. The snippets first compare the customer's codes with your list of fingerprints (SHA-256), so a general code never leaves your server.
buyer_hashRecommendedsha256 of the buyer's email in lower case, with no leading or trailing spaces. Used only to reject self-referrals. The email itself is never sent.
buyer_hash_nRecommendedThe same fingerprint of the normalised email (+tag removed, and for Gmail the dots too), so the same mailbox written differently is recognised. The rule is in Buyer fingerprint.
order_timeRecommendedWhen the order was placed (ISO 8601). The cookie period is measured from it, so a payment confirmed the next day still counts. At most 180 days old.
itemsNoThe order lines: product_id, title, qty and price (the unit price the customer paid), at most 50. The snippets also take name and quantity. With product_id as in your product feed, Products shows which items affiliates sell.
  • With no click and no personal discount code there is nothing to report – the snippets skip the call. An order with a general code or no code at all never leaves your server.
  • The snippets never throw an error into your code, and they log errors instead of swallowing them. Never let the call decide whether the order goes through – call it once the order is saved as paid.
  • affilyflow_refund / affilyflowRefund reports a refund: leave out the amount for a full refund. For a partial refund, send the amount, the order total on the same basis and always your refund ID, for example the credit note number – without it the refund isn't sent, because two partial refunds could not be told apart. Only report refunds of orders marked sent. If a refund still arrives before the sale, we answer 404 and the snippets answer retry – it is then sent again with the others once the sale has been reported.
  • All fields, responses and errors are in Conversion API.

When Affilyflow doesn't answer

The functions answer with one of four words, which you save on the order, for example in an affilyflow_status column:

AnswerMeaning
sentReported.
skippedNothing to report: neither a click nor a personal discount code.
rejectedRejected, for example an expired click or an invalid field. The reason is in your log, and trying again won't help.
retryNo answer, 404 (the order hasn't been reported yet – for example a refund that came before the sale), 409, 429 or 5xx. Try again later.

In the call itself, the snippets try at most twice, one second apart, so checkout and the payment callback are never held up. You handle the rest outside the call:

  • PHP, Node.js and Next.js: let a cron job call affilyflow_sale / affilyflowSale again every 10–15 minutes for paid orders marked retry – for up to 72 hours – and save the new answer.
  • Laravel: put the report on the queue with AffilyflowReport::dispatch(…). The job tries again after 1, 5 and 15 minutes, 1 and 3 hours, and then every 3 hours for up to 72 hours. It needs a real queue, not QUEUE_CONNECTION=sync.

The order number is the Idempotency-Key, so a retry never counts twice, and with order_time the cookie period is still measured from the order, even when the report arrives later.

Your own proxy (optional)

If you also want the script and its requests off our domain, your web server can forward everything under /af/ to Affilyflow. The script is then loaded from /af/t/DIN_BUTIK.js on your own domain, and because the script sends its requests to the folder it was loaded from, they go through your domain too. An ad blocker only sees your own addresses.

It's the same script as before, with your settings from Setup. Afterwards, replace the script in <head> with the line at the bottom of the snippet. The proxy doesn't pass your customers' cookies on to us – we don't need them. If your domain has its DNS at Cloudflare, the Cloudflare Worker can be the proxy too.

Tekst
# nginx: alt under /af/ sendes videre til Affilyflow
location /af/ {
    proxy_pass https://app.affilyflow.com/;
    proxy_set_header Host app.affilyflow.com;
    proxy_ssl_server_name on;
    # Jeres kunders cookies sendes ikke med.
    proxy_set_header Cookie "";
}

<!-- Scriptet hentes nu fra jeres eget domæne (alle sider, i <head>) -->
<script src="/af/t/DIN_BUTIK.js" async></script>

The customer's IP address. Behind a proxy, every request comes from your server, so our abuse protection, which counts per IP address, sees the whole store as one visitor. X-Forwarded-For doesn't help – it is overwritten on the way to prevent spoofing. If the snippet in Setup shows a proxy key, the proxy therefore sends two more lines: X-Affilyflow-Proxy with the key and X-Affilyflow-Client-IP with the customer's address. We only use the address when the key matches your store, and only for the script and its requests – never for login or the API. The address is never stored; it becomes a key that changes every day and is only used for counting. With Next.js, the proxy then becomes a route handler instead of a rewrite, because a rewrite can't set headers.

Your settings from Setup (Google Analytics, VAT, shipping, consent) come along, because our server adds them to the script. The older proxy line <script src="/af/s.js" data-store="DIN_BUTIK" async></script> still works – if you use it, keep its attributes such as data-consent and data-sale.

How it works with the script

  • The script can stay. Once your server has set the cookie, af_srv=1 is present, and track.js never writes af_click or af_t again – Safari would shorten a cookie written by JavaScript to about 7 days, even if your server set it first. The script still keeps the click in localStorage as a fallback.
  • The same order only counts once. If both your server and the browser (the script or the sale line) report the same order with the same order number, the sale is recorded once. The browser report can stay in place as a fallback – when your server reports the same order with its key, the sale is marked Confirmed by server.
  • The click comes along. The script reads af_click whether your server or the script set it, so the sale line on the order confirmation works as before.
  • A no removes everything. If a customer actively declines marketing in a banner the script waits for (Wait for consent), or you call affilyflow.consent(false), the script also deletes the cookies your server set. The server code with the consent function deletes them on a no as well. Don't set them again without consent.

Test tracking

  1. Go to the Test tracking step in Setup, press Open test link, and place a test order in the same browser. Pay for it, so your server reports the purchase.
  2. The live test shows the test click and the purchase with order number and amount – on the server route with reported by your server. Check that the amount is the goods after discount, excluding VAT and shipping.
  3. In the browser's developer tools, check that the af_click, af_t, af_store and af_srv cookies are set on your domain after the test link.

On the server route, Setup doesn't check the homepage for a script – the status changes from Waiting for the first sale from your server to Tracking is running as soon as the test purchase is reported. If the purchase doesn't come through, check that the click is saved on the order at checkout, that the key is in AFFILYFLOW_API_KEY, and what your log says Affilyflow replied.

With the script on the pages, Tracking coverage in Setup then shows how many affiliate clicks arrive, are stored and turn into a sale. More in Testing and troubleshooting.

Missing something?

Write to us – we answer quickly, and the page gets fixed.

Contact support