Skip to main content

JavaScript SDK for Instant Loyalty Integration

The Loyalteez SDK is the quickest way to integrate loyalty rewards into your website or web application. No blockchain knowledge required!

⚡ 5KB gzipped • Works with React, Vue, Angular, and Vanilla JS • Auto-detection included

Quick Start

1. Add the SDK

Add this script tag to your HTML, preferably in the <head>:

<script src="https://api.loyalteez.app/sdk.js"></script>

2. Initialize with Your Brand ID

<script>
// Initialize once the SDK loads
window.addEventListener('DOMContentLoaded', () => {
LoyalteezAutomation.init('YOUR_BRAND_ID');
});
</script>

Get your Brand ID: Partner Portal → Settings → Account

3. Start Tracking Events

// SDK automatically loads your event configurations and sets up detection
// Events are tracked automatically based on your detection methods:
// - URL patterns (e.g., /thank-you, /success)
// - CSS selectors (e.g., .download-button clicks)
// - Form submissions (e.g., #contact-form submits)

// Or manually track events:
LoyalteezAutomation.track('newsletter_signup', {
userEmail: user.email,
metadata: { source: 'homepage_banner' }
});

That's it! The SDK automatically:

  • ✅ Loads your custom event configurations
  • ✅ Sets up detection methods (URL patterns, CSS selectors, forms)
  • ✅ Tracks events automatically when conditions are met
  • ✅ Distributes LTZ rewards to users

No additional code needed - just configure detection methods in Partner Portal → Settings → LTZ Distribution → Automation.

Installation

Add the SDK via Cloudflare Workers CDN:

<script src="https://api.loyalteez.app/sdk.js"></script>

Benefits:

  • ✅ Always up-to-date automatically
  • ✅ Cached globally via Cloudflare edge network
  • ✅ No build step or package manager required
  • ✅ ~5KB gzipped
  • ✅ Works with any website or framework

Alternative: Load Dynamically

// Load SDK programmatically
const script = document.createElement('script');
script.src = 'https://api.loyalteez.app/sdk.js';
script.async = true;

script.onload = () => {
// SDK ready - initialize
LoyalteezAutomation.init('YOUR_BRAND_ID');
};

document.head.appendChild(script);

Note: We use a Cloudflare Worker to serve the SDK, not an npm package. This ensures you always get the latest version without needing to update dependencies.

Configuration

Basic Configuration

LoyalteezAutomation.init('YOUR_BRAND_ID', {
// Optional configuration
autoDetect: true, // Auto-detect events based on configured detection methods (default: true)
debug: false, // Enable console logging
endpoint: 'https://api.loyalteez.app', // API endpoint
trackPageViews: true, // Track page navigation
trackClicks: true, // Track button/link clicks
sessionTimeout: 30 // Session timeout in minutes
});

Automatic Detection Methods: When autoDetect is enabled (default), the SDK automatically:

  1. Loads your event configurations from /loyalteez-api/event-config
  2. Sets up detection listeners for:
    • URL Pattern Detection - Monitors URL changes
    • CSS Selector Detection - Attaches click listeners
    • Form Submission Detection - Intercepts form submissions
  3. Tracks events automatically when detection conditions are met

No code changes needed - just configure detection methods in Partner Portal and the SDK handles the rest!

Advanced Configuration

LoyalteezAutomation.init('YOUR_BRAND_ID', {
// Event filtering
ignoreEvents: ['page_view'], // Events to not track

// Custom event mapping
eventMap: {
'signup': 'account_creation', // Map custom events
'buy': 'purchase'
},

// User identification
userId: user.id, // Your internal user ID
userEmail: user.email, // User's email

// Metadata attached to all events
globalMetadata: {
appVersion: '1.0.0',
platform: 'web'
},

// Callbacks
onEventTracked: (event) => {
console.log('Event tracked:', event);
},

onError: (error) => {
console.error('SDK error:', error);
},

onRewardReceived: (reward) => {
// Show notification: "You earned 100 LTZ!"
showNotification(`You earned ${reward.amount} LTZ!`);
}
});

API Reference

LoyalteezAutomation.init()

Initialize the SDK with your brand ID.

LoyalteezAutomation.init(
brandId: string,
options?: {
autoTrack?: boolean;
debug?: boolean;
endpoint?: string;
trackPageViews?: boolean;
trackClicks?: boolean;
sessionTimeout?: number;
ignoreEvents?: string[];
eventMap?: Record<string, string>;
userId?: string;
userEmail?: string;
globalMetadata?: Record<string, any>;
onEventTracked?: (event: Event) => void;
onError?: (error: Error) => void;
onRewardReceived?: (reward: Reward) => void;
}
): void

LoyalteezAutomation.track()

Manually track a custom event.

LoyalteezAutomation.track(
eventName: string,
metadata?: {
email?: string;
userId?: string;
value?: number;
[key: string]: any;
}
): Promise<TrackingResponse>

Example:

LoyalteezAutomation.track('purchase', {
email: '[email protected]',
value: 99.99,
orderId: 'order_123',
products: ['product_1', 'product_2']
});

LoyalteezAutomation.identify()

Associate SDK session with a user.

LoyalteezAutomation.identify(
userId: string,
traits?: {
email?: string;
name?: string;
[key: string]: any;
}
): void

Example:

// After user logs in
LoyalteezAutomation.identify(user.id, {
email: user.email,
name: user.name,
tier: 'premium'
});

LoyalteezAutomation.reset()

Clear user session (call on logout).

LoyalteezAutomation.reset(): void

Example:

// On user logout
function logout() {
LoyalteezAutomation.reset();
// Your logout logic
}

LoyalteezAutomation.getUserWallet()

Get the user's Loyalteez wallet address.

LoyalteezAutomation.getUserWallet(email: string): Promise<{
walletAddress: string;
ltzBalance: number;
}>

Example:

const wallet = await LoyalteezAutomation.getUserWallet('[email protected]');
console.log('Wallet:', wallet.walletAddress);
console.log('Balance:', wallet.ltzBalance, 'LTZ');

Auto-Tracking

The SDK can automatically track common events when autoTrack: true:

Page Views

Tracked on every page load and navigation.

// Automatically tracked as:
{
event: 'page_view',
metadata: {
path: '/products',
referrer: 'https://google.com',
title: 'Products Page'
}
}

Track clicks on elements with data-ltz-track attribute:

<button data-ltz-track="cta_click" data-ltz-label="Get Started">
Get Started
</button>

<a href="/pricing" data-ltz-track="pricing_link">
View Pricing
</a>

Form Submissions

Track form submissions with data-ltz-form attribute:

<form data-ltz-form="newsletter_signup">
<input type="email" name="email" required>
<button type="submit">Subscribe</button>
</form>

Auto-tracked as:

{
event: 'newsletter_signup',
metadata: {
email: '[email protected]' // From form fields
}
}

Integration Examples

React

import { useEffect } from 'react';

function App() {
useEffect(() => {
// Initialize SDK
LoyalteezAutomation.init(process.env.REACT_APP_BRAND_ID, {
debug: process.env.NODE_ENV === 'development',
userId: user?.id,
userEmail: user?.email,
onRewardReceived: (reward) => {
toast.success(`You earned ${reward.amount} LTZ!`);
}
});
}, []);

const handlePurchase = async (orderId: string, amount: number) => {
// Your purchase logic
await processPurchase(orderId, amount);

// Track purchase event
await LoyalteezAutomation.track('purchase', {
orderId,
amount,
email: user.email
});
};

return <YourApp />;
}

Vue.js

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
LoyalteezAutomation.init(import.meta.env.VITE_BRAND_ID, {
autoTrack: true,
debug: import.meta.env.DEV
});
});

const trackSignup = () => {
LoyalteezAutomation.track('account_creation', {
email: formData.email,
source: 'signup_form'
});
};
</script>

Next.js

// _app.tsx
import { useEffect } from 'react';
import { useRouter } from 'next/router';

function MyApp({ Component, pageProps }) {
const router = useRouter();

useEffect(() => {
LoyalteezAutomation.init(process.env.NEXT_PUBLIC_BRAND_ID, {
trackPageViews: false // Handle manually with router
});

// Track page views on route change
const handleRouteChange = (url) => {
LoyalteezAutomation.track('page_view', {
path: url
});
};

router.events.on('routeChangeComplete', handleRouteChange);
return () => router.events.off('routeChangeComplete', handleRouteChange);
}, [router]);

return <Component {...pageProps} />;
}

WordPress

<!-- In theme's header.php or footer.php -->
<script src="https://api.loyalteez.app/sdk.js"></script>
<script>
LoyalteezAutomation.init('<?php echo get_option('loyalteez_brand_id'); ?>', {
autoTrack: true,
<?php if (is_user_logged_in()): ?>
userId: '<?php echo get_current_user_id(); ?>',
userEmail: '<?php echo wp_get_current_user()->user_email; ?>'
<?php endif; ?>
});
</script>

Shopify

<!-- In theme.liquid, before </body> -->
<script src="https://api.loyalteez.app/sdk.js"></script>
<script>
LoyalteezAutomation.init('{{ settings.loyalteez_brand_id }}', {
{% if customer %}
userId: '{{ customer.id }}',
userEmail: '{{ customer.email }}'
{% endif %}
});

// Track purchase on order confirmation
{% if template == 'customers/order' %}
LoyalteezAutomation.track('purchase', {
orderId: '{{ order.name }}',
amount: {{ order.total_price | money_without_currency }},
email: '{{ order.email }}'
});
{% endif %}
</script>

Events Configuration

Configure which events trigger LTZ distribution:

Partner Portal → Settings → LTZ Distribution → Events

  1. Select event type (e.g., "account_creation")
  2. Set LTZ reward amount (e.g., 100 LTZ)
  3. Configure restrictions (e.g., "once per user")
  4. Set detection method (SDK auto-track or custom event name)

The SDK automatically distributes LTZ when users trigger configured events.

Testing

Development Mode

LoyalteezAutomation.init('YOUR_BRAND_ID', {
debug: true // Enable detailed console logging
});

Console output:

[Loyalteez] SDK initialized
[Loyalteez] Tracking event: page_view
[Loyalteez] Event sent successfully
[Loyalteez] LTZ distributed: 10 LTZ to [email protected]

Test Events

// Test without actually triggering rewards
LoyalteezAutomation.track('test_event', {
email: '[email protected]',
testMode: true // Won't distribute real LTZ
});

Verify Integration

Check Partner Portal → Analytics to see:

  • Events received
  • LTZ distributed
  • Active users

Performance

  • Bundle size: ~5KB gzipped
  • Load time: < 50ms (CDN cached)
  • Tracking latency: < 100ms
  • No blocking: Async, doesn't slow page load

Privacy

  • Privacy-first design: Minimal data collection
  • Opt-out support: Users can disable tracking
  • Data retention: Configurable in Partner Portal
  • Cookie-less: Uses localStorage, no tracking cookies

Implement Opt-Out

// Check user's tracking preference
if (localStorage.getItem('ltz_tracking_opt_out') !== 'true') {
LoyalteezAutomation.init('YOUR_BRAND_ID');
}

// Allow users to opt out
function optOutTracking() {
localStorage.setItem('ltz_tracking_opt_out', 'true');
LoyalteezAutomation.reset();
}

Troubleshooting

SDK not loading?

// Check if SDK loaded
if (typeof Loyalteez !== 'undefined') {
console.log('SDK loaded successfully');
} else {
console.error('SDK failed to load');
}

Events not tracking?

  1. Check browser console for errors (with debug: true)
  2. Verify brand ID is correct
  3. Check Partner Portal → Analytics for received events
  4. Verify event names match configured rules

CORS errors?

The SDK handles CORS automatically. If you see CORS errors:

  1. Verify your domain is added in Partner Portal → Settings → Domains
  2. Check that you're using HTTPS (required for production)

Support