Integration Guide
Integration Guide
Follow these steps to integrate the affiliate tracking system into your main STMS event website. This is required for click and sale data to appear on this dashboard.
Developer Required
These steps require technical knowledge and access to your event website's code. If you are not a developer, please share this guide with your technical team.
1Track Affiliate Clicks (Frontend)
Add this JavaScript snippet to the <head> section of your event website's HTML. It captures the affiliate ID from the URL, stores it in a cookie, and calls your backend to log the click.
<!-- Add this script to the <head> of YOUR event website -->
<script>
function getAffiliateId() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('ref');
}
function getSessionId() {
let sessionId = sessionStorage.getItem('stms_session_id');
if (!sessionId) {
sessionId = crypto.randomUUID();
sessionStorage.setItem('stms_session_id', sessionId);
}
return sessionId;
}
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
async function trackClick(affiliateId, sessionId) {
try {
// IMPORTANT: Replace with the actual URL of your event website.
const trackingApiUrl = 'https://YOUR-EVENT-WEBSITE.com/api/track-click';
await fetch(trackingApiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ affiliate_id: affiliateId, session_id: sessionId }),
});
} catch (error) {
console.error('Failed to track click:', error);
}
}
const affiliateId = getAffiliateId();
if (affiliateId) {
const sessionId = getSessionId();
// Store the ID in a cookie for 30 days
setCookie('stms_affiliate_id', affiliateId, 30);
// Send the click to your backend to be recorded
trackClick(affiliateId, sessionId);
}
</script>2Create a Click-Tracking API Route (Backend)
Create a backend API endpoint (e.g., /api/track-click) on your event website's server. The script from Step 1 will call this endpoint. Its job is to receive the affiliate ID and insert a new record into your Supabase 'clicks' table.
// Example API route for YOUR event website: /api/track-click
// This code must be deployed on your event website's backend server.
import { createClient } from '@supabase/supabase-js';
// IMPORTANT: Initialize Supabase client with the SERVICE_ROLE_KEY for backend operations.
// The service role key must be kept secret on your server and loaded from environment variables.
const supabaseAdmin = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.SUPABASE_SERVICE_KEY
);
export async function POST(request: Request) {
try {
const { affiliate_id, session_id } = await request.json();
if (!affiliate_id) {
return new Response(JSON.stringify({ error: 'Affiliate ID is required' }), { status: 400 });
}
if (!session_id) {
return new Response(JSON.stringify({ error: 'Session ID is required' }), { status: 400 });
}
// Prevent duplicate clicks for the same session
const { data: existingClick, error: selectError } = await supabaseAdmin
.from('clicks')
.select('id')
.eq('affiliate_id', affiliate_id)
.eq('session_id', session_id)
.maybeSingle();
if (selectError) throw selectError;
if (existingClick) {
return new Response(JSON.stringify({ success: true, message: 'Click already tracked for this session.' }), { status: 200 });
}
// Insert new click using the admin client
const { error: insertError } = await supabaseAdmin
.from('clicks')
.insert({ affiliate_id: affiliate_id, session_id: session_id });
if (insertError) {
throw insertError;
}
return new Response(JSON.stringify({ success: true }), { status: 201 });
} catch (error) {
console.error('Error tracking click:', error);
return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });
}
}3Track Ticket Sales (Backend)
After a successful purchase on your event website, your backend code needs to check for the affiliate cookie. If it exists, create a new record in your Supabase 'sales' table. This logic should run on your server.
// Example backend logic for YOUR event website's checkout process.
// This code should run on your server after a successful purchase.
import { createClient } from '@supabase/supabase-js';
import { cookies } from 'next/headers'; // Example for Next.js App Router
// IMPORTANT: Initialize Supabase client with the SERVICE_ROLE_KEY for backend operations.
const supabaseAdmin = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.SUPABASE_SERVICE_KEY
);
async function handleSuccessfulPurchase(saleAmount, commissionAmount) {
// This example uses next/headers to read cookies. Your framework may differ.
const cookieStore = cookies();
const affiliateId = cookieStore.get('stms_affiliate_id')?.value;
if (!affiliateId) {
console.log('Not an affiliate sale.');
return;
}
try {
// Use the admin client to insert into the sales table
const { data, error } = await supabaseAdmin
.from('sales')
.insert({
affiliate_id: affiliateId,
amount: saleAmount,
commission: commissionAmount,
});
if (error) {
throw error;
}
console.log('Successfully recorded affiliate sale:', data);
} catch (error) {
console.error('Error recording affiliate sale:', error.message);
}
}4Enable Row Level Security (Database)
This is a critical security step. Go to the Supabase dashboard, open the SQL Editor, and run the following SQL commands. This ensures that each affiliate can only see their own click data.
Important Security Step
Without this step, your affiliate data may be visible to other affiliates or your application will not be able to fetch any click data at all.
-- 1. Enable Row Level Security on the 'clicks' table
ALTER TABLE public.clicks ENABLE ROW LEVEL SECURITY;
-- 2. Create a policy that allows affiliates to view their own clicks
CREATE POLICY "Affiliates can view their own clicks"
ON public.clicks
FOR SELECT
TO authenticated
USING (auth.uid() = affiliate_id);
-- 3. Create a policy that allows your backend (using a service_role key) to insert clicks
-- The service_role bypasses RLS, so no explicit INSERT policy is needed if you are using the service key on your backend.
-- If you were inserting from the frontend, you would need an INSERT policy.