Docsllms.txtSign inGo to your sites

Updated

View as Markdown

Revenue attribution

twelvebit shows which sources bring revenue, not only visitors. It needs two things:

  1. The payments. Connect your provider in the site's revenue settings in the dashboard (Stripe, Polar, Lemon Squeezy, Paddle or Dodo Payments). twelvebit then receives each payment, renewal and refund. Stores on Shopify or WooCommerce connect the store instead. For other providers, send payments with POST /api/v1/payments.
  2. The visitor. When you create a checkout on your server, read the _tb_vid and _tb_sid cookies and put them in the checkout metadata as twelvebit_visitor_id and twelvebit_session_id. The provider sends the metadata back with the payment.

Ask your coding agent

Paste this into Claude Code, Codex or Cursor in your project folder. It holds no key: the agent gets one with the CLI, and you approve the sign-in in the browser. To do it yourself, follow the steps after it.

Prompt for your coding agent · holds no key
Wire twelvebit revenue attribution into this project for <production domain>. The twelvebit script sets two first-party cookies: _tb_vid (visitor id) and _tb_sid (session id). twelvebit gives a payment to the visit that led to it when these ids travel with the payment. 1. Detect the payment provider: Stripe, Polar, Lemon Squeezy, Paddle, Dodo Payments, or something else. 2. Find every place where the code creates a checkout. On the server, read _tb_vid and _tb_sid from the request cookies. In the browser (Paddle.js), read them from document.cookie. 3. Put them in the checkout metadata as twelvebit_visitor_id and twelvebit_session_id: - Stripe: Checkout Session metadata, and subscription_data.metadata for subscriptions. - Polar: checkout metadata. - Lemon Squeezy: checkout_data.custom. - Paddle: customData in Paddle.Checkout.open (custom_data in the API). - Dodo Payments: checkout session metadata, plus a plan key with the product name. - Other providers: send each payment to POST https://twelvebit.app/api/v1/payments with visitor_id and session_id (see the reference). 4. Never block or fail a checkout when the cookies are missing: send empty strings. Do not change prices, products or URLs. 5. Tell me to connect the provider in twelvebit (Settings → Revenue) if it is not connected yet. That step needs the provider's dashboard. 6. Check it: tell me how to make one test-mode payment. After it, the get_revenue MCP tool (or the Revenue page) must list it with the channel of my test visit. Reference: https://twelvebit.app/docs/revenue.md. At the end, show me the diff. Fill in <production domain> and <site id> from this project: the site id is data-website-id in the twelvebit script tag, or TWELVEBIT_SITE_ID in .env. Ask me if you cannot find them.

How the credit is given

The model is last touch: the visit before the payment. For each payment, twelvebit picks the credited visit in this order:

  1. The session in the checkout metadata (twelvebit_session_id).
  2. The visitor's latest visit that started before the payment (twelvebit_visitor_id).
  3. A visitor that identified with the same email as the customer.
  4. For renewals and refunds: the customer's earlier attributed payment.

The visit's channel, referrer, campaign, landing page and country get the revenue. Refunds count against the same visit.

Revenue in reports

  • Breakdowns are last touch. Channel, referrer, campaign, entry page, exit page, hostname, country and the other cards count each payment once, for the visit it is credited to, so the rows add up to the attributed revenue. On the Page card a payment counts for the last page viewed before it in that visit. Cards with a revenue column say "Revenue: last touch".
  • Goal revenue overlaps. The goal rows show the revenue in the range of the people who completed each goal. One person can complete several goals, so these rows do not add up.
  • GET /api/v1/breakdown and the MCP tool get_breakdown return revenue_model: one sentence that says how revenue is counted for that dimension.
  • Funnels show per step the payments that people made after they reached the step (last touch), and revenue_stopped_here: the part of it from people whose last step this is.
  • Revenue page. The attribution switch picks Last touch (the default, the same as the overview) or First touch (the person's first visit). It is in the URL as ?attr=first; no parameter, or ?attr=last, is last touch. It applies to every revenue card on the page: the KPIs, the chart, the flow chart, landing pages, revenue per visitor and recent payments. The chart's revenue line is Net by default, or only New payments, Renewals or Refunds: ?rev=new, ?rev=renewal or ?rev=refund. The page takes the same filters as the overview.

Read the cookies

The cookies are first-party, so your server receives them with each request from your site:

lib/twelvebit.ts
// lib/twelvebit.ts
import { cookies } from "next/headers";

export async function twelvebitIds() {
  const c = await cookies(); // cookies() is async in Next.js 15 and later
  const visitor = c.get("_tb_vid")?.value;
  const session = c.get("_tb_sid")?.value;
  return {
    ...(visitor && { twelvebit_visitor_id: visitor }),
    ...(session && { twelvebit_session_id: session }),
  };
}

Stripe

Put the ids on the Checkout Session. For subscriptions, also put them on the subscription, so renewals carry them. For one-time payments, put them on the PaymentIntent.

app/api/checkout/route.ts
// app/api/checkout/route.ts
import Stripe from "stripe";
import { twelvebitIds } from "@/lib/twelvebit";

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

export async function POST(req: Request) {
  const { priceId } = await req.json();
  const ids = await twelvebitIds();
  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: "https://example.com/welcome",
    cancel_url: "https://example.com/pricing",
    metadata: { ...ids, plan: "pro" },
    subscription_data: { metadata: { ...ids, plan: "pro" } },
    // mode: "payment" → use payment_intent_data: { metadata: ids } instead of subscription_data
  });
  return Response.json({ url: session.url });
}

Express:

server.js
// server.js (with cookie-parser)
app.post("/checkout", async (req, res) => {
  const ids = {
    twelvebit_visitor_id: req.cookies._tb_vid,
    twelvebit_session_id: req.cookies._tb_sid,
  };
  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [{ price: req.body.priceId, quantity: 1 }],
    success_url: "https://example.com/thanks",
    metadata: ids,
    payment_intent_data: { metadata: ids },
  });
  res.json({ url: session.url });
});

Payment Links cannot carry server metadata. Use a Checkout Session, or identify the visitor with their email before they pay.

Polar

TypeScript
import { Polar } from "@polar-sh/sdk";
import { twelvebitIds } from "@/lib/twelvebit";

const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN! });

export async function POST() {
  const checkout = await polar.checkouts.create({
    products: [process.env.POLAR_PRODUCT_ID!],
    successUrl: "https://example.com/welcome",
    metadata: await twelvebitIds(),
  });
  return Response.json({ url: checkout.url });
}

Lemon Squeezy

Use checkout_data.custom:

TypeScript
import { createCheckout } from "@lemonsqueezy/lemonsqueezy.js";
import { twelvebitIds } from "@/lib/twelvebit";

export async function POST() {
  const { data } = await createCheckout(process.env.LS_STORE_ID!, process.env.LS_VARIANT_ID!, {
    checkoutData: { custom: await twelvebitIds() }, // sent as checkout_data.custom
  });
  return Response.json({ url: data?.data.attributes.url });
}

With plain HTTP, send "checkout_data": { "custom": { "twelvebit_visitor_id": "…", "twelvebit_session_id": "…" } } in the checkout attributes.

Paddle

Paddle Checkout often opens in the browser. Read the cookies there and pass them as customData:

JavaScript
const cookie = (k) => document.cookie.match(new RegExp("(?:^|; )" + k + "=([^;]*)"))?.[1];

Paddle.Checkout.open({
  items: [{ priceId: "pri_123", quantity: 1 }],
  customData: {
    twelvebit_visitor_id: cookie("_tb_vid"),
    twelvebit_session_id: cookie("_tb_sid"),
  },
});

For transactions that your server creates, set custom_data with the same keys.

Dodo Payments

TypeScript
import DodoPayments from "dodopayments";
import { twelvebitIds } from "@/lib/twelvebit";

const dodo = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY! });

export async function POST() {
  const session = await dodo.checkoutSessions.create({
    product_cart: [{ product_id: process.env.DODO_PRODUCT_ID!, quantity: 1 }],
    return_url: "https://example.com/welcome",
    metadata: await twelvebitIds(),
  });
  return Response.json({ url: session.checkout_url });
}

Shopify

Install the twelvebit app from the Shopify App Store (Install → Shopify). It connects the store in one step: no custom app, no ids, no secrets, no scopes and no theme code.

The app:

  • loads the script on every storefront page with an app embed (Theme editor → App embeds → twelvebit analytics). The embed reads the site id and the cookieless setting from a setting that twelvebit writes into the store, so a change in twelvebit applies at once.
  • adds a web pixel. On checkout_started and checkout_completed it sends the checkout token to twelvebit. This never starts a visit and is not billed.
  • receives the webhooks orders/paid and refunds/create at one endpoint, signed by Shopify. twelvebit records each delivery once, also when Shopify sends it again.

Each order goes to the visit that led to it. twelvebit tries these in order:

  1. the visitor and session ids on the cart (_tb_vid and _tb_sid in note_attributes). The script writes them when the site uses cookies and the visitor allows analytics.
  2. the checkout token: the order's checkout_token matches the token that the web pixel sent from the visitor's browser. This works with cookies and in cookieless mode.
  3. the browser that paid: the daily hash of the order's browser address and user agent (the same hash as cookieless mode). It finds the visit of a visitor without cookies, and also a visit with cookies that has no cart ids, for example after a Buy it now or express checkout. The hash of the day before counts too, for a visit just before midnight UTC. twelvebit does not store the address, and it deletes the hash of a visit with cookies after 3 days. Stores connected with a custom app use this step too.

Consent. On Shopify the script follows the store's consent banner (Shopify's Customer Privacy API). It sets no cookie and puts no ids on the cart until the visitor allows analytics. Before that, after a no, and where the store has no answer for it, the script counts like cookieless mode: it stores nothing on the device. When the visitor withdraws consent, the script removes its cookies. The web pixel declares the analytics purpose to Shopify, not marketing, and it never sells data: Shopify runs it only where the visitor allows analytics or where no consent is needed. Step 3 needs neither cookies nor the pixel.

What the app stores. For each paid order: the order id and order name, the time, the total and its currency, the name of the first product, the checkout token, the Shopify customer id (a number, so that repeat orders count as one customer), whether it is a test order, and the visit that it joins. For each refund: the refund id, the amount and the order id. Optional paid sales classification also stores a normalized customer type, its classification basis and the order source; it reads customer tags only after permission is granted. Raw customer tags are not copied into sales-report fields. No email, name, address or phone number. See Paid sales. The app has protected customer data Level 1 only.

Each paid order becomes a payment (the order total in the store currency, the first product as the plan) and a payment goal. Refunds subtract. Test orders ("test": true) count like other orders.

Uninstall stops the orders at once and removes the link. Shopify asks twelvebit 48 hours later to delete the store's data (shop/redact): twelvebit then deletes the store's orders and refunds. Your twelvebit account, the site and its visits stay until you delete them.

Billing. An account that you make in the app pays through Shopify (Shopify App Pricing: Starter or Growth at 10k, 100k, 500k or 1M events, monthly or yearly, with a 14-day free trial). An account that you made on twelvebit.app keeps its twelvebit plan, and Shopify never bills it for twelvebit. One account can link several stores; it pays once.

Stores that connected before the app

Stores with a custom app keep working. To move, install the app, then uninstall the custom app in Shopify. See Shopify: legacy setup.

WooCommerce

Install the twelvebit plugin for WordPress:

  1. In twelvebit, open the site's revenue settings, choose WooCommerce, and click Create secret. Keep the page open: the secret is shown once.
  2. Download twelvebit-woocommerce.zip. In WordPress, open Plugins → Add New Plugin → Upload Plugin, install it and activate it. It needs PHP 7.4 or later.
  3. Open Settings → twelvebit and paste the Site ID (tb_YOUR_SITE_ID), the Domain (example.com), the App URL (https://twelvebit.app) and the Webhook secret. Save.

The plugin:

  • adds the script to every page. Another twelvebit tag for the same site does no harm: the script runs once on each page.
  • sends the goals add_to_cart (AJAX buttons, the product page form and the block cart) and initiate_checkout (the checkout page).
  • saves the _tb_vid and _tb_sid cookies on each new order (classic and block checkout).
  • sends the order to https://twelvebit.app/api/webhooks/woocommerce/tb_YOUR_SITE_ID when its status becomes Processing or Completed, and each refund. The body is JSON, signed with HMAC-SHA256 (hex) of the body in the X-Twelvebit-Signature header. The request is non-blocking, so checkout never waits.

twelvebit counts each order once, also when it is sent for Processing and again for Completed.

Other providers: the payments API

For PayPal, Gumroad, your own billing or a Zapier flow, send each payment from your server. The call is safe to repeat: transaction_id makes it idempotent.

Shell
curl -sS -X POST https://twelvebit.app/api/v1/payments -H "Authorization: Bearer $TWELVEBIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"amount": 49, "currency": "USD", "transaction_id": "order_1042", "visitor_id": "VISITOR_ID", "email": "ada@example.com", "plan": "pro"}'
FieldTypeNotes
amountnumberRequired. Major units: 49.99 means 49.99. 0 is a free trial and is not counted.
currencystringRequired. ISO 4217, for example USD, EUR.
transaction_idstringRequired. Your unique id for the payment.
visitor_idstringThe _tb_vid cookie.
session_idstringThe _tb_sid cookie. Gives the exact visit.
emailstringMatches a visitor that identified with this email.
customer_idstringLinks renewals to the first payment.
renewalbooleantrue for a subscription renewal.
refundedbooleantrue for a refund.
planstringThe plan or product name, for the revenue by plan view.
timestampstring or numberISO 8601 or Unix time. Default: now.

With an account token, add "site_id" to the body.

Check it

Make a test payment in the provider's test mode. Then open the Revenue view, or ask the MCP server: "What revenue came from each channel in the last 7 days?" The get_revenue tool lists recent payments with their credited channel.