> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tagada.io/llms.txt
> Use this file to discover all available pages before exploring further.

# External Page Tracker

> Track users on external pages (WordPress, WooCommerce, custom landing pages) that are part of a TagadaPay funnel

# External Page Tracker

The External Page Tracker is a lightweight JavaScript snippet that connects your external pages to the TagadaPay funnel system. It enables accurate analytics (device, browser, OS), session tracking, and funnel navigation on pages **not hosted on TagadaPay**.

<Info>
  This is essential for WooCommerce stores, WordPress sites, custom landing pages, or any external page that is part of your funnel.
  Without the tracker, analytics data will be inaccurate (e.g., showing the server's User-Agent instead of the visitor's browser).
</Info>

***

## Why You Need This

When a funnel includes steps hosted outside TagadaPay (e.g., your WooCommerce store), the TagadaPay platform has no visibility into what happens on those pages. The External Page Tracker solves this by:

1. **Creating a session** — authenticates the visitor and creates an anonymous token
2. **Tracking page views** — records which funnel step the visitor is on
3. **Capturing real device data** — sends the actual browser User-Agent, screen size, and device info (instead of a server-side PHP User-Agent)
4. **Enabling funnel navigation** — allows the visitor to move to the next step via JavaScript
5. **Preserving identity** — maintains the same customer identity across TagadaPay-hosted and external pages

```
┌────────────────┐     ┌──────────────────┐     ┌────────────────┐
│  Your Store     │ ──► │  TagadaPay        │ ──► │  Thank You     │
│  (WooCommerce)  │     │  Checkout         │     │  Page          │
│  + Tracker ✅   │     │  (hosted)         │     │  (hosted)      │
└────────────────┘     └──────────────────┘     └────────────────┘
```

***

## Quick Start

### Option 1: CDN (recommended for most sites)

Add this before the closing `</body>` tag on your external page:

```html theme={null}
<script src="https://cdn.jsdelivr.net/npm/@tagadapay/plugin-sdk/dist/external-tracker.min.js"></script>
<script>
  TagadaTracker.init({
    storeId: 'store_xxx',       // Your TagadaPay store ID
    accountId: 'acc_xxx',       // Your TagadaPay account ID
    stepId: 'step_xxx',         // The funnel step this page represents
    funnelId: 'funnel_xxx',     // Optional: auto-detected from URL params
    debug: false,               // Set true during development

    onReady: function(session) {
      console.log('Tracker ready:', session.sessionId);
    },
    onError: function(error) {
      console.error('Tracker failed:', error.message);
    }
  });
</script>
```

### Option 2: NPM Package

```bash theme={null}
npm install @tagadapay/plugin-sdk
```

```typescript theme={null}
import { TagadaTracker } from '@tagadapay/plugin-sdk/v2/standalone';

await TagadaTracker.init({
  storeId: 'store_xxx',
  accountId: 'acc_xxx',
  stepId: 'step_xxx',
  debug: process.env.NODE_ENV === 'development',

  onReady: (session) => {
    console.log('Ready:', session);
  }
});
```

<Tip>
  You can find your `storeId`, `accountId`, and `stepId` in the TagadaPay dashboard under **Storefront → \[Your Funnel] → External Step → Tracking Script**.
</Tip>

***

## Configuration

### Required Parameters

| Parameter   | Type     | Description                                                   |
| ----------- | -------- | ------------------------------------------------------------- |
| `storeId`   | `string` | Your TagadaPay store ID (e.g., `store_019dd15cdb5b`)          |
| `accountId` | `string` | Your TagadaPay account ID (e.g., `acc_4ff19578aaa2`)          |
| `stepId`    | `string` | The funnel step ID this page represents (e.g., `step_abc123`) |

### Optional Parameters

| Parameter    | Type      | Default                     | Description                                             |
| ------------ | --------- | --------------------------- | ------------------------------------------------------- |
| `funnelId`   | `string`  | Auto-detected from URL      | Funnel ID (if not in URL params)                        |
| `stepName`   | `string`  | —                           | Human-readable step name for analytics                  |
| `stepType`   | `string`  | —                           | Step categorization (`landing`, `offer`)                |
| `apiBaseUrl` | `string`  | `https://app.tagadapay.com` | API base URL (only change for self-hosted or local dev) |
| `debug`      | `boolean` | `false`                     | Enable verbose console logging                          |

### Callbacks

| Callback  | Signature                                   | Description                                                    |
| --------- | ------------------------------------------- | -------------------------------------------------------------- |
| `onReady` | `(session: ExternalTrackerSession) => void` | Called when the tracker is fully initialized                   |
| `onError` | `(error: Error) => void`                    | Called on failure — when provided, `init()` will **not** throw |

<Warning>
  When `onError` is **not** provided, `init()` will throw on failure. Always use `onError` or wrap `init()` in a try/catch.
</Warning>

***

## API Reference

### `TagadaTracker.init(config)`

Initialize the tracker. Must be called once per page load. Returns a `Promise<ExternalTrackerSession | null>`.

```javascript theme={null}
const session = await TagadaTracker.init({
  storeId: 'store_xxx',
  accountId: 'acc_xxx',
  stepId: 'step_xxx',
});
```

The returned session object:

```typescript theme={null}
interface ExternalTrackerSession {
  sessionId: string;      // Funnel session ID
  customerId: string;     // Anonymous customer ID
  storeId: string;        // Store ID
  funnelId?: string;      // Funnel ID (if resolved)
  currentStepId?: string; // Current step ID
  cmsToken?: string;      // Auth token (for API calls)
}
```

***

### `TagadaTracker.navigate(options)`

Navigate to the next funnel step. By default, this redirects the browser automatically.

```javascript theme={null}
await TagadaTracker.navigate({
  eventType: 'form.submitted',
  eventData: {
    email: 'user@example.com',
    source: 'landing-page'
  },
  autoRedirect: true,  // default: true
});
```

| Option         | Type      | Default | Description                         |
| -------------- | --------- | ------- | ----------------------------------- |
| `eventType`    | `string`  | —       | Event type (e.g., `form.submitted`) |
| `eventData`    | `object`  | `{}`    | Arbitrary event data                |
| `autoRedirect` | `boolean` | `true`  | Auto-redirect to the next step URL  |
| `returnUrl`    | `string`  | —       | Override the redirect URL           |

***

### `TagadaTracker.trackEvent(options)`

Track a custom event for analytics without navigating. Non-blocking — errors are silently swallowed.

```javascript theme={null}
TagadaTracker.trackEvent({
  name: 'video_play',
  data: { videoId: 'hero-video', watchTime: 30 }
});

TagadaTracker.trackEvent({
  name: 'add_to_cart',
  data: { productId: 'prod_123', quantity: 2 }
});
```

***

### `TagadaTracker.buildUrl(baseUrl, params?)`

Build a URL that preserves funnel session context. Use this when linking to other external pages within the same funnel.

```javascript theme={null}
const nextPageUrl = TagadaTracker.buildUrl('https://mysite.com/offer', {
  customParam: 'value'
});
// https://mysite.com/offer?funnelSessionId=fs_xxx&token=xxx&funnelId=xxx&storeId=xxx&customParam=value
```

***

### `TagadaTracker.reset(newStepId)`

Reset the tracker to a different step without re-creating the session. Useful for single-page applications.

```javascript theme={null}
await TagadaTracker.reset('step_new_step_id');
```

***

### `TagadaTracker.destroy()`

Clean up the tracker, remove event listeners, and clear state. Call this when the tracker is no longer needed.

```javascript theme={null}
TagadaTracker.destroy();
```

***

### Utility Methods

| Method                 | Returns                        | Description                        |
| ---------------------- | ------------------------------ | ---------------------------------- |
| `isReady()`            | `boolean`                      | Whether the tracker is initialized |
| `getSession()`         | `ExternalTrackerSession\|null` | Current session data               |
| `getCustomerId()`      | `string\|null`                 | Customer ID                        |
| `getFunnelSessionId()` | `string\|null`                 | Funnel session ID                  |
| `getClient()`          | `TagadaClient\|null`           | Underlying SDK client (advanced)   |
| `version`              | `string`                       | Tracker version (e.g., `1.0.0`)    |

***

## Examples

### WooCommerce / WordPress

If you're using the TagadaPay WooCommerce plugin, the tracker is injected automatically. No manual setup needed.

For manual integration, add the tracker to your theme's `footer.php`:

```php theme={null}
<script src="https://cdn.jsdelivr.net/npm/@tagadapay/plugin-sdk/dist/external-tracker.min.js"></script>
<script>
  TagadaTracker.init({
    storeId: '<?php echo esc_js(TGD_STORE_ID); ?>',
    accountId: '<?php echo esc_js(TGD_ACCOUNT_ID); ?>',
    stepId: '<?php echo esc_js(TGD_STEP_ID); ?>',
    funnelId: '<?php echo esc_js(TGD_FUNNEL_ID); ?>',
    debug: <?php echo TGD_DEBUG ? 'true' : 'false'; ?>,

    onReady: function(session) {
      // Store token in cookie for server-side use
      document.cookie = 'tgd_token=' + (session.cmsToken || '') + ';path=/;samesite=lax';
      document.cookie = 'tgd_customer_id=' + (session.customerId || '') + ';path=/;samesite=lax';
    }
  });
</script>
```

***

### Landing Page with CTA Button

```html theme={null}
<!DOCTYPE html>
<html>
<body>
  <h1>Special Offer</h1>
  <p>Get 50% off today!</p>
  <button id="buy-now">Buy Now</button>

  <script src="https://cdn.jsdelivr.net/npm/@tagadapay/plugin-sdk/dist/external-tracker.min.js"></script>
  <script>
    TagadaTracker.init({
      storeId: 'store_xxx',
      accountId: 'acc_xxx',
      stepId: 'step_landing',
      debug: true,
    });

    document.getElementById('buy-now').addEventListener('click', function() {
      TagadaTracker.navigate({
        eventType: 'offer.accepted',
        eventData: { offerId: 'summer-sale' }
      });
    });
  </script>
</body>
</html>
```

***

### Lead Capture Form

```html theme={null}
<form id="lead-form">
  <input type="email" name="email" placeholder="Your email" required />
  <button type="submit">Get Started</button>
</form>

<script src="https://cdn.jsdelivr.net/npm/@tagadapay/plugin-sdk/dist/external-tracker.min.js"></script>
<script>
  TagadaTracker.init({
    storeId: 'store_xxx',
    accountId: 'acc_xxx',
    stepId: 'step_lead_capture',
  });

  document.getElementById('lead-form').addEventListener('submit', function(e) {
    e.preventDefault();
    var email = e.target.email.value;

    TagadaTracker.navigate({
      eventType: 'form.submitted',
      eventData: { email: email },
    });
  });
</script>
```

***

### Single Page App (React)

```tsx theme={null}
import { useEffect } from 'react';
import { TagadaTracker } from '@tagadapay/plugin-sdk/v2/standalone';

function ExternalPage({ stepId }: { stepId: string }) {
  useEffect(() => {
    TagadaTracker.init({
      storeId: 'store_xxx',
      accountId: 'acc_xxx',
      stepId,
      onError: (err) => console.error('Tracker failed:', err),
    });

    return () => {
      TagadaTracker.destroy();
    };
  }, [stepId]);

  const handleCTA = async () => {
    await TagadaTracker.navigate({
      eventType: 'button.clicked',
      autoRedirect: false, // handle routing yourself
    });
  };

  return <button onClick={handleCTA}>Continue</button>;
}
```

***

## How It Works Internally

1. **`init()` is called** — validates config, creates an anonymous session token via `POST /api/v1/cms/session/anonymous`
2. **Session initialized** — sends device/browser data via `POST /api/v1/cms/session/v2/init`
3. **Funnel registered** — tells the orchestrator which step the visitor is on via `POST /api/v1/funnel/initialize`
4. **`onReady` fires** — session is ready, page view is tracked
5. **`navigate()` called** — sends navigation event, orchestrator determines the next step URL, browser redirects

All API calls include the real browser User-Agent, screen resolution, and device data — ensuring accurate analytics.

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Console shows 'storeId is required'">
    Make sure you're passing a valid `storeId` string. Check the TagadaPay dashboard for your store ID.
  </Accordion>

  <Accordion title="Console shows 'accountId is required'">
    The `accountId` parameter is required since v1.0.0. Find it in your TagadaPay dashboard under **Settings → Account**.
  </Accordion>

  <Accordion title="Analytics show wrong OS (e.g., 'PHP/8.2')">
    This means session initialization is happening server-side (PHP) instead of client-side. Make sure the External Page Tracker script is loaded in the browser, not called from PHP.
  </Accordion>

  <Accordion title="Tracker shows 'No plugin config found - using defaults'">
    The tracker bundle may be outdated. Make sure you're using the latest version from the CDN. Clear your browser cache or add a version query parameter: `?v=1.0.0`.
  </Accordion>

  <Accordion title="Duplicate /api/v1/funnel/initialize calls">
    Make sure you're using the latest tracker version (1.0.0+). Older versions had a bug where both the tracker and the SDK client would independently initialize the funnel.
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Trigger Checkout" icon="cart-shopping" href="/developer-tools/web-integration/trigger-checkout-from-website">
    Create checkout sessions from any website
  </Card>

  <Card title="Plugin SDK" icon="puzzle-piece" href="/developer-tools/sdk/introduction">
    Build full custom checkout experiences
  </Card>

  <Card title="Funnels" icon="filter" href="https://help.tagada.io/funnels-pages">
    Learn about multi-step funnels
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Full REST API documentation
  </Card>
</CardGroup>
