Use this JavaScript reference to install AffiliateBase browser tracking, configure attribution parameters, read the generated referral ID, and hand that ID to Stripe Checkout.
Install snippet
<script>
(function (w, r) {
w._abq = w._abq || [];
w[r] =
w[r] ||
function () {
(w[r].q = w[r].q || []).push(arguments);
};
})(window, "affiliatebase");
</script>
<script
async
src="https://app.affiliatebase.io/track.js"
data-account-id="YOUR_ACCOUNT_ID"
></script>
Updates and exact-version installations
The default URL serves the approved stable build. Compatible updates arrive automatically on subsequent page loads after caches refresh. Publishing a numbered package does not automatically promote it to this URL. Breaking changes require an explicit migration.
For controlled upgrades, developers can install an exact npm package version or use a numbered jsDelivr URL. For example, https://cdn.jsdelivr.net/npm/@relay-capital/affiliatebase-tracking@1.0.10/dist/track.min.js remains the immutable 1.0.10 release; it will not receive later fixes automatically. Keep exact pins current yourself. Do not load both a bundled copy and the hosted script.
To migrate an existing tag, replace only its script URL with https://app.affiliatebase.io/track.js, preserving the queue snippet, account ID and other attributes. Permit app.affiliatebase.io in CSP script-src and connect-src. Keep your consent manager’s loading rules in place.
Installation diagnostics report the public account ID, loaded version and script source without URL queries/fragments, visitor identifiers or page paths. Requests omit credentials. Reporting works without a referral click and cannot create a referral, sale or commission. Diagnostic failure does not block attribution. Reports respect configured Do Not Track handling; data-telemetry="false" disables them. A missing report does not prove the script is absent.
Script attributes
| Attribute | Required | Notes |
|---|---|---|
data-account-id | Yes | Account id (data-account alias also supported) |
data-api-url | No | Override API base URL (useful for local dev) |
data-debug | No | true enables client logs |
data-telemetry | No | false disables installation diagnostic reporting |
data-affiliatebase-params | No | Comma-separated custom attribution params |
data-params | No | Alias for data-affiliatebase-params |
data-domains | No | Comma-separated domains for cross-domain referral tagging |
data-request-timeout-ms | No | Request timeout (default 8000) |
data-respect-dnt | No | true skips tracking requests when DNT is enabled |
URL parameter behavior
Priority:
?referral=<REFERRAL_ID>(preloads existing referral id)?via=<TOKEN>(canonical token parameter)- Custom params from
data-affiliatebase-params(for example?partner=<TOKEN>)
Runtime methods
// Identify a referred signup; no sale or commission is created.
affiliatebase("convert", { email: "customer@example.com" });
affiliatebase("identify", { email: "customer@example.com" }); // alias
affiliatebase("source", "affiliate_token");
affiliatebase("track", "affiliate_token"); // alias
affiliatebase("ready", () => console.log("attribution settled"));
affiliatebase("debug", true);
affiliatebase("set_debug", true); // alias
affiliatebase("reset");
affiliatebase("clear"); // alias
affiliatebase("referral"); // returns referral id
affiliatebase("tracked"); // returns whether attribution tracking completed
affiliatebase("state"); // returns full attribution state
Identity, readiness, and reset
Browser identify, convert, and conversion associate an email with the current referral and visitor session through /api/track/lead. They do not record revenue. Use Stripe webhooks for purchases.
affiliatebase("ready", async () => {
const result = await affiliatebase("identify", { email: "customer@example.com" });
if (!result.success) console.log(result.code);
});
ready waits until pending attribution requests finish, including failures. A ready callback can run without a referral: check window.AffiliateBase.referral before using it. Preloader calls are queued and have no immediate result; await identity inside a ready callback after the library loads.
Identity returns a Promise with success, optional attributed, and an error code when unsuccessful. Common codes include NO_REFERRAL, EMAIL_REQUIRED, DO_NOT_TRACK, REQUEST_FAILED, and SERVER_CONVERSION_REQUIRED. Amount, currency, order, and payment fields are rejected in browser calls.
reset clears browser attribution and restores values the tracker inserted into forms, links, and Stripe components. It preserves subsequent merchant edits and invalidates earlier in-flight attribution responses. It does not delete server records or revoke commissions.
Signed server conversions
Most Stripe integrations should use automatic verified webhooks. The advanced endpoint POST https://app.affiliatebase.io/api/track/convert can attribute an existing verified Stripe sale; it is not an API for arbitrary offline or non-Stripe revenue.
Keep the API token on your server. The key must belong to the referral’s account and grant tracking.conversions.write (or full access). MCP reporting tokens cannot use this endpoint. Sign the exact JSON bytes sent, using a current Unix timestamp and a fresh nonce for every request. Requests outside the five-minute window and reused nonces are rejected.
// Node.js server only. Values come from your verified checkout records.
import { createHash, createHmac, randomUUID } from "node:crypto";
async function attributeVerifiedSale({ referralId, visitorId, email, paymentIntentId, amountCents, currency, conversionId }) {
const token = process.env.AFFILIATEBASE_API_KEY;
if (!token) throw new Error("Missing server API key");
const body = JSON.stringify({
referral_id: referralId,
visitor_id: visitorId,
email,
amount_cents: amountCents,
currency,
conversion_id: conversionId,
stripe_payment_intent_id: paymentIntentId,
});
const timestamp = Math.floor(Date.now() / 1000).toString();
const nonce = randomUUID();
const digest = createHash("sha256").update(body).digest("hex");
const signature = createHmac("sha256", token)
.update([timestamp, nonce, digest].join(".")).digest("hex");
const response = await fetch("https://app.affiliatebase.io/api/track/convert", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
"X-Track-Timestamp": timestamp,
"X-Track-Nonce": nonce,
"X-Track-Signature": signature,
},
body,
});
const result = await response.json();
if (!response.ok || !result.success) throw new Error(result.code || result.error);
return result;
}
Use integer cents, an explicit currency, a stable conversion ID, and the generated referral ID. Supply a verified Stripe invoice, payment intent, or charge reference using stripe_invoice_id, stripe_payment_intent_id, or stripe_charge_id. The payment must already exist in AffiliateBase and match its recorded amount and currency. A valid signature does not bypass payment, visitor, attribution, or duplicate checks. On retry, keep the conversion ID and use a fresh timestamp, nonce, and signature.
Global state
window.AffiliateBase.referral;
window.AffiliateBase.affiliate;
window.AffiliateBase.campaign;
window.AffiliateBase.coupon;
window.AffiliateBase.tracked;
window.AffiliateBase.version;
window.affiliatebase_referral; // legacy alias getter
Use window.AffiliateBase.referral or affiliatebase("state") for new integrations. The legacy alias remains available for older snippets, but new Stripe Checkout code should submit the generated window.AffiliateBase.referral value to your server.
Automatic integrations
Forms
Add data-affiliatebase to a form to auto-inject a hidden referral input when attribution exists. If the active referral includes an AffiliateBase coupon, the script also injects a hidden coupon input.
<form data-affiliatebase action="/signup" method="POST">
...
</form>
Optional custom hidden field name:
<form data-affiliatebase data-affiliatebase-param-name="referral_id">
...
</form>
Stripe Buy Buttons and Pricing Tables
The script sets client-reference-id on standard Stripe Buy Button and Pricing Table elements after a referred visitor is present.
<stripe-buy-button buy-button-id="buy_btn_xxx" publishable-key="pk_live_xxx"></stripe-buy-button>
<stripe-pricing-table pricing-table-id="prctbl_xxx" publishable-key="pk_live_xxx"></stripe-pricing-table>
Stripe Payment Links
For standard https://buy.stripe.com/... and https://link.payment/... links, the script appends client_reference_id=<generated_referral_id> after a referred visitor is present. For custom Stripe-hosted or redirected Payment Link URLs, add data-affiliatebase to the anchor as an explicit opt-in where AffiliateBase owns client_reference_id.
<a href="https://buy.stripe.com/...">Buy</a>
<a data-affiliatebase href="https://link.payment/...">Buy</a>
Cross-domain tagging
With data-domains="example.com,checkout.example.com", matching external links are tagged with via=<affiliate_token>. Tracker-owned values follow later attribution changes. Existing merchant values are preserved unless the link explicitly opts in.
Browser events
AffiliateBase.initializedAffiliateBase.trackedAffiliateBase.resetAffiliateBase.identified(successful lead handoff)AffiliateBase.error(identity failure; inspectevent.detail.code)
Example:
window.addEventListener("AffiliateBase.tracked", (event) => {
console.log(event.detail.referral);
});
Local development
Point the script at your local API:
<script
async
src="/track.js"
data-account-id="YOUR_ACCOUNT_ID"
data-api-url="http://localhost:3000"
data-debug="true"
></script>