# Marketing analytics

Track and analyze ad campaign performance.

> Marketing analytics is in private preview.

Marketing analytics combines Stripe payment data with Google Ads and Meta Ads data so you can:

- See new customers, subscriptions, and net revenue attributed to your campaigns.
- Measure return on ad spend (ROAS) with metrics that account for subscriptions, trial conversions, refunds, and disputes.
- Use a large language model (LLM) to analyze ad performance with [Stripe MCP](https://docs.stripe.com/mcp.md).
- Opt in to send conversion signals to Google Ads and Meta Ads.

### Join the waitlist

Enter your email to request early access.

```bash
curl https://docs.stripe.com/preview/register \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Referer: https://docs.stripe.com/reports/marketing-analytics" \
  -d '{"email": "EMAIL", "preview": "marketing_analytics_preview"}'
```

You need access to the private preview to use `marketing_attributions`. If your account doesn’t have access, the API returns an unknown parameter error for `marketing_attributions`.

The basic attribution pipeline works as follows:

1. The ad campaign passes query parameters to your landing page when a customer clicks an ad. These include UTM parameters such as `utm_source`, and a click ID such as `gclid` or `fbclid`.
2. The customer visits your page with UTM parameters that indicate the referral source, and a click ID that identifies the ad click.
3. A cookie stores those parameters. Your browser includes the cookie in back-end requests, such as the request that creates a Checkout Session or a Customer.
4. Your back end passes the UTM parameters and click ID to Stripe in the `marketing_attributions` parameter.

This attribution pipeline uses last touch. This means Stripe attributes a purchase to the last ad the customer clicked before buying.

## Before you begin

Make sure that you meet these requirements:

- You have a [Google Ads](https://ads.google.com) or [Meta Ads](https://adsmanager.facebook.com) account.
- Your back end [creates Checkout Sessions](https://docs.stripe.com/api/checkout/sessions/create.md) or [creates Customers](https://docs.stripe.com/api/customers/create.md).

## Set up attribution in your ad platform

> #### If you already track ad clicks
> 
> If you already have an attribution pipeline that tracks ad clicks (for example, using a cookie or another system), skip to [Pass attribution data to Stripe](https://docs.stripe.com/reports/marketing-analytics.md#pass-attribution-data-to-stripe).

Configure your ad platform to add attribution query parameters to your landing page URL when a customer clicks an ad.

#### Google Ads

In [Google Ads](https://ads.google.com/aw/settings/account), go to **Admin** > **Account Settings**. Under **Tracking**, set your final URL suffix to:

```
utm_source=google&utm_medium=cpc&utm_id={campaignid}&utm_adgroup={adgroupid}&utm_content={creative}&utm_term={keyword}
```

When a customer clicks your ad, Google passes attribution metadata to your landing page as query parameters. Set **Auto-tagging** to `Yes` (this is the default), so that Google adds a `gclid` click ID to the URL.
![Google Ads attribution settings](https://b.stripecdn.com/docs-statics-srv/assets/google_tracking_screenshot.0a04e9d35ee80606bb71106251973ee8.png)

#### Meta Ads

In Meta, you set URL parameters on each ad. To set them on all your ads together:

1. Go to [Ads in Meta Ads Manager](https://adsmanager.facebook.com/adsmanager/manage/ads) and select all the ads you want to track.

2. Click the dropdown arrow next to **Edit**. Under **Tracking**, select **URL parameters**.

3. Set the URL parameters to the following value, and save your changes:

   ```
   utm_source={{site_source_name}}&utm_medium=cpc&utm_id={{campaign.id}}&utm_adgroup={{adset.id}}&utm_content={{ad.id}}
   ```

When a customer clicks your ad, Meta replaces each dynamic parameter with the value for that ad and passes the result to your landing page as query parameters. For example, `{{site_source_name}}` becomes `fb` for Facebook or `ig` for Instagram. Meta also adds an `fbclid` click ID to the URL.

## Capture attribution parameters on your landing page

Store the attribution query parameters in a cookie when a customer arrives on your landing page. Cookies can persist across subdomains, expire automatically, and are included in requests to your domain. Keep in mind consent and privacy laws in your region. You might want to use a service such as [CookieBot](https://cookiebot.com/) to manage consent.

The following function stores the attribution parameters in a cookie. Replace `COOKIE_DOMAIN` with your root domain (include a leading dot to share the cookie across subdomains), or leave it as `undefined` to scope the cookie to the current hostname.

```ts
// Replace with your root domain (include a leading dot to share
// the cookie across subdomains), or leave as undefined to scope
// it to the current hostname.
const COOKIE_DOMAIN: string | undefined = ".{{yourdomain.com}}";

export const STRIPE_ATTRIBUTION_COOKIE_NAME = "__stripe_attrib";
const MAX_AGE_SECONDS = 30 * 24 * 60 * 60;

const ATTRIBUTION_PARAMS = [
  "utm_source",
  "utm_medium",
  "utm_adgroup",
  "utm_term",
  "utm_content",
  "utm_id",
  "gclid",
  "fbclid",
] as const;

export function captureStripeAttribution(): void {
  const params = new URLSearchParams(window.location.search);
  const attribution: Record<string, string> = {};

  for (const key of ATTRIBUTION_PARAMS) {
    const value = params.get(key);
    if (value) {
      attribution[key] = value.slice(0, 500);
    }
  }

  if (Object.keys(attribution).length === 0) {
    return;
  }

  attribution.landing_page = window.location.pathname;
  attribution.touch_ts = String(Math.floor(Date.now() / 1000));

  const secure = window.location.protocol === "https:" ? ";Secure" : "";
  const domain = COOKIE_DOMAIN ? `;domain=${COOKIE_DOMAIN}` : "";

  document.cookie =
    `${STRIPE_ATTRIBUTION_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(attribution))}` +
    `;path=/;max-age=${MAX_AGE_SECONDS};SameSite=Lax${domain}${secure}`;
}
```

Use it on your landing page. The following example is for Next.js App Router. Adapt it to your framework’s route-change hook (for example, `useLocation` in React Router).

Select the integration that matches how you collect payments. If you use Stripe Checkout, select **Checkout Session**. Otherwise, select **Customer** to pass the attribution data when you create the Customer.

#### Integration - Checkout Session

```ts
"use client";

import { useEffect } from "react";
import { useSearchParams } from "next/navigation";

export function MerchantLandingPage() {
  const searchParams = useSearchParams();

  useEffect(() => {
    captureStripeAttribution();
  }, [searchParams]); // re-runs on client-side navigation

  async function startCheckout() {
    const response = await fetch("/api/create-checkout-session", {
      method: "POST",
    });
    const { url } = await response.json();
    window.location.assign(url);
  }
  return <button onClick={startCheckout}>Buy now</button>;
}
```

#### Integration - Customer

```ts
"use client";

import { useEffect } from "react";
import { useSearchParams } from "next/navigation";

export function MerchantLandingPage() {
  const searchParams = useSearchParams();

  useEffect(() => {
    captureStripeAttribution();
  }, [searchParams]); // re-runs on client-side navigation

  async function handleSignUp() {
    const response = await fetch("/api/create-customer", {
      method: "POST",
    });
    // ...other logic that runs
  }
  return <button onClick={handleSignUp}>Sign up</button>;
}
```

## Pass attribution data to Stripe

During this private preview, pass attribution data in the `marketing_attributions` parameter when you [create a Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) or [create a Customer](https://docs.stripe.com/api/customers/create.md). If you use Checkout, pass it on the Checkout Session. Otherwise, pass it on the Customer.

| API parameter | Required | Value |
| --- | --- | --- |
| `utm_id` | Yes | Ad campaign ID from the `utm_id` value of your cookie. If not set, attribution defaults to organic. |
| `utm_source` | Yes, if you set `click_id` | `utm_source` value. Use `google` for Google Ads. For Meta Ads, use the value that Meta sets, such as `fb` or `ig`. Stripe uses this value to identify the ad platform for `click_id`, and ignores `click_id` if the value doesn’t identify a supported ad platform. |
| `utm_medium` | No | `utm_medium` value |
| `utm_term` | No | `utm_term` value |
| `utm_adgroup` | No | `utm_adgroup` value |
| `utm_content` | No | `utm_content` value |
| `click_id` | No | Ad platform click ID. For Google Ads, use the `gclid` value. For Meta Ads, use the `fbclid` value. |
| `occurred_at` | Yes | Unix timestamp for when attribution was captured. The timestamp can’t be in the future. |

You can send one object in the `marketing_attributions` array. Pass all available UTM values to support segmentation and filtering in the Dashboard.

On your server, read the attribution cookie and convert it to the `marketing_attributions` format. Add the following code to `attribution.ts`:

```ts
function optionalString(value: unknown): string | undefined {
  return typeof value === "string" && value.length > 0
    ? value.slice(0, 500)
    : undefined;
}

type MarketingAttribution = {
  utm_id?: string | undefined;
  utm_source?: string | undefined;
  utm_medium?: string | undefined;
  utm_term?: string | undefined;
  utm_adgroup?: string | undefined;
  utm_content?: string | undefined;
  click_id?: string | undefined;
  occurred_at: number;
  ad_conversion?: {
    consent_collected: boolean;
    source_url?: string | undefined;
    user_agent?: string | undefined;
  };
};

export function attributionCookieToMarketingAttributions(
  cookieValue: string | undefined,
): MarketingAttribution[] {
  if (!cookieValue) {
    return [];
  }

  try {
    const attribution = JSON.parse(decodeURIComponent(cookieValue)) as Record<
      string,
      unknown
    >;
    const occurredAt = Number(attribution.touch_ts);
    const now = Math.floor(Date.now() / 1000);
    if (!Number.isInteger(occurredAt)) {
      return [];
    }

    return [
      {
        utm_id: optionalString(attribution.utm_id),
        utm_source: optionalString(attribution.utm_source),
        utm_medium: optionalString(attribution.utm_medium),
        utm_term: optionalString(attribution.utm_term),
        utm_adgroup: optionalString(attribution.utm_adgroup),
        utm_content: optionalString(attribution.utm_content),
        click_id:
          optionalString(attribution.gclid) ??
          optionalString(attribution.fbclid),
        occurred_at: Math.min(occurredAt, now),
      },
    ];
  } catch {
    return [];
  }
}
```

Then pass the attribution data when you create the Checkout Session or Customer:

#### Checkout Session

The Stripe Node SDK’s TypeScript types don’t include the private-preview `marketing_attributions` parameter. You must extend `Stripe.Checkout.SessionCreateParams` with this parameter before passing it to `stripe.checkout.sessions.create`.

Use the API key already configured for your integration. If it’s a [restricted API key](https://docs.stripe.com/keys/restricted-api-keys.md), make sure it has the `Checkout Sessions: Write` permission.

```ts
import Stripe from "stripe";
import { NextRequest, NextResponse } from "next/server";
import {
  attributionCookieToMarketingAttributions,
  STRIPE_ATTRIBUTION_COOKIE_NAME,
} from "./attribution";

const stripe = new Stripe(process.env.STRIPE_API_KEY!);

type SessionCreateParamsWithAttributions = Stripe.Checkout.SessionCreateParams & {
  marketing_attributions: ReturnType<
    typeof attributionCookieToMarketingAttributions
  >;
};

export async function POST(request: NextRequest) {
  const attributionCookie = request.cookies.get(
    STRIPE_ATTRIBUTION_COOKIE_NAME,
  )?.value;
  const params: SessionCreateParamsWithAttributions = {
    // ... your other checkout parameters
    marketing_attributions: attributionCookieToMarketingAttributions(attributionCookie),
  };

  const session = await stripe.checkout.sessions.create(params);

  return NextResponse.json({ url: session.url });
}
```

#### Customer

The Stripe Node SDK’s TypeScript types don’t include the private-preview `marketing_attributions` parameter. You must extend `Stripe.CustomerCreateParams` with this parameter before passing it to `stripe.customers.create`.

Use the API key already configured for your integration. If it’s a [restricted API key](https://docs.stripe.com/keys/restricted-api-keys.md), make sure it has the `Customers: Write` permission.

```ts
import Stripe from "stripe";
import { NextRequest, NextResponse } from "next/server";
import {
  attributionCookieToMarketingAttributions,
  STRIPE_ATTRIBUTION_COOKIE_NAME,
} from "./attribution";

const stripe = new Stripe(process.env.STRIPE_API_KEY!);

type CustomerCreateParamsWithAttributions = Stripe.CustomerCreateParams & {
  marketing_attributions: ReturnType<
    typeof attributionCookieToMarketingAttributions
  >;
};

export async function POST(request: NextRequest) {
  const attributionCookie = request.cookies.get(
    STRIPE_ATTRIBUTION_COOKIE_NAME,
  )?.value;

  const params: CustomerCreateParamsWithAttributions = {
    // ... your other customer parameters
    marketing_attributions: attributionCookieToMarketingAttributions(attributionCookie),
  };

  const customer = await stripe.customers.create(params);

  return NextResponse.json({ id: customer.id });
}
```

## Connect your ad account in the Dashboard

Go to the [Marketing page](https://dashboard.stripe.com/marketing) in the Dashboard, and sign in to your Google Ads or Meta Ads account. You can see your existing campaigns there.

## Enable conversion signals

Conversion APIs send data back to ad platforms about successful conversions, which allows platforms to improve ad targeting.

To enable conversion signals:

1. On the [Marketing settings page](https://dashboard.stripe.com/marketing/settings), go to **Conversions** and click **Edit** next to a conversion.
2. Under **Ad platforms**, select **Google Ads**, **Meta Ads**, or both. If you select **Meta Ads**, choose a **Pixel** to receive your events. Stripe sends every Meta Ads conversion to this pixel.
3. Click **Save**.
4. In your API call, set `marketing_attributions[0][ad_conversion][consent_collected]` to `true` only when the customer consents to sending conversion data. It defaults to `false`.

If you set a minimum charge for **Purchase**, it applies to both Google Ads and Meta Ads.

#### Google Ads

When you enable conversion signals, Stripe sends conversion data to Google using the `marketing_attributions[0][click_id]` value. For Checkout Sessions, the conversion value is the amount charged in the Checkout Session.

#### Meta Ads

When you enable conversion signals, Stripe sends conversion data to Meta using the `fbclid` value in `marketing_attributions[0][click_id]`. For Checkout Sessions, the conversion value is the amount charged in the Checkout Session.

Meta also requires these parameters in `marketing_attributions[0][ad_conversion]`:

- `source_url`: The HTTPS URL of the page where the customer converted. Stripe removes the query string and fragment before sending it to Meta.
- `user_agent`: The `User-Agent` header of the customer’s browser.

If `source_url` or `user_agent` is missing or invalid, Stripe doesn’t send that conversion to Meta.

## Test the integration

Using your local development environment and a Stripe Sandbox, append attribution parameters to your localhost URL, for example `?utm_source=google&utm_id=test&gclid=test_id`. This triggers your cookie flow. Complete a test checkout or create a test Customer, then check [attributions in your test Dashboard](https://dashboard.stripe.com/test/marketing/attributions). If you see data in the attributions table, the integration is working.

Alternatively, click **Test integration** in the [Marketing settings page](https://dashboard.stripe.com/marketing/settings) to generate a prompt for your AI coding agent to evaluate your implementation against your ad account setup.

*By submitting attribution data to Stripe, you agree that you’ve provided all required notices and obtained all necessary rights, consents, and other permissions to collect, use, and disclose that data to Stripe and, if you enable conversion signals, to the applicable ad platform. You’re responsible for complying with applicable laws, including laws governing cookies and similar tracking technologies.*
