Actually Tracking

Revenue tracking

Learn how to easily track your revenue with Actually Tracking and how to get it shown directly in your dashboard.

Revenue tracking is a great way to get a better understanding of what your best revenue source is. On this page we'll break down how to get started.

Connect your billing provider (no code)

If you take payments with Stripe, Lemon Squeezy, Polar, Paddle or Dodo Payments, you can skip the code on this page. Go to Project settings → Revenue.

Polar: click Connect Polar, sign in to Polar and approve read access. If you belong to several Polar organizations, pick the one to connect. Nothing to copy. To stop it, click Disconnect: the access is revoked on Polar's side too.

The others connect with an API key:

ProviderKeyNeeds
StripeA restricted keyRead: Charges, Checkout Sessions, Customers, Invoices, Products, Refunds, Subscriptions. Write: Webhook Endpoints
Lemon SqueezyAn API key from Settings → APIA test-mode key connects your test store
Polar (instead of signing in)An organization access tokenScopes orders:read, subscriptions:read, refunds:read, customers:read, webhooks:read, webhooks:write. A sandbox token connects your sandbox
PaddleAn API key from Developer tools → AuthenticationRead transactions, subscriptions, adjustments, customers and products; write notification settings. A sandbox key connects your sandbox
Dodo PaymentsAn API key from Developer → API KeysTick "Enable write access" (it is only used to add our webhook). A test-mode key connects your test mode

Actually Tracking then:

  • adds one webhook to your account, so new payments, refunds, failed payments and subscription changes arrive within seconds
  • imports the last 12 months of payments and subscriptions
  • fills the Revenue page, MRR and churn, and the revenue on your overview
  • records each subscription's moments as events you can use in funnels, KPIs and notifications:
EventWhen
trial_startedA subscription starts with a trial
trial_convertedThe trial turns into a paid subscription
subscription_startedA subscription starts without a trial
subscription_upgraded / subscription_downgradedThe plan or quantity changes MRR (previousMrr, mrrChange)
cancel_scheduled / cancel_revertedA cancel at period end is set (cancelAt) or taken back
subscription_endedThe subscription is over
subscription_renewedAny other change, such as a new billing period (Stripe only)
payment_succeeded / payment_refunded / payment_failedMoney in, money back, a failed charge

Lemon Squeezy, Polar, Paddle and Dodo Payments are merchants of record, so their revenue excludes the tax they collect. Stripe revenue is what the customer paid.

Currency

Each project reports revenue in one currency, set in Settings → Revenue. Until you choose, it's the currency your provider pays you in, set by the first payment. A payment in another currency is converted as exactly as the provider allows:

ProviderConverted with
StripeThe payment's balance transaction: what Stripe credited your balance, at Stripe's own rate
PaddleThe transaction's payout totals
Dodo PaymentsThe payment's settlement amount
Lemon SqueezyThe order's USD totals
PolarPolar pays out in USD but doesn't show its rate, so the day's European Central Bank rate

That's exact when the provider pays you in the project's currency. Otherwise, and for MRR (no provider prices a subscription in your payout currency), the payment is converted at the European Central Bank's reference rate for the day it happened. Every event keeps what the customer paid (originalAmount, originalCurrency) and how it was converted (conversion: provider, rate or unconverted). Changing the currency converts payments already imported again, from those originals.

Revenue you send yourself (op('revenue', …) or a server SDK) isn't converted: send it in the project's currency.

Tie payments to visitors

To credit each payment to the visit, source and campaign that led to it, give the checkout the visitor's ids, op.getDeviceId() and op.getSessionId():

ProviderHow
Stripemetadata: { at_visitor_id, at_session_id } on the Checkout Session. For Payment Links, a success URL on your site with ?session_id={CHECKOUT_SESSION_ID}
Lemon SqueezyNothing for checkout links on your site: the script adds the ids when one is clicked. For API checkouts, checkout_data.custom: { at_visitor_id, at_session_id }
Polarmetadata: { at_visitor_id, at_session_id } on the checkout, or a success URL on your site with ?checkout_id={CHECKOUT_ID}
PaddlecustomData: { at_visitor_id, at_session_id } in Paddle.Checkout.open. Payment links that open on your own site (?_ptxn=…) need nothing
Dodo Paymentsmetadata: { at_visitor_id, at_session_id } when you create the checkout session (Dodo copies it onto the payment), or a return_url (redirect_url on a payment link) on your site: Dodo adds ?payment_id= or ?subscription_id= and the tracking script reports it. The email Dodo adds to that URL is never stored

For example, with Stripe:

// Browser: send these to your server when the buyer clicks "Buy"
const visitorId = op.getDeviceId();
const sessionId = op.getSessionId();

// Server
await stripe.checkout.sessions.create({
  // ...line items, mode, success_url
  metadata: { at_visitor_id: visitorId, at_session_id: sessionId },
});

A payment from a checkout the browser reports waits up to two minutes for that report before it is recorded.

Know the buyer's email on your site? Call op('payment', { email }) when you have it, and a payment by that email is credited to that visit, with any provider. Only a hash of the email is sent.

The deviceId key from the examples below works too. A subscription's renewals follow its first checkout on their own. A payment without any of this is matched to a signed-in user (see identifying users) by the customer's email, or else the customer's earlier payments.

Connect a provider or send revenue from your own webhook, not both. With both, every payment counts twice.

If your provider isn't listed, or you want full control, track revenue yourself as described below.

Before we start, we need to know some fundamentals about how Actually Tracking and your payment provider work and how we can link a payment to a visitor.

Payment providers

Usually, you create your checkout from your backend, which then returns a payment link that your visitor will be redirected to. When creating the checkout link, you usually add additional fields such as metadata, customer information, or order details. We'll add the device ID information in this metadata field to be able to link your payment to a visitor.

Actually Tracking

Actually Tracking is a cookieless analytics tool that identifies visitors using a device_id. To link a payment to a visitor, you need to capture their device_id before they complete checkout. This device_id will be stored in your payment provider's metadata, and when the payment webhook arrives, you'll use it to associate the revenue with the correct visitor.

Some typical flows

Revenue tracking from your backend (webhook)

This is the most common flow and most secure one. Your backend receives webhooks from your payment provider, and here is the best opportunity to do revenue tracking.

1
Visitor: Visits your website
2
Visitor: Makes a purchase
3
Your website: Does a POST request to get the checkout URL

When you create the checkout, you should first call op.getDeviceId(), which will return your visitor's current deviceId. Pass this to your checkout endpoint.

fetch('https://domain.com/api/checkout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    deviceId: op.getDeviceId(), // ✅ since deviceId is here we can link the payment now
    // ... other checkout data
  }),
})
  .then(response => response.json())
  .then(data => {
    // Handle checkout response, e.g., redirect to payment link
    window.location.href = data.paymentUrl;
  })
4
Your backend: Will generate and return the checkout URL
import Stripe from 'stripe';

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

export async function POST(req: Request) {
  const { deviceId, amount, currency } = await req.json();
  
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: currency,
          product_data: { name: 'Product Name' },
          unit_amount: amount * 100, // Convert to cents
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    metadata: {
      deviceId: deviceId, // ✅ since deviceId is here we can link the payment now
    },
    success_url: 'https://domain.com/success',
    cancel_url: 'https://domain.com/cancel',
  });
  
  return Response.json({
    paymentUrl: session.url,
  });
} 
5
Visitor: Gets redirected to payment link
6
Visitor: Pays on your payment provider
7
Your backend: Receives a webhook for a successful payment
export async function POST(req: Request) {
  const event = await req.json();
  
  // Stripe sends events with type and data.object structure
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    const deviceId = session.metadata.deviceId;
    const amount = session.amount_total;
    
    op.revenue(amount, { deviceId }); // ✅ since deviceId is here we can link the payment now
  }
  
  return Response.json({ received: true });
}
8
Visitor: Redirected to your website with payment confirmation

Revenue tracking from your backend (webhook) - Identified users

If your visitors are identified (meaning you have called identify with a profileId), this process gets a bit easier. You don't need to pass the deviceId when creating your checkout, and you only need to provide the profileId (in backend) to the revenue call.

1
Visitor: Visits your website
2
Your website: Identifies the visitor

When a visitor logs in or is identified, call op.identify() with their unique profileId.

op.identify({
  profileId: 'user-123', // Unique identifier for this user
  email: 'user@example.com',
  firstName: 'John',
  lastName: 'Doe',
});
3
Visitor: Makes a purchase
4
Your website: Does a POST request to get the checkout URL

Since the visitor is already identified, you don't need to fetch or pass the deviceId. Just send the checkout data.

fetch('https://domain.com/api/checkout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    // ✅ No deviceId needed - user is already identified
    // ... other checkout data
  }),
})
  .then(response => response.json())
  .then(data => {
    // Handle checkout response, e.g., redirect to payment link
    window.location.href = data.paymentUrl;
  })
5
Your backend: Will generate and return the checkout URL

Since the user is authenticated, you can get their profileId from the session and store it in metadata for easy retrieval in the webhook.

import Stripe from 'stripe';

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

export async function POST(req: Request) {
  const { amount, currency } = await req.json();
  
  // Get profileId from authenticated session
  const profileId = req.session.userId; // or however you get the user ID
  
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: currency,
          product_data: { name: 'Product Name' },
          unit_amount: amount * 100, // Convert to cents
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    metadata: {
      profileId: profileId, // ✅ Store profileId instead of deviceId
    },
    success_url: 'https://domain.com/success',
    cancel_url: 'https://domain.com/cancel',
  });
  
  return Response.json({
    paymentUrl: session.url,
  });
} 
6
Visitor: Gets redirected to payment link
7
Visitor: Pays on your payment provider
8
Your backend: Receives a webhook for a successful payment

In the webhook handler, retrieve the profileId from the session metadata.

export async function POST(req: Request) {
  const event = await req.json();
  
  // Stripe sends events with type and data.object structure
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    const profileId = session.metadata.profileId;
    const amount = session.amount_total;
    
    op.revenue(amount, { profileId }); // ✅ Use profileId instead of deviceId
  }
  
  return Response.json({ received: true });
}
9
Visitor: Redirected to your website with payment confirmation

Revenue tracking from your frontend

This flow tracks revenue directly from your frontend. Since the success page doesn't have access to the payment amount (payment happens on Stripe's side), we track revenue when checkout is initiated and then confirm it on the success page.

1
Visitor: Visits your website
2
Visitor: Clicks to purchase
3
Your website: Track revenue when checkout is initiated

When the visitor clicks the checkout button, track the revenue with the amount.

async function handleCheckout() {
  const amount = 2000; // Amount in cents

  // Create a pending revenue (stored in sessionStorage)
  op.pendingRevenue(amount, {
    productId: '123',
    // ... other properties
  });
   
  // Redirect to Stripe checkout
  window.location.href = 'https://checkout.stripe.com/...';
}
4
Visitor: Gets redirected to payment link
5
Visitor: Pays on your payment provider
6
Visitor: Redirected back to your success page
7
Your website: Confirm/flush the revenue on success page

On your success page, flush all pending revenue events. This will send all pending revenues tracked during checkout and clear them from sessionStorage.

// Flush all pending revenues
await op.flushRevenue();

// Or if you want to clear without sending (e.g., payment was cancelled)
op.clearRevenue();

Pros:

  • Quick way to get going
  • No backend required
  • Can track revenue immediately when checkout starts

Cons:

  • Less accurate (visitor might not complete payment)
  • Less "secure" meaning anyone could post revenue data

Revenue tracking without linking it to an identity or device

If you simply want to track revenue totals without linking payments to specific visitors or devices, you can call op.revenue() directly from your backend without providing a deviceId or profileId. This is the simplest approach and works well when you only need aggregate revenue data.

1
Visitor: Makes a purchase
2
Visitor: Pays on your payment provider
3
Your backend: Receives a webhook for a successful payment

Simply call op.revenue() with the amount. No deviceId or profileId is needed.

export async function POST(req: Request) {
  const event = await req.json();
  
  // Stripe sends events with type and data.object structure
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;
    const amount = session.amount_total;
    
    op.revenue(amount); // ✅ Simple revenue tracking without linking to a visitor
  }
  
  return Response.json({ received: true });
}

Pros:

  • Simplest implementation
  • No need to capture or pass device IDs
  • Works well for aggregate revenue tracking

Cons:

  • You can't dive deeper into where this revenue came from. For instance, you won't be able to see which source generates the best revenue, which campaigns are most profitable, or which visitors are your highest-value customers.
  • Revenue events won't be linked to specific user journeys or sessions

Available methods

Revenue

The revenue method will create a revenue event. It's important to know that this method will not work if your Actually Tracking instance didn't receive a client secret (for security reasons). You can enable frontend revenue tracking within your project settings.

op.revenue(amount: number, properties: Record<string, unknown>): Promise<void>

Add a pending revenue

This method will create a pending revenue item and store it in sessionStorage. It will not be sent to Actually Tracking until you call flushRevenue(). Pending revenues are automatically restored from sessionStorage when the SDK initializes.

op.pendingRevenue(amount: number, properties?: Record<string, unknown>): void

Send all pending revenues

This method will send all pending revenues to Actually Tracking and then clear them from sessionStorage. Returns a Promise that resolves when all revenues have been sent.

await op.flushRevenue(): Promise<void>

Clear any pending revenue

This method will clear all pending revenues from memory and sessionStorage without sending them to Actually Tracking. Useful if a payment was cancelled or you want to discard pending revenues.

op.clearRevenue(): void

Fetch your current users device id

op.getDeviceId(): string

On this page