API EchoTag : Développez vos propres intégrations

Published by January 27, 2025 · Reading time 10 minutes · Created by William

API EchoTag : Développez vos propres intégrations

L'API EchoTag vous donne un contrôle total sur vos données de tracking et vos automatisations. Découvrez comment créer des intégrations personnalisées, des webhooks avancés et des applications tierces qui s'intègrent parfaitement avec EchoTag.

🚀 Vue d'ensemble de l'API EchoTag

Endpoints principaux

// Base URL de l'API
const API_BASE_URL = "https://api.echotag.io/v1";

// Endpoints disponibles
const API_ENDPOINTS = {
  // Tracking
  events: "/events",
  visitors: "/visitors",
  sessions: "/sessions",

  // Triggers et automatisations
  triggers: "/triggers",
  executions: "/executions",

  // Intégrations
  webhooks: "/webhooks",
  integrations: "/integrations",

  // Analytics
  analytics: "/analytics",
  reports: "/reports",

  // Gestion des projets
  projects: "/projects",
  tags: "/tags",
};

Authentification

// Authentification par API Key
const API_KEY = "et_live_abc123def456ghi789";

// Headers d'authentification
const headers = {
  Authorization: `Bearer ${API_KEY}`,
  "Content-Type": "application/json",
  Accept: "application/json",
};

// Exemple de requête authentifiée
fetch(`${API_BASE_URL}/events`, {
  method: "GET",
  headers: headers,
});

📊 API de Tracking

Envoyer des événements

// Envoyer un événement simple
const trackEvent = async (eventData) => {
  const response = await fetch(`${API_BASE_URL}/events`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      project_id: "proj_abc123",
      event_type: "page_view",
      visitor_id: "vis_xyz789",
      data: {
        url: "https://example.com/products",
        title: "Produits",
        referrer: "https://google.com",
      },
      timestamp: new Date().toISOString(),
    }),
  });

  return response.json();
};

// Envoyer un événement e-commerce
const trackPurchase = async (purchaseData) => {
  const response = await fetch(`${API_BASE_URL}/events`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      project_id: "proj_abc123",
      event_type: "purchase",
      visitor_id: "vis_xyz789",
      data: {
        order_id: "ORD_123456",
        revenue: 89.99,
        currency: "EUR",
        products: [
          {
            id: "PROD_001",
            name: "T-shirt Premium",
            price: 29.99,
            quantity: 2,
          },
        ],
        shipping: 4.99,
        tax: 15.0,
      },
    }),
  });

  return response.json();
};

Récupérer les événements

// Récupérer les événements d'un visiteur
const getVisitorEvents = async (visitorId, options = {}) => {
  const params = new URLSearchParams({
    visitor_id: visitorId,
    limit: options.limit || 100,
    offset: options.offset || 0,
    event_type: options.eventType || "",
    start_date: options.startDate || "",
    end_date: options.endDate || "",
  });

  const response = await fetch(`${API_BASE_URL}/events?${params}`, {
    method: "GET",
    headers: headers,
  });

  return response.json();
};

// Exemple d'utilisation
const events = await getVisitorEvents("vis_xyz789", {
  limit: 50,
  eventType: "purchase",
  startDate: "2025-01-01",
});

🔧 API de Triggers

Créer un trigger personnalisé

// Créer un trigger via API
const createTrigger = async (triggerConfig) => {
  const response = await fetch(`${API_BASE_URL}/triggers`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      project_id: "proj_abc123",
      name: triggerConfig.name,
      description: triggerConfig.description,
      event_type: triggerConfig.eventType,
      conditions: triggerConfig.conditions,
      actions: triggerConfig.actions,
      is_active: true,
    }),
  });

  return response.json();
};

// Exemple : Trigger de panier abandonné
const cartAbandonmentTrigger = {
  name: "Cart Abandonment Recovery",
  description: "Récupère les paniers abandonnés",
  eventType: "add_to_cart",
  conditions: {
    url: { contains: "/cart" },
    time_since_event: { greater_than: 1800000 }, // 30 minutes
    no_purchase: true,
  },
  actions: [
    {
      type: "add_tag",
      tag: "cart_abandoned",
    },
    {
      type: "webhook",
      url: "https://your-api.com/cart-recovery",
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: {
        visitor_id: "{{visitor.id}}",
        cart_value: "{{event.cart_value}}",
        cart_items: "{{event.cart_items}}",
      },
    },
  ],
};

const trigger = await createTrigger(cartAbandonmentTrigger);

Gérer les triggers existants

// Lister tous les triggers
const listTriggers = async (projectId) => {
  const response = await fetch(
    `${API_BASE_URL}/triggers?project_id=${projectId}`,
    {
      method: "GET",
      headers: headers,
    },
  );

  return response.json();
};

// Mettre à jour un trigger
const updateTrigger = async (triggerId, updates) => {
  const response = await fetch(`${API_BASE_URL}/triggers/${triggerId}`, {
    method: "PATCH",
    headers: headers,
    body: JSON.stringify(updates),
  });

  return response.json();
};

// Désactiver un trigger
await updateTrigger("trig_abc123", {
  is_active: false,
});

🔗 API de Webhooks

Créer un webhook personnalisé

// Créer un webhook
const createWebhook = async (webhookConfig) => {
  const response = await fetch(`${API_BASE_URL}/webhooks`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      project_id: "proj_abc123",
      name: webhookConfig.name,
      url: webhookConfig.url,
      method: webhookConfig.method || "POST",
      headers: webhookConfig.headers || {},
      events: webhookConfig.events || ["*"],
      is_active: true,
      retry_config: {
        max_attempts: 3,
        backoff_multiplier: 2,
        max_delay: 30000,
      },
    }),
  });

  return response.json();
};

// Exemple : Webhook pour CRM
const crmWebhook = {
  name: "CRM Integration",
  url: "https://your-crm.com/api/leads",
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_CRM_KEY",
    "Content-Type": "application/json",
  },
  events: ["lead_qualified", "purchase", "cart_abandoned"],
};

const webhook = await createWebhook(crmWebhook);

Gérer les webhooks

// Lister les webhooks
const listWebhooks = async (projectId) => {
  const response = await fetch(
    `${API_BASE_URL}/webhooks?project_id=${projectId}`,
    {
      method: "GET",
      headers: headers,
    },
  );

  return response.json();
};

// Tester un webhook
const testWebhook = async (webhookId) => {
  const response = await fetch(`${API_BASE_URL}/webhooks/${webhookId}/test`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      test_data: {
        event_type: "test_event",
        visitor_id: "test_visitor",
        data: {
          test: true,
          timestamp: new Date().toISOString(),
        },
      },
    }),
  });

  return response.json();
};

// Obtenir les logs d'un webhook
const getWebhookLogs = async (webhookId, options = {}) => {
  const params = new URLSearchParams({
    limit: options.limit || 100,
    offset: options.offset || 0,
    status: options.status || "",
    start_date: options.startDate || "",
    end_date: options.endDate || "",
  });

  const response = await fetch(
    `${API_BASE_URL}/webhooks/${webhookId}/logs?${params}`,
    {
      method: "GET",
      headers: headers,
    },
  );

  return response.json();
};

📈 API d'Analytics

Récupérer les analytics

// Récupérer les métriques d'un projet
const getProjectAnalytics = async (projectId, options = {}) => {
  const params = new URLSearchParams({
    project_id: projectId,
    period: options.period || "30d",
    start_date: options.startDate || "",
    end_date: options.endDate || "",
    metrics: options.metrics || "visitors,events,conversions",
  });

  const response = await fetch(`${API_BASE_URL}/analytics?${params}`, {
    method: "GET",
    headers: headers,
  });

  return response.json();
};

// Récupérer les analytics temps réel
const getRealTimeAnalytics = async (projectId) => {
  const response = await fetch(
    `${API_BASE_URL}/analytics/realtime?project_id=${projectId}`,
    {
      method: "GET",
      headers: headers,
    },
  );

  return response.json();
};

// Récupérer les rapports personnalisés
const getCustomReport = async (reportConfig) => {
  const response = await fetch(`${API_BASE_URL}/reports`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      project_id: reportConfig.projectId,
      report_type: reportConfig.type,
      filters: reportConfig.filters,
      group_by: reportConfig.groupBy,
      metrics: reportConfig.metrics,
      date_range: reportConfig.dateRange,
    }),
  });

  return response.json();
};

🏷️ API de Tags et Segmentation

Gérer les tags

// Créer un tag
const createTag = async (tagConfig) => {
  const response = await fetch(`${API_BASE_URL}/tags`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      project_id: tagConfig.projectId,
      name: tagConfig.name,
      description: tagConfig.description,
      color: tagConfig.color || "#3B82F6",
    }),
  });

  return response.json();
};

// Assigner un tag à un visiteur
const assignTagToVisitor = async (visitorId, tagId) => {
  const response = await fetch(`${API_BASE_URL}/visitors/${visitorId}/tags`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      tag_id: tagId,
    }),
  });

  return response.json();
};

// Récupérer les visiteurs par tag
const getVisitorsByTag = async (tagId, options = {}) => {
  const params = new URLSearchParams({
    tag_id: tagId,
    limit: options.limit || 100,
    offset: options.offset || 0,
  });

  const response = await fetch(`${API_BASE_URL}/visitors?${params}`, {
    method: "GET",
    headers: headers,
  });

  return response.json();
};

🔐 SDK EchoTag

Installation du SDK

# NPM
npm install @echotag/sdk

# Yarn
yarn add @echotag/sdk

Utilisation du SDK

import { EchoTagAPI } from "@echotag/sdk";

// Initialiser le SDK
const echotag = new EchoTagAPI({
  apiKey: "et_live_abc123def456ghi789",
  projectId: "proj_abc123",
  baseUrl: "https://api.echotag.io/v1",
});

// Envoyer un événement
await echotag.events.track({
  eventType: "page_view",
  visitorId: "vis_xyz789",
  data: {
    url: "https://example.com",
    title: "Accueil",
  },
});

// Créer un trigger
const trigger = await echotag.triggers.create({
  name: "Custom Trigger",
  eventType: "custom_event",
  conditions: {
    // vos conditions
  },
  actions: [
    // vos actions
  ],
});

// Récupérer les analytics
const analytics = await echotag.analytics.get({
  period: "30d",
  metrics: ["visitors", "events", "conversions"],
});

🛠️ Cas d'usage avancés

Intégration CRM personnalisée

// Intégration avec un CRM personnalisé
class CustomCRMIntegration {
  constructor(apiKey, crmConfig) {
    this.echotag = new EchoTagAPI({ apiKey });
    this.crmConfig = crmConfig;
  }

  async syncLead(visitorId) {
    // Récupérer les données du visiteur
    const visitor = await this.echotag.visitors.get(visitorId);

    // Récupérer les événements récents
    const events = await this.echotag.events.list({
      visitorId,
      limit: 50,
    });

    // Calculer le score de lead
    const leadScore = this.calculateLeadScore(events);

    // Créer le lead dans le CRM
    const lead = await this.createCRMLead({
      email: visitor.email,
      name: visitor.name,
      leadScore,
      events: events.data,
      tags: visitor.tags,
    });

    return lead;
  }

  calculateLeadScore(events) {
    let score = 0;

    events.forEach((event) => {
      switch (event.event_type) {
        case "page_view":
          score += 1;
          break;
        case "form_submit":
          score += 10;
          break;
        case "purchase":
          score += 50;
          break;
      }
    });

    return Math.min(score, 100);
  }

  async createCRMLead(leadData) {
    // Implémentation spécifique à votre CRM
    const response = await fetch(this.crmConfig.apiUrl, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${this.crmConfig.apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(leadData),
    });

    return response.json();
  }
}

Dashboard personnalisé

// Dashboard personnalisé avec l'API EchoTag
class CustomDashboard {
  constructor(apiKey, projectId) {
    this.echotag = new EchoTagAPI({ apiKey });
    this.projectId = projectId;
  }

  async getDashboardData() {
    const [analytics, triggers, webhooks] = await Promise.all([
      this.echotag.analytics.get({ period: "30d" }),
      this.echotag.triggers.list({ projectId: this.projectId }),
      this.echotag.webhooks.list({ projectId: this.projectId }),
    ]);

    return {
      analytics,
      triggers: triggers.data,
      webhooks: webhooks.data,
      summary: this.calculateSummary(analytics),
    };
  }

  calculateSummary(analytics) {
    return {
      totalVisitors: analytics.visitors.total,
      totalEvents: analytics.events.total,
      conversionRate:
        (analytics.conversions.total / analytics.visitors.total) * 100,
      topPages: analytics.pages.slice(0, 5),
      topEvents: analytics.events.by_type.slice(0, 5),
    };
  }

  async createCustomReport(reportConfig) {
    return await this.echotag.reports.create({
      projectId: this.projectId,
      ...reportConfig,
    });
  }
}

📊 Monitoring et Debugging

Logs et monitoring

// Monitoring des appels API
class EchoTagMonitor {
  constructor(apiKey) {
    this.echotag = new EchoTagAPI({ apiKey });
    this.logs = [];
  }

  async trackAPICall(endpoint, method, data) {
    const startTime = Date.now();

    try {
      const response = await this.echotag.request(endpoint, method, data);

      this.logs.push({
        endpoint,
        method,
        status: "success",
        duration: Date.now() - startTime,
        timestamp: new Date().toISOString(),
      });

      return response;
    } catch (error) {
      this.logs.push({
        endpoint,
        method,
        status: "error",
        error: error.message,
        duration: Date.now() - startTime,
        timestamp: new Date().toISOString(),
      });

      throw error;
    }
  }

  getPerformanceStats() {
    const successfulCalls = this.logs.filter((log) => log.status === "success");
    const failedCalls = this.logs.filter((log) => log.status === "error");

    return {
      totalCalls: this.logs.length,
      successRate: (successfulCalls.length / this.logs.length) * 100,
      averageResponseTime:
        successfulCalls.reduce((sum, log) => sum + log.duration, 0) /
        successfulCalls.length,
      errorRate: (failedCalls.length / this.logs.length) * 100,
    };
  }
}

🔒 Sécurité et bonnes pratiques

Gestion des clés API

// Gestion sécurisée des clés API
class SecureEchoTagClient {
  constructor() {
    this.apiKey = process.env.ECHOTAG_API_KEY;
    this.projectId = process.env.ECHOTAG_PROJECT_ID;

    if (!this.apiKey) {
      throw new Error("ECHOTAG_API_KEY environment variable is required");
    }
  }

  // Rotation automatique des clés
  async rotateAPIKey() {
    const response = await fetch(`${API_BASE_URL}/auth/rotate-key`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${this.apiKey}`,
        "Content-Type": "application/json",
      },
    });

    const { new_api_key } = await response.json();

    // Mettre à jour la variable d'environnement
    process.env.ECHOTAG_API_KEY = new_api_key;
    this.apiKey = new_api_key;

    return new_api_key;
  }

  // Validation des données
  validateEventData(eventData) {
    const required = ["event_type", "visitor_id"];
    const missing = required.filter((field) => !eventData[field]);

    if (missing.length > 0) {
      throw new Error(`Missing required fields: ${missing.join(", ")}`);
    }

    return true;
  }
}

📚 Documentation complète

Endpoints détaillés

// Documentation des endpoints
const API_DOCUMENTATION = {
  events: {
    POST: "Créer un événement",
    GET: "Récupérer les événements",
    parameters: {
      project_id: "string (required)",
      event_type: "string (required)",
      visitor_id: "string (required)",
      data: "object (optional)",
    },
  },
  triggers: {
    POST: "Créer un trigger",
    GET: "Lister les triggers",
    PATCH: "Mettre à jour un trigger",
    DELETE: "Supprimer un trigger",
  },
  webhooks: {
    POST: "Créer un webhook",
    GET: "Lister les webhooks",
    PUT: "Mettre à jour un webhook",
    DELETE: "Supprimer un webhook",
  },
};

Conclusion

L'API EchoTag vous donne un contrôle total sur vos données et vos automatisations. Que vous développiez des intégrations personnalisées, des dashboards avancés ou des applications tierces, l'API EchoTag est conçue pour être flexible et puissante.

Prochaines étapes :

  1. Obtenir votre clé API
  2. Explorer la documentation
  3. Tester avec le SDK
  4. Créer votre première intégration

Ressources :


Prêt à développer avec l'API EchoTag ? Commencez maintenant.

xs
PrivacyTermsapp icon