← Back to Table of Contents

Integration Guide

This guide covers various integration methods for the Open Source Site Tracking platform, including JavaScript SDK, REST API, webhooks, and third-party tool integrations.

Overview JavaScript SDK REST API Webhooks Third-Party Tools Framework Integrations Backend Integrations Mobile Integrations

Overview

The Open Source Site Tracking platform provides multiple integration methods to suit different use cases and technical requirements. Choose the integration method that best fits your needs.

JavaScript SDK

Basic Setup

Installation

<!-- Add to your HTML head -->
<script src="https://your-domain.com/tracking.js" 
        data-project-id="your-project-id"></script>

Configuration

// Configure tracking
SiteTracking.init({
  projectId: 'your-project-id',
  tracking: {
    pageViews: true,
    clicks: true,
    scrolls: true,
    forms: true
  },
  privacy: {
    respectDoNotTrack: true,
    anonymizeIp: true
  }
});

Advanced Features

Custom Events

// Track custom events
SiteTracking.track('button-click', {
  button: 'signup',
  page: 'homepage',
  timestamp: Date.now()
});
// Track form submissions
SiteTracking.track('form-submit', {
  form: 'contact',
  fields: ['name', 'email', 'message'],
  success: true
});
// Track user actions
SiteTracking.track('user-action', {
  action: 'login',
  method: 'email',
  userId: 'user123'
});

User Identification

// Identify user
SiteTracking.identify('user123', {
  name: 'John Doe',
  email: 'john@example.com',
  plan: 'premium'
});
// Track user properties
SiteTracking.setUserProperties({
  age: 30,
  location: 'New York',
  interests: ['technology', 'analytics']
});

E-commerce Tracking

// Track product views
SiteTracking.track('product-view', {
  productId: 'prod-123',
  productName: 'Analytics Pro',
  category: 'software',
  price: 99.99
});
// Track purchases
SiteTracking.track('purchase', {
  orderId: 'order-456',
  products: [
    {
      productId: 'prod-123',
      quantity: 1,
      price: 99.99
    }
  ],
  total: 99.99,
  currency: 'USD'
});

REST API

Authentication

JWT Authentication

# Get JWT token
curl -X POST "http://localhost:8000/api/v1/auth/login" \
     -H "Content-Type: application/json" \
     -d '{"email": "user@example.com", "password": "password"}'
# Use token for API requests
curl -X GET "http://localhost:8000/api/v1/projects" \
     -H "Authorization: Bearer YOUR_JWT_TOKEN"

API Endpoints

Projects

# Get all projects
GET /api/v1/projects
# Create project
POST /api/v1/projects
{
  "name": "My Project",
  "description": "Project description",
  "repositoryUrl": "https://github.com/user/repo"
}
# Get project
GET /api/v1/projects/{project_id}
# Update project
PUT /api/v1/projects/{project_id}
{
  "name": "Updated Project",
  "description": "Updated description"
}
# Delete project
DELETE /api/v1/projects/{project_id}

Analytics

# Get analytics overview
GET /api/v1/analytics/{project_id}/overview
# Get page views
GET /api/v1/analytics/{project_id}/pageviews?start_date=2024-01-01&end_date=2024-01-31
# Get visitors
GET /api/v1/analytics/{project_id}/visitors?start_date=2024-01-01&end_date=2024-01-31
# Get real-time analytics
GET /api/v1/analytics/{project_id}/realtime
# Get custom events
GET /api/v1/analytics/{project_id}/events?event_type=button-click

Events

# Track event
POST /api/v1/events/{project_id}
{
  "event_type": "custom-event",
  "properties": {
    "key": "value",
    "timestamp": "2024-01-15T10:30:00Z"
  },
  "user_id": "user123",
  "session_id": "session456"
}
# Get events
GET /api/v1/events/{project_id}?event_type=custom-event&limit=100

Rate Limiting

Endpoint Rate Limit Window
Analytics 100 requests per minute
Events 1000 requests per minute
Projects 50 requests per minute

Webhooks

Webhook Configuration

Create Webhook

POST /api/v1/webhooks
{
  "url": "https://your-domain.com/webhook",
  "events": ["page_view", "button_click", "form_submit"],
  "secret": "your-webhook-secret",
  "active": true
}

Webhook Payload

{
  "event_type": "page_view",
  "project_id": "proj-123",
  "timestamp": "2024-01-15T10:30:00Z",
  "data": {
    "page_url": "/homepage",
    "user_id": "user123",
    "session_id": "session456",
    "properties": {
      "referrer": "https://google.com",
      "user_agent": "Mozilla/5.0..."
    }
  },
  "signature": "sha256=abc123..."
}

Webhook Verification

# Verify webhook signature
import hmac
import hashlib
def verify_webhook(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(f"sha256={expected_signature}", signature)

Third-Party Tools

Google Analytics Integration

Export from Google Analytics

# Export data using Google Analytics API
from googleapiclient.discovery import build
analytics = build('analyticsreporting', 'v4', credentials=credentials)
response = analytics.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': 'VIEW_ID',
                'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
                'metrics': [{'expression': 'ga:pageviews'}],
                'dimensions': [{'name': 'ga:pagePath'}]
            }
        ]
    }
).execute()

Import to Site Tracking

# Import Google Analytics data
import requests
def import_ga_data(ga_data, project_id):
    for row in ga_data['reports'][0]['data']['rows']:
        page_url = row['dimensions'][0]
        page_views = row['metrics'][0]['values'][0]
        
        requests.post(
            f'http://localhost:8000/api/v1/events/{project_id}',
            json={
                'event_type': 'page_view',
                'properties': {
                    'page_url': page_url,
                    'page_views': int(page_views)
                }
            }
        )

Mixpanel Integration

Export from Mixpanel

# Export Mixpanel data
import mixpanel
mixpanel = mixpanel.Mixpanel('YOUR_API_SECRET')
data = mixpanel.export(
    event=['page_view', 'button_click'],
    from_date='2024-01-01',
    to_date='2024-01-31'
)

Import to Site Tracking

# Import Mixpanel data
def import_mixpanel_data(mixpanel_data, project_id):
    for event in mixpanel_data:
        requests.post(
            f'http://localhost:8000/api/v1/events/{project_id}',
            json={
                'event_type': event['event'],
                'properties': event['properties'],
                'timestamp': event['properties']['time']
            }
        )

Framework Integrations

React Integration

React Hook

// useSiteTracking.js
import { useEffect } from 'react';
export const useSiteTracking = (projectId) => {
  useEffect(() => {
    // Initialize tracking
    if (window.SiteTracking) {
      window.SiteTracking.init({ projectId });
    }
  }, [projectId]);
  const track = (eventType, properties) => {
    if (window.SiteTracking) {
      window.SiteTracking.track(eventType, properties);
    }
  };
  return { track };
};
// Usage in component
import { useSiteTracking } from './useSiteTracking';
function MyComponent() {
  const { track } = useSiteTracking('your-project-id');
  const handleClick = () => {
    track('button-click', { button: 'submit' });
  };
  return ;
}

Vue.js Integration

Vue Plugin

// siteTracking.js
export default {
  install(app, options) {
    const tracking = {
      init: (projectId) => {
        if (window.SiteTracking) {
          window.SiteTracking.init({ projectId });
        }
      },
      track: (eventType, properties) => {
        if (window.SiteTracking) {
          window.SiteTracking.track(eventType, properties);
        }
      }
    };
    app.config.globalProperties.$tracking = tracking;
    app.provide('tracking', tracking);
  }
};
// Usage in component
export default {
  mounted() {
    this.$tracking.init('your-project-id');
  },
  methods: {
    handleClick() {
      this.$tracking.track('button-click', { button: 'submit' });
    }
  }
};

Angular Integration

Angular Service

// site-tracking.service.ts
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class SiteTrackingService {
  private projectId: string;
  constructor() {}
  init(projectId: string) {
    this.projectId = projectId;
    if (window.SiteTracking) {
      window.SiteTracking.init({ projectId });
    }
  }
  track(eventType: string, properties: any) {
    if (window.SiteTracking) {
      window.SiteTracking.track(eventType, properties);
    }
  }
}
// Usage in component
import { Component, OnInit } from '@angular/core';
import { SiteTrackingService } from './site-tracking.service';
@Component({
  selector: 'app-my-component',
  template: ''
})
export class MyComponent implements OnInit {
  constructor(private tracking: SiteTrackingService) {}
  ngOnInit() {
    this.tracking.init('your-project-id');
  }
  handleClick() {
    this.tracking.track('button-click', { button: 'submit' });
  }
}

Backend Integrations

Python Integration

Python SDK

# site_tracking.py
import requests
import json
class SiteTrackingClient:
    def __init__(self, api_url, api_key):
        self.api_url = api_url
        self.api_key = api_key
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
    def track_event(self, project_id, event_type, properties=None):
        data = {
            'event_type': event_type,
            'properties': properties or {}
        }
        
        response = requests.post(
            f'{self.api_url}/api/v1/events/{project_id}',
            json=data,
            headers=self.headers
        )
        
        return response.json()
    def get_analytics(self, project_id, start_date=None, end_date=None):
        params = {}
        if start_date:
            params['start_date'] = start_date
        if end_date:
            params['end_date'] = end_date
        
        response = requests.get(
            f'{self.api_url}/api/v1/analytics/{project_id}/overview',
            params=params,
            headers=self.headers
        )
        
        return response.json()
# Usage
client = SiteTrackingClient('http://localhost:8000', 'your-api-key')
client.track_event('project-123', 'backend-event', {'action': 'create'})

Node.js Integration

Node.js SDK

// siteTracking.js
const axios = require('axios');
class SiteTrackingClient {
  constructor(apiUrl, apiKey) {
    this.apiUrl = apiUrl;
    this.apiKey = apiKey;
    this.headers = {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    };
  }
  async trackEvent(projectId, eventType, properties = {}) {
    const data = {
      event_type: eventType,
      properties
    };
    try {
      const response = await axios.post(
        `${this.apiUrl}/api/v1/events/${projectId}`,
        data,
        { headers: this.headers }
      );
      
      return response.data;
    } catch (error) {
      console.error('Error tracking event:', error);
      throw error;
    }
  }
  async getAnalytics(projectId, startDate, endDate) {
    const params = {};
    if (startDate) params.start_date = startDate;
    if (endDate) params.end_date = endDate;
    try {
      const response = await axios.get(
        `${this.apiUrl}/api/v1/analytics/${projectId}/overview`,
        { params, headers: this.headers }
      );
      
      return response.data;
    } catch (error) {
      console.error('Error getting analytics:', error);
      throw error;
    }
  }
}
// Usage
const client = new SiteTrackingClient('http://localhost:8000', 'your-api-key');
await client.trackEvent('project-123', 'server-event', { action: 'update' });

Mobile Integrations

React Native Integration

React Native Module

// SiteTracking.js
import { NativeModules, Platform } from 'react-native';
const { SiteTracking } = NativeModules;
export default {
  init: (projectId) => {
    if (Platform.OS === 'ios') {
      SiteTracking.init(projectId);
    } else {
      SiteTracking.init(projectId);
    }
  },
  track: (eventType, properties) => {
    if (Platform.OS === 'ios') {
      SiteTracking.track(eventType, properties);
    } else {
      SiteTracking.track(eventType, properties);
    }
  }
};
// Usage in component
import React, { useEffect } from 'react';
import SiteTracking from './SiteTracking';
function MyComponent() {
  useEffect(() => {
    SiteTracking.init('your-project-id');
  }, []);
  const handlePress = () => {
    SiteTracking.track('button-click', { button: 'submit' });
  };
  return ;
}

iOS Integration

Swift Integration

// SiteTracking.swift
import Foundation
class SiteTracking {
    static let shared = SiteTracking()
    private var projectId: String?
    private var apiUrl: String = "http://localhost:8000"
    func init(projectId: String) {
        self.projectId = projectId
    }
    func track(eventType: String, properties: [String: Any]) {
        guard let projectId = projectId else { return }
        
        let url = URL(string: "\(apiUrl)/api/v1/events/\(projectId)")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let data = [
            "event_type": eventType,
            "properties": properties
        ]
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: data)
            URLSession.shared.dataTask(with: request) { _, _, _ in }
                .resume()
        } catch {
            print("Error tracking event: \(error)")
        }
    }
}
// Usage
SiteTracking.shared.init("your-project-id")
SiteTracking.shared.track(eventType: "button-click", properties: ["button": "submit"])

Android Integration

Kotlin Integration

// SiteTracking.kt
import okhttp3.*
import org.json.JSONObject
class SiteTracking {
    companion object {
        private const val API_URL = "http://localhost:8000"
        private var projectId: String? = null
        private val client = OkHttpClient()
        fun init(projectId: String) {
            this.projectId = projectId
        }
        fun track(eventType: String, properties: Map) {
            val projectId = projectId ?: return
            
            val json = JSONObject().apply {
                put("event_type", eventType)
                put("properties", JSONObject(properties))
            }
            val body = RequestBody.create(
                MediaType.parse("application/json"),
                json.toString()
            )
            val request = Request.Builder()
                .url("$API_URL/api/v1/events/$projectId")
                .post(body)
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle error
                }
                override fun onResponse(call: Call, response: Response) {
                    // Handle response
                }
            })
        }
    }
    // Usage
    SiteTracking.init("your-project-id")
    SiteTracking.track("button-click", mapOf("button" to "submit"))

Integration Best Practices

  • Error Handling: Implement proper error handling for all integrations
  • Rate Limiting: Respect API rate limits and implement backoff strategies
  • Authentication: Securely store and manage API keys and tokens
  • Testing: Test integrations thoroughly before production deployment
  • Documentation: Document integration code and configuration

Security Considerations

  • API Keys: Never expose API keys in client-side code
  • Data Privacy: Respect user privacy and data protection regulations
  • Input Validation: Validate all input data before sending to API
  • HTTPS: Always use HTTPS for API communications
  • CORS: Configure CORS properly for API endpoints