npm package: @relay-capital/affiliatebase-tracking
Description: Lightweight affiliate tracking script for AffiliateBase - cookie-based attribution, conversion tracking, and Stripe integration
Author: AffiliateBase
Latest version: 1.0.7

# @relay-capital/affiliatebase-tracking

Lightweight, zero-dependency affiliate tracking script for [AffiliateBase](https://affiliatebase.io). Cookie-based attribution, conversion tracking, and automatic Stripe integration.

[![npm version](https://img.shields.io/npm/v/%40relay-capital%2Faffiliatebase-tracking.svg)](https://www.npmjs.com/package/@relay-capital/affiliatebase-tracking)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- Cookie-based referral attribution (30-day default)
- Rewardful-style tracking parameter defaults (`?via=` + optional custom params)
- Automatic Stripe Buy Button / Pricing Table integration
- Conversion tracking via email
- Cross-domain link tagging
- Automatic form integration
- Zero dependencies, pure JavaScript with production-ready dist artifacts

## Quick Start

Add this snippet to your website's `<head>` or before `</body>`:

```html
<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://cdn.jsdelivr.net/npm/@relay-capital/affiliatebase-tracking@1/dist/track.min.js"
  data-account-id="YOUR_ACCOUNT_ID"
></script>
```

Replace `YOUR_ACCOUNT_ID` with your account ID from the [AffiliateBase dashboard](https://app.affiliatebase.io).  
`data-account` is also accepted as a shorter alias.

That's it! The script will automatically track referrals from affiliate links.

## Usage

### Track Conversions

When a referred visitor signs up or makes a purchase, track the conversion:

```javascript
affiliatebase("convert", { email: "customer@example.com" });

// Optional purchase metadata (recommended for dedupe + revenue accuracy)
affiliatebase("convert", {
  email: "customer@example.com",
  amount_cents: 4999,
  currency: "USD",
  conversion_id: "order_123"
});
```

### Check Attribution

```javascript
affiliatebase("ready", () => {
  if (window.AffiliateBase.referral) {
    console.log("Referred by:", window.AffiliateBase.affiliate?.name);
  }
});
```

### Stripe Integration

Add `data-affiliatebase` to your Stripe elements for automatic attribution:

```html
<!-- Stripe Buy Button -->
<stripe-buy-button buy-button-id="buy_btn_xxx" publishable-key="pk_live_xxx" data-affiliatebase></stripe-buy-button>

<!-- Stripe Pricing Table -->
<stripe-pricing-table
  pricing-table-id="prctbl_xxx"
  publishable-key="pk_live_xxx"
  data-affiliatebase
></stripe-pricing-table>
```

### Form Integration

Add `data-affiliatebase` (or `data-affiliatebase="true"`) to forms to automatically include referral data:

```html
<form data-affiliatebase action="/signup" method="POST">
  <input type="email" name="email" />
  <button>Sign Up</button>
  <!-- Hidden referral input auto-injected -->
</form>
```

## Configuration

### Script Attributes

| Attribute                   | Required | Description                             |
| --------------------------- | -------- | --------------------------------------- |
| `data-account-id`               | Yes      | Your account ID (`data-account` alias supported) |
| `data-debug`                | No       | Set to `"true"` for console logging     |
| `data-affiliatebase-params` | No       | Custom URL parameters (comma-separated) |
| `data-params`               | No       | Alias for `data-affiliatebase-params` |
| `data-domains`              | No       | Cross-domain hosts to auto-tag with `via` |
| `data-request-timeout-ms`   | No       | Request timeout in milliseconds (default: `8000`) |
| `data-respect-dnt`          | No       | Set to `"true"` to skip requests when Do Not Track is enabled |

### URL Parameters

The script automatically detects these URL parameters:

- `?via=TOKEN` (primary)
- `?<custom>=TOKEN` when configured via `data-affiliatebase-params`
- `?referral=ID` (preload existing referral)

Example affiliate link: `https://yoursite.com?via=john123`

## API Reference

### Methods

```javascript
// Track conversion
affiliatebase("convert", { email: "customer@example.com" });
affiliatebase("identify", { email: "customer@example.com" }); // alias

// Force attribution to specific affiliate
affiliatebase("source", "affiliate_token");
affiliatebase("track", "affiliate_token"); // alias

// Execute when loaded
affiliatebase("ready", () => {
  console.log("Ready!");
});

// Enable verbose debug logs at runtime
affiliatebase("debug", true);
affiliatebase("set_debug", true); // alias

// Reset attribution state during local QA
affiliatebase("reset");
affiliatebase("clear"); // alias

// Read current referral id and full state
affiliatebase("referral");
affiliatebase("state");
```

### Global Object

Access attribution data via `window.AffiliateBase`:

```javascript
window.AffiliateBase.referral; // Referral ID (UUID) or ""
window.AffiliateBase.affiliate; // Affiliate object or false
window.AffiliateBase.campaign; // Campaign object or false
window.AffiliateBase.coupon; // Coupon object or false
```

### Events

```javascript
window.addEventListener("AffiliateBase.initialized", () => {
  console.log("Tracking initialized");
});

window.addEventListener("AffiliateBase.tracked", (e) => {
  console.log("Referral tracked:", e.detail.referral);
});
```

## Local Testing Tips

Use first-party endpoints in local/dev by pointing the script to your Rails app:

```html
<script
  async
  src="/track.js"
  data-account-id="YOUR_ACCOUNT_ID"
  data-api-url="http://localhost:3000"
  data-debug="true"
></script>
```

Useful runtime helpers during QA:

```javascript
affiliatebase("debug", true); // enable logs
affiliatebase("reset"); // clear attribution and start a clean test cycle
```

## TypeScript

Type definitions are included:

```typescript
import "@relay-capital/affiliatebase-tracking";

affiliatebase("convert", { email: "test@example.com" });

if (window.AffiliateBase.referral) {
  console.log("Affiliate:", window.AffiliateBase.affiliate?.name);
}
```

## Browser Support

- Chrome/Edge (last 2 versions)
- Firefox (last 2 versions)
- Safari (last 2 versions)
- iOS Safari (last 2 versions)

## License

MIT

## Links

- [AffiliateBase](https://affiliatebase.io)
- [Dashboard](https://app.affiliatebase.io)
- [npm](https://www.npmjs.com/package/@relay-capital/affiliatebase-tracking)