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

# Attribution Tracking

> Complete guide for implementing attribution tracking in Masivo - understand attribution parameters, tracking IDs, and how to measure campaign effectiveness across all customer touchpoints

## Overview

Attribution tracking in Masivo enables you to measure and analyze the complete customer journey across all touchpoints. By implementing proper attribution parameters, you can track which marketing campaigns, channels, and touchpoints drive customer behavior, purchases, and engagement. This guide covers the complete attribution system, from generating tracking IDs to analyzing campaign performance.

<Note>
  Attribution data is automatically collected from deeplinks and can be manually
  attached to events. All attribution parameters are optional but provide
  valuable insights when implemented consistently across your marketing
  campaigns.
</Note>

## Understanding Attribution Parameters

### Attribution Data Structure

Attribution data in Masivo consists of several key parameters that help track the customer journey:

```typescript theme={null}
interface AttributionData {
  tracking_id?: string; // Unique identifier for tracking user sessions
  utm_source?: string; // Traffic source (e.g., "google", "facebook")
  utm_medium?: string; // Marketing medium (e.g., "cpc", "email", "social")
  utm_campaign?: string; // Campaign name (e.g., "summer-sale-2024")
  utm_term?: string; // Paid search keywords
  utm_content?: string; // Ad variation or email version
  utm_referral?: string; // Specific referral source
}
```

### How Attribution Works in Masivo

Attribution data flows through the system in several ways:

1. **Automatic Collection**: Generated automatically when customers click deeplinks
2. **Event Attribution**: Manually attached to events via the API
3. **Journey Tracking**: Automatically propagated through customer journey steps
4. **Analytics**: Aggregated for campaign performance analysis

## 1. Tracking ID Generation and Usage

### Understanding Tracking IDs

The `tracking_id` is a unique identifier that connects customer actions across your marketing funnel. It's automatically generated for deeplinks and can be manually created for custom tracking scenarios.

### Automatic Tracking ID Generation

When customers click on a Masivo deeplink, a `tracking_id` is automatically generated:

```typescript theme={null}
// This happens automatically in Masivo's deeplink handler
import { v4 as uuidv4 } from "uuid";

const tracking_id = uuidv4(); // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// Added to attribution data
const attribution = {
  tracking_id,
  utm_source: "email",
  utm_medium: "newsletter",
  utm_campaign: "spring-collection"
};

// Appended to destination URL
const destinationUrl =
  "https://yourapp.com/products?$tracking_id=f47ac10b-58cc-4372-a567-0e02b2c3d479";
```

### Extracting Tracking ID from URLs

In your application, extract the `tracking_id` from URL parameters to maintain attribution throughout the customer journey:

```typescript theme={null}
// Mobile app or web application
const extractTrackingId = (url: string): string | null => {
  try {
    const urlObj = new URL(url);
    return urlObj.searchParams.get("$tracking_id");
  } catch (error) {
    console.error("Invalid URL:", error);
    return null;
  }
};

// Usage examples
const tracking_id = extractTrackingId(window.location.href);
// Or from deep link parameters in mobile apps
const tracking_id = extractTrackingId(incomingDeepLink);

// Store for later use in events
if (tracking_id) {
  // Store in session storage, app state, or local storage
  sessionStorage.setItem("masivo_tracking_id", tracking_id);
}
```

### Using Tracking ID in Events

Once you have the `tracking_id`, include it in attribution data when sending events:

```typescript theme={null}
const sendEventWithAttribution = async (eventData: {
  type: string;
  customer_id: string;
  brand_id: string | null;
  [key: string]: any;
}) => {
  // Retrieve stored tracking ID
  const tracking_id = sessionStorage.getItem("masivo_tracking_id");

  const payload = {
    ...eventData,
    attribution: {
      tracking_id,
      // Add other attribution parameters as needed
      utm_source: "mobile_app",
      utm_medium: "push_notification"
    }
  };

  const response = await fetch(
    "https://app.masivo.ai/api/storefront/v1/behavior/events",
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(payload)
    }
  );

  return response.json();
};

// Example: Track purchase with attribution
await sendEventWithAttribution({
  type: "PURCHASE",
  customer_id: "customer-123",
  brand_id: "brand-456",
  order: {
    purchase_id: "order-789",
    value: 99.99,
    products: [
      {
        sku: "PROD-001",
        amount: 1,
        value: 99.99
      }
    ],
    payment_method: "CREDIT"
  }
});
```

## 2. UTM Parameters and Campaign Tracking

### Understanding UTM Parameters

UTM parameters are standardized tags that help track the effectiveness of marketing campaigns:

#### utm\_source

Identifies the traffic source:

* `"google"` - Google search or ads
* `"facebook"` - Facebook ads or posts
* `"email"` - Email campaigns
* `"newsletter"` - Newsletter campaigns
* `"organic"` - Organic/direct traffic

#### utm\_medium

Describes the marketing medium:

* `"cpc"` - Cost-per-click advertising
* `"email"` - Email marketing
* `"social"` - Social media
* `"push"` - Push notifications
* `"sms"` - SMS campaigns

#### utm\_campaign

Names the specific campaign:

* `"summer-sale-2024"`
* `"new-user-onboarding"`
* `"cart-abandonment-recovery"`

#### utm\_term

Used for paid search keywords:

* `"premium headphones"`
* `"wireless earbuds"`

#### utm\_content

Differentiates ad variations:

* `"banner-ad-v1"`
* `"email-button-cta"`
* `"video-ad-30s"`

### Implementing UTM Tracking

```typescript theme={null}
const sendPurchaseWithUTMTracking = async (
  customerId: string,
  orderData: any,
  campaignInfo: {
    source: string;
    medium: string;
    campaign: string;
    term?: string;
    content?: string;
  }
) => {
  const attribution = {
    tracking_id: sessionStorage.getItem("masivo_tracking_id"),
    utm_source: campaignInfo.source,
    utm_medium: campaignInfo.medium,
    utm_campaign: campaignInfo.campaign,
    utm_term: campaignInfo.term,
    utm_content: campaignInfo.content,
    revenue: orderData.total
  };

  const eventData = {
    type: "PURCHASE",
    customer_id: customerId,
    brand_id: orderData.brand_id,
    attribution,
    order: {
      purchase_id: orderData.id,
      value: orderData.total,
      products: orderData.items.map(item => ({
        sku: item.sku,
        amount: item.quantity,
        value: item.price
      })),
      payment_method: orderData.payment_method
    }
  };

  return await fetch(
    "https://app.masivo.ai/api/storefront/v1/behavior/events",
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(eventData)
    }
  );
};

// Usage example
await sendPurchaseWithUTMTracking("customer-123", orderData, {
  source: "google",
  medium: "social",
  campaign: "spring-collection-launch",
  content: "carousel-ad-variant-a"
});
```

## 3. Revenue and Cost Attribution

### Tracking Revenue Attribution

Revenue attribution helps measure the financial impact of marketing campaigns and track the revenue and cost at each step of the customer journey until completion, providing a complete view of campaign ROI:

```typescript theme={null}
const trackRevenueAttribution = async (
  customerId: string,
  purchaseData: {
    order_value: number;
    acquisition_cost: number;
    campaign_source: string;
  }
) => {
  const attribution = {
    tracking_id: sessionStorage.getItem("masivo_tracking_id"),
    revenue: purchaseData.order_value,
    cost: purchaseData.acquisition_cost,
    utm_source: purchaseData.campaign_source,
    utm_medium: "paid_advertising"
  };

  const eventData = {
    type: "PURCHASE",
    customer_id: customerId,
    brand_id: "your-brand-id",
    attribution,
    order: {
      purchase_id: `order-${Date.now()}`,
      value: purchaseData.order_value,
      products: [
        /* order products */
      ],
      payment_method: "CREDIT"
    }
  };

  return await sendEventWithAttribution(eventData);
};
```

### Cost Tracking for Campaign Analysis

Track marketing costs to calculate ROI:

```typescript theme={null}
const trackCampaignCost = async (
  customerId: string,
  action: string,
  campaignCost: number
) => {
  const attribution = {
    tracking_id: sessionStorage.getItem("masivo_tracking_id"),
    cost: campaignCost,
    utm_source: "google_ads",
    utm_medium: "cpc",
    utm_campaign: "holiday-sale-2024"
  };

  const eventData = {
    type: action, // e.g., "ADD_TO_CART", "VIEW_PRODUCT"
    customer_id: customerId,
    brand_id: "your-brand-id",
    attribution
  };

  return await sendEventWithAttribution(eventData);
};
```

For more information about implementing campaigns and measuring their effectiveness, see the [Journey Triggers Guide](/api-reference/guides/journey-triggers) and [Customer Audience Enrollment Guide](/api-reference/guides/customer-audience-enrollment).
