Updated
View as MarkdownRevenue attribution
twelvebit shows which sources bring revenue, not only visitors. It needs two things:
- 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. - The visitor. When you create a checkout on your server, read the
_tb_vidand_tb_sidcookies and put them in the checkout metadata astwelvebit_visitor_idandtwelvebit_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.
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:
- The session in the checkout metadata (
twelvebit_session_id). - The visitor's latest visit that started before the payment (
twelvebit_visitor_id). - A visitor that identified with the same email as the customer.
- 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/breakdownand the MCP toolget_breakdownreturnrevenue_model: one sentence that says howrevenueis 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=renewalor?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
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
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 (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
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:
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:
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
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_startedandcheckout_completedit sends the checkout token to twelvebit. This never starts a visit and is not billed. - receives the webhooks
orders/paidandrefunds/createat 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:
- the visitor and session ids on the cart (
_tb_vidand_tb_sidinnote_attributes). The script writes them when the site uses cookies and the visitor allows analytics. - the checkout token: the order's
checkout_tokenmatches the token that the web pixel sent from the visitor's browser. This works with cookies and in cookieless mode. - 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:
- In twelvebit, open the site's revenue settings, choose WooCommerce, and click Create secret. Keep the page open: the secret is shown once.
- 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.
- 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) andinitiate_checkout(the checkout page). - saves the
_tb_vidand_tb_sidcookies on each new order (classic and block checkout). - sends the order to
https://twelvebit.app/api/webhooks/woocommerce/tb_YOUR_SITE_IDwhen its status becomes Processing or Completed, and each refund. The body is JSON, signed with HMAC-SHA256 (hex) of the body in theX-Twelvebit-Signatureheader. 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.
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"}'| Field | Type | Notes |
|---|---|---|
amount | number | Required. Major units: 49.99 means 49.99. 0 is a free trial and is not counted. |
currency | string | Required. ISO 4217, for example USD, EUR. |
transaction_id | string | Required. Your unique id for the payment. |
visitor_id | string | The _tb_vid cookie. |
session_id | string | The _tb_sid cookie. Gives the exact visit. |
email | string | Matches a visitor that identified with this email. |
customer_id | string | Links renewals to the first payment. |
renewal | boolean | true for a subscription renewal. |
refunded | boolean | true for a refund. |
plan | string | The plan or product name, for the revenue by plan view. |
timestamp | string or number | ISO 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.