InstallPeak
Pricing Solutions Developer Docs Contact Support Sign In / Dashboard
Developer & Attribution Reference

Attribution SDK, S2S Postbacks & Wholesale API v2

Every Qualified Redirects campaign launches with zero code and includes optional free S2S postback tracking. Use this production reference for Extension MV3 bridges, Telegram HMAC verification, Android Play Referrer / MMPs, iOS AdAttributionKit windows, /pb/ev status contracts, and idempotent Wholesale API v2.

SECTION 01

Browser Extensions (MV3) — First-Party Same-Origin Bridge & /sdk/v1.js

Requirements (Same-Origin, JSON Parser & Node 18+): /lp, /welcome, and POST /api/install-hook MUST share the exact same origin (scheme + host + port) so first-party cookies and localStorage remain readable across steps. Your backend requires Node 18+ (built-in fetch) and express.json(). NEVER expose &tok= in browser HTML.
1a. First-Party Bridge Landing Page (https://your-domain.com/lp)

Set your campaign destination URL to https://your-domain.com/lp (our router appends ?dr_cid=<cid>, sanitized to [A-Za-z0-9_-]{6,48}). /sdk/v1.js with data-capture-only="1" persists dr_cid with a 7-day TTL in both 1st-party cookie (Max-Age=604800) and localStorage before redirecting to Chrome Web Store:

<!-- https://your-domain.com/lp -->
<script src="https://installpeak.com/sdk/v1.js" data-order="YOUR_ORDER_CODE" data-capture-only="1"></script>
<script>
  location.replace("https://chromewebstore.google.com/detail/your-extension/YOUR_32_CHAR_ID");
</script>
1b. background.js (Manifest V3 — fires only on fresh install)
// background.js (Manifest V3)
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === "install") {
    chrome.tabs.create({ url: "https://your-domain.com/welcome" });
  }
});
1c. welcome.html (https://your-domain.com/welcome — ZERO secrets in HTML; marks sent ONLY after 2xx/409)
<!-- https://your-domain.com/welcome (same origin as /lp and /api/install-hook) -->
<script async src="https://installpeak.com/sdk/v1.js"
  data-order="YOUR_ORDER_CODE"
  data-endpoint="/api/install-hook"></script>
1d. backend/install-hook.js (Node 18+ Express — pins ORDER &amp; TOK server-side, propagates 502/503 on failure for safe SDK retry)
// backend/install-hook.js (Node 18+, Express)
import express from "express";
const app = express();
app.use(express.json());

app.post("/api/install-hook", async (req, res) => {
  const cid = String(req.body?.cid || "").trim();
  if (!/^[A-Za-z0-9_-]{6,48}$/.test(cid)) {
    return res.status(400).json({ ok: false, error: "Invalid cid" });
  }
  // Pin ORDER_CODE and S2S_TOKEN strictly from server env (NEVER blindly trust req.body.order!)
  const orderCode = process.env.INSTALLPEAK_ORDER;
  const s2sToken = process.env.INSTALLPEAK_TOK;
  if (!orderCode || !s2sToken) return res.status(500).json({ ok: false });

  try {
    const qs = new URLSearchParams({ o: orderCode, cid, e: "install", tok: s2sToken });
    const pb = await fetch("https://installpeak.com/pb/ev?" + qs.toString(), {
      method: "GET",
      signal: AbortSignal.timeout(5000),
    });
    if (pb.ok || pb.status === 409) {
      // 200 confirmed or 409 already converted -> safe for /sdk/v1.js to mark dr_sent=1 & clear dr_cid
      return res.status(pb.status === 409 ? 409 : 200).json({ ok: true, duplicate: pb.status === 409 });
    }
    if (pb.status === 403 || pb.status === 404 || pb.status === 410) {
      return res.status(pb.status).json({ ok: false, permanent: true });
    }
    // Upstream 5xx/429 -> return 502 so /sdk/v1.js does NOT set dr_sent and can retry cleanly
    return res.status(502).json({ ok: false, retryable: true });
  } catch (err) {
    return res.status(503).json({ ok: false, retryable: true });
  }
});
Attribution Reliability & Compliance Note: A welcome-page ping is a lightweight install signal ideal for Qualified Redirects analytics; Managed S2S CPA ($500+) campaigns may require additional active-extension qualification events agreed in the SOW. Custom HTTPS pre-landers pass automated link compliance review and start in an isolated pool until verified — always complete the 1-Click TEST_ handshake in your Order Portal before funding live CPA volume.
SECTION 02

Telegram Bots (?start=cid_) & Mini Apps (?startapp=cid_ + HMAC initData)

Platform Limits vs. InstallPeak Convention: Telegram restricts Bot ?start= payloads to 64 characters ([A-Za-z0-9_-], no =), while Mini App ?startapp= allows up to 512 characters in ecosystem docs. To stay universally safe across both, InstallPeak generates compact CIDs (<=36 chars) and recommends validating full payloads with /^(?:.+__)?cid_([A-Za-z0-9_-]{6,48})$/.

2a. Runnable SQL Schema (First-Ever User vs. Per-Order Attribution Dedup)

bot_users tracks whether a Telegram user is brand-new to your bot (isNewUser), while tg_attributed_users enforces atomic per-order deduplication with explicit postback state (pending / confirmed / failed_permanent). NEVER delete the dedup row on HTTP 409!

-- Standard SQL schema (PostgreSQL / relational DB compatible)
CREATE TABLE IF NOT EXISTS bot_users (
  tg_user_id TEXT PRIMARY KEY,
  first_seen_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS tg_attributed_users (
  tg_user_id TEXT NOT NULL,
  order_code TEXT NOT NULL,
  click_id   TEXT NOT NULL,
  pb_status  TEXT NOT NULL DEFAULT 'pending', -- pending | confirmed | failed_permanent
  attempts   INTEGER NOT NULL DEFAULT 0,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (tg_user_id, order_code)
);
2b. Node.js Bot & Mini App — HMAC-SHA256 initData (auth_date <= 300s) + Status-Safe Postback Handler
import crypto from "node:crypto";

const CID_PAYLOAD_RE = /^(?:.+__)?cid_([A-Za-z0-9_-]{6,48})$/;

function verifyTelegramInitData(rawInitData, botToken, maxAgeSec = 300) {
  const params = new URLSearchParams(rawInitData);
  const hash = params.get("hash") || "";
  params.delete("hash");
  const checkStr = [...params.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => k + "=" + v).join("\n");
  const secretKey = crypto.createHmac("sha256", "WebAppData").update(botToken).digest();
  const calc = crypto.createHmac("sha256", secretKey).update(checkStr).digest("hex");
  if (!hash || hash.length !== calc.length || !crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(calc))) return null;
  const authDate = Number(params.get("auth_date") || 0);
  if (!authDate || Math.abs(Math.floor(Date.now() / 1000) - authDate) > maxAgeSec) return null;
  return Object.fromEntries(params.entries());
}

// Explicit isNewUser check (first-ever bot user) + per-order dedup + status-safe /pb/ev delivery
async function attributeTelegramStart(db, tgUserId, rawPayload, orderCode, orderTok) {
  const m = String(rawPayload || "").trim().match(CID_PAYLOAD_RE);
  if (!tgUserId || !m) return { attributed: false };
  const cid = m[1];

  // 1. Atomic transaction: check first-ever bot user & reserve per-order dedup row as 'pending'
  const reserved = await db.transaction(async (tx) => {
    const newUserRes = await tx.query(
      "INSERT INTO bot_users (tg_user_id) VALUES ($1) ON CONFLICT (tg_user_id) DO NOTHING",
      [tgUserId]
    );
    const isNewUser = newUserRes.rowCount === 1;
    if (!isNewUser) return false; // Existing bot user — skip acquisition credit
    const ins = await tx.query(
      "INSERT INTO tg_attributed_users (tg_user_id, order_code, click_id, pb_status) VALUES ($1, $2, $3, 'pending') ON CONFLICT (tg_user_id, order_code) DO NOTHING",
      [tgUserId, orderCode, cid]
    );
    return ins.rowCount === 1;
  });
  if (!reserved) return { attributed: false };

  // 2. Deliver S2S postback and transition pb_status by HTTP code (NEVER delete on 409!)
  try {
    const qs = new URLSearchParams({ o: orderCode, cid, e: "install", tok: orderTok });
    const resp = await fetch("https://installpeak.com/pb/ev?" + qs.toString(), { signal: AbortSignal.timeout(5000) });
    if (resp.ok || resp.status === 409) {
      await db.query(
        "UPDATE tg_attributed_users SET pb_status = 'confirmed', attempts = attempts + 1, updated_at = CURRENT_TIMESTAMP WHERE tg_user_id = $1 AND order_code = $2",
        [tgUserId, orderCode]
      );
      return { attributed: true, duplicate: resp.status === 409 };
    }
    if (resp.status === 403 || resp.status === 404 || resp.status === 410) {
      await db.query(
        "UPDATE tg_attributed_users SET pb_status = 'failed_permanent', attempts = attempts + 1, updated_at = CURRENT_TIMESTAMP WHERE tg_user_id = $1 AND order_code = $2",
        [tgUserId, orderCode]
      );
      console.error("[S2S] Permanent failure status=" + resp.status + " order=" + orderCode); // NEVER log orderTok!
      return { attributed: false, permanent: true };
    }
    // 429 or 5xx -> keep pb_status = 'pending' for bounded background worker retry
    await db.query(
      "UPDATE tg_attributed_users SET attempts = attempts + 1, updated_at = CURRENT_TIMESTAMP WHERE tg_user_id = $1 AND order_code = $2",
      [tgUserId, orderCode]
    );
  } catch (err) {
    // Network timeout -> keep pb_status = 'pending' for bounded retry
    await db.query(
      "UPDATE tg_attributed_users SET attempts = attempts + 1, updated_at = CURRENT_TIMESTAMP WHERE tg_user_id = $1 AND order_code = $2",
      [tgUserId, orderCode]
    );
  }
  return { attributed: false, retryPending: true };
}
2c. Python Mini App & Bot — HMAC-SHA256 initData + Explicit Commit & Status-Safe 409/5xx Handling
import hashlib, hmac, json, re, time, requests
from urllib.parse import parse_qsl

CID_PAYLOAD_RE = re.compile(r"^(?:.+__)?cid_([A-Za-z0-9_-]{6,48})$")

def verify_tg_init_data(raw_init_data: str, bot_token: str, max_age_sec: int = 300) -> dict | None:
    pairs = dict(parse_qsl(raw_init_data, keep_blank_values=True))
    got_hash = pairs.pop("hash", "")
    check_str = "\n".join(f"{k}={v}" for k, v in sorted(pairs.items()))
    secret_key = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
    calc = hmac.new(secret_key, check_str.encode(), hashlib.sha256).hexdigest()
    if not got_hash or not hmac.compare_digest(got_hash, calc):
        return None
    auth_date = int(pairs.get("auth_date") or 0)
    if auth_date <= 0 or abs(int(time.time()) - auth_date) > max_age_sec:
        return None
    return pairs

def fire_verified_start(conn, data: dict, order_code: str, order_tok: str):
    tg_user = json.loads(data.get("user") or "{}")
    tg_user_id = str(tg_user.get("id") or "")
    m = CID_PAYLOAD_RE.match((data.get("start_param") or "").strip())
    if not (tg_user_id and m):
        return
    cid = m.group(1)

    with conn:  # Explicit DB transaction & commit
        cur = conn.cursor()
        cur.execute("INSERT INTO bot_users (tg_user_id) VALUES (%s) ON CONFLICT (tg_user_id) DO NOTHING", (tg_user_id,))
        if cur.rowcount != 1:
            return  # Returning user — not a first-ever bot start
        cur.execute(
            "INSERT INTO tg_attributed_users (tg_user_id, order_code, click_id, pb_status) VALUES (%s, %s, %s, 'pending') ON CONFLICT (tg_user_id, order_code) DO NOTHING",
            (tg_user_id, order_code, cid),
        )
        if cur.rowcount != 1:
            return

    try:
        resp = requests.get("https://installpeak.com/pb/ev", params={"o": order_code, "cid": cid, "e": "install", "tok": order_tok}, timeout=5)
        if resp.status_code < 300 or resp.status_code == 409:
            new_status = "confirmed"  # NEVER delete dedup row on 409 duplicate!
        elif resp.status_code in (403, 404, 410):
            new_status = "failed_permanent"  # Alert ops; never log order_tok!
        else:
            new_status = "pending"  # 429 / 5xx -> retry via bounded worker queue
    except requests.RequestException:
        new_status = "pending"  # Network failure -> keep pending for bounded retry

    with conn:
        conn.execute(
            "UPDATE tg_attributed_users SET pb_status = %s, attempts = attempts + 1, updated_at = CURRENT_TIMESTAMP WHERE tg_user_id = %s AND order_code = %s",
            (new_status, tg_user_id, order_code),
        )
SECTION 03

Android Play Install Referrer & Mobile MMPs (Adjust, AppsFlyer, AppMetrica)

Our router replaces {cid} / {click_id} macros on ALL outbound links automatically (without appending extra dr_cid). For clean play.google.com/store/apps/details?id=... URLs without a macro, our router automatically injects referrer=utm_source%3Dinstallpeak%26cid%3D<cid> for Google Play Install Referrer.

3a. Android Kotlin — Google Play InstallReferrerClient (first_open -> Your Backend -> /pb/ev)

Read Play Install Referrer once on first_open, handle organic installs (null/missing cid) gracefully, and deduplicate reinstalls server-side by your stable app/install identifier before calling /pb/ev:

// build.gradle: implementation("com.android.installreferrer:installreferrer:2.2")
import android.content.Context
import android.net.Uri
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener

fun reportPlayReferrerOnce(context: Context, onSendToBackend: (cid: String) -> Unit) {
    val prefs = context.getSharedPreferences("ip_attr", Context.MODE_PRIVATE)
    if (prefs.getBoolean("first_open_sent", false)) return // Guard against repeat launches

    val client = InstallReferrerClient.newBuilder(context).build()
    client.startConnection(object : InstallReferrerStateListener {
        override fun onInstallReferrerSetupFinished(code: Int) {
            try {
                if (code == InstallReferrerClient.InstallReferrerResponse.OK) {
                    val rawRef = client.installReferrer.installReferrer ?: ""
                    val cid = Uri.parse("https://dummy.local/?" + rawRef).getQueryParameter("cid")?.trim()
                    if (!cid.isNullOrEmpty() && Regex("^[A-Za-z0-9_-]{6,48}$").matches(cid)) {
                        // Send cid to YOUR backend (never embed &tok= inside the APK!);
                        // Backend deduplicates reinstalls, fires /pb/ev?...&tok=, then returns 200/409
                        onSendToBackend(cid)
                    }
                    // Mark checked even on organic null-CID installs so Play Referrer isn't re-queried
                    prefs.edit().putBoolean("first_open_sent", true).apply()
                }
            } finally {
                client.endConnection()
            }
        }
        override fun onInstallReferrerServiceDisconnected() { /* Retry on next app launch */ }
    })
}
3b. MMP 2-Way Mapping — Adjust, AppsFlyer & AppMetrica (Outbound + Inbound Callback)
# 1. Adjust (pass click ID in ?label={cid}; configure server callback with cid={label})
Outbound: https://app.adjust.com/YOUR_TRACKER?label={cid}
Callback: https://installpeak.com/pb/ev?o=YOUR_ORDER_CODE&cid={label}&e=install&tok=YOUR_ORDER_TOK

# 2. AppsFlyer (replace <your_media_source> with your own partner/custom pid configured in AppsFlyer)
Outbound: https://app.appsflyer.com/com.example.app?pid=<your_media_source>&af_sub1={cid}
Callback: https://installpeak.com/pb/ev?o=YOUR_ORDER_CODE&cid={af_sub1}&e=install&tok=YOUR_ORDER_TOK

# 3. AppMetrica (2-way: outbound ?click_id={cid} + postback macro {click_id})
# Note: Yandex AppMetrica distinguishes {click_id} (from tracker URL) vs {external_click_id};
# verify which macro your tracker template forwards and note user consent / restricted callbacks.
Outbound: https://redirect.appmetrica.yandex.com/serve/YOUR_TRACKER_ID?click_id={cid}
Callback: https://installpeak.com/pb/ev?o=YOUR_ORDER_CODE&cid={click_id}&e=install&tok=YOUR_ORDER_TOK

# 4. Direct Google Play Store URL (clean URL auto-receives referrer=utm_source%3Dinstallpeak%26cid%3D<cid>,
#    or pass explicit macro below — never appends bogus &dr_cid=)
Outbound: https://play.google.com/store/apps/details?id=com.example.app&referrer=cid%3D{cid}
AppsFlyer & AppMetrica Notes: In AppsFlyer, pid=<your_media_source> depends on your own custom/partner media-source setup (there is no globally pre-configured media source ID). In AppMetrica, confirm your tracker maps click_id vs external_click_id consistently and account for regional user-consent / restricted-callback settings.
SECTION 04

iOS ATT / IDFA vs. AdAttributionKit & Attribution Settlement Windows

iOS 14.5+ ATT / IDFA (Click-Level Only With Consent)

Deterministic 1:1 click-level attribution on iOS is only available when the user explicitly opts in via Apple App Tracking Transparency (ATT) so the MMP can match IDFA. For non-consented users, click-level IDs are unavailable.

iOS / iPadOS 17.4+ AdAttributionKit (Aggregate Cohort Only)

AdAttributionKit / SKAdNetwork delivers privacy-preserving aggregate cohort postbacks subject to Apple crowd-anonymity thresholds and randomized timers. NEVER attempt to infer or reconstruct an individual click_id from cohort postbacks.

Strict Window Separation (24h vs. Apple 24–48h): Our automated 24-hour attribution_review window on /pb/ev applies ONLY to click-level S2S orders (Extensions, Telegram, Android). iOS Managed S2S CPA ($500+) cohort postbacks are NEVER truncated at 24 hours — they settle strictly according to Apple's 24–48h post-conversion-window delivery rules documented in your Managed CPA SOW.
SECTION 05 · CONTRACTS & B2B API

/pb/ev Postback Contract &amp; Wholesale Panel API v2

Security Warning — Mask &tok= Everywhere: Each order has a unique 24-character hex secret. Keep &tok= strictly server-side and ALWAYS mask/redact &tok=*** in application logs, APM traces, reverse-proxy logs, and support tickets.
5a. /pb/ev HTTP Status Contract, Events & Click Lifecycle

Endpoint: GET|POST ${esc(origin)}/pb/ev?o=<ORDER_CODE>&cid=<CLICK_ID>&e=<EVENT>&tok=<SECRET>. Valid events: install (max 1 conversion per CID, requires &tok=), uninstall (requires &tok=), engaged, redirect. Server-side click records persist in order_clicks for the full active campaign lifecycle (plus 24h on click-level attribution_review orders; client-side /sdk/v1.js cookie/storage TTL is 7 days).

HTTP Meaning Client / Server Action
200Accepted (or TEST_ handshake verified)Mark confirmed; do not resend.
400Missing/invalid cid or unsupported eventPermanent error — fix payload formatting.
403Missing/invalid &tok= or click/order mismatchPermanent error — check server env secret; alert ops.
404Unknown click_id, TEST_ id, or orderPermanent error — do not retry endlessly.
409Duplicate install (duplicate: true)Treat as confirmed! NEVER delete your dedup row.
410Order closed (cancelled/refunded/expired/stalled or >24h review)Permanent error — mark failed_permanent.
429Per-IP rate limit exceededTransient — keep pending & retry with backoff.
5b. Wholesale Panel API v2 (POST /api/v2) — Idempotent client_ref & Bulk Status

Available to approved Agencies & Reseller Panels (JSON or application/x-www-form-urlencoded). Pass an optional client_ref (alias idempotency_key, 4–64 chars [A-Za-z0-9_.-]) on action=add so network timeout retries NEVER double-charge your wallet — duplicates return HTTP 200 with "idempotent": true. All rates are per 1,000 USD (currency: "USD").

# 1. List calibrated services (rate = USD per 1,000 Qualified Redirects)
curl -X POST https://installpeak.com/api/v2 -H "Content-Type: application/json" \
  -d '{"key":"YOUR_API_KEY","action":"services"}'
# Response 200:
# [{"service":211,"name":"Browser Extension Qualified Redirects (Chrome/Firefox/Edge · Global 110+ Countries — Per 1k Redirects)","type":"Default",
#   "category":"Browser Extensions","rate":"1.60","min":"1000","max":"250000","refill":false,"cancel":false}, ...]

# 2. Check Prepaid USD wallet balance
curl -X POST https://installpeak.com/api/v2 -d "key=YOUR_API_KEY&action=balance"
# Response 200: {"balance":"142.5000","currency":"USD"}

# 3. Create order with client_ref idempotency (safe to retry on timeout!)
curl -X POST https://installpeak.com/api/v2 -H "Content-Type: application/json" \
  -d '{"key":"YOUR_API_KEY","action":"add","service":211,"link":"https://chromewebstore.google.com/detail/...","quantity":5000,"client_ref":"panel-ord-90142"}'
# First call 200:  {"order":42,"order_code":"DR8A92F1","charge":"8.0000","currency":"USD"}
# Retry call 200:  {"order":42,"order_code":"DR8A92F1","charge":"8.0000","currency":"USD","idempotent":true}

# 4. Single order status (numeric id or order_code)
curl -X POST https://installpeak.com/api/v2 -H "Content-Type: application/json" \
  -d '{"key":"YOUR_API_KEY","action":"status","order":"DR8A92F1"}'
# Response 200: {"charge":"8.0000","start_count":"0","status":"In progress","remains":"1840","delivered":"3160","currency":"USD","order_code":"DR8A92F1"}

# 5. Bulk order status (comma-separated, up to 50 IDs per request)
curl -X POST https://installpeak.com/api/v2 -H "Content-Type: application/json" \
  -d '{"key":"YOUR_API_KEY","action":"status","orders":"42,DR8A92F1,999999"}'
# Response 200:
# {"42":{"charge":"8.0000","start_count":"0","status":"In progress","remains":"1840","delivered":"3160","currency":"USD","order_code":"DR8A92F1"},
#  "DR8A92F1":{"charge":"8.0000","start_count":"0","status":"In progress","remains":"1840","delivered":"3160","currency":"USD","order_code":"DR8A92F1"},
#  "999999":{"error":"Incorrect order ID"}}

# Error format (400 / 401 / 404 / 429): {"error":"Insufficient balance"}
API v2 Status Mapped Order States
Pendingpending_payment, paid, provisioning
In progressrunning, active, delivering, trial_active
Completedcompleted
Partialpaused, client_paused, cost_capped, attribution_review, s2s_stalled, compliance_paused
Canceledexpired, cancelled, refunded