# Revenue

> Record purchases with a revenue property, connect Stripe, or post payments from your own backend.

There are three ways to get revenue into AnyAnalytics: add a `revenue` property to your own events, connect your Stripe account so payments and refunds are recorded for you, or post them from your own backend, whatever takes the payments. Either way, revenue shows on the Overview next to the visitors and players who brought it.

## The revenue property

Any event with a numeric `revenue` property counts as revenue. Add an optional `currency` with the three-letter ISO code.

`shop.js`:

```ts
// Any event with a numeric "revenue" property counts as revenue
analytics.track("purchase_completed", {
  item: "gem_pack_s",
  revenue: 4.99,
  currency: "USD",
});
```

- Send the amount in major units: `4.99` dollars, not `499` cents.
- Numbers and numeric strings (`"4.99"`) both work. Anything else counts as zero.
- The event name is up to you. `purchase_completed`, `order_paid` or `subscription_renewed` all count.
- Send revenue from wherever the payment is confirmed. For real money, that's usually your server, so a player can't fake a purchase.

## Where revenue shows up

When the period you're looking at has revenue, the Overview shows revenue, conversion rate (the share of people who paid) and revenue per person to its headline numbers. Revenue is credited to the source, entry page, country and device of the visit that brought the person, so the breakdowns show which channels make money, not just traffic. The **Journey** tab under Goals lists the paying customers and how they first found you.

### Goals

Each goal on the Overview shows the revenue of the events that match it. Make your purchase event a goal to see its completions, conversion rate and revenue side by side.

## Several currencies

Amounts in different currencies are never added together. Each report picks one currency, the one used by most revenue events in the period, and totals that. Revenue in any other currency is listed separately next to the total, marked as not included.

Events without a `currency` are counted in the report's currency. If you only ever sell in one currency you can leave it out; if you sell in several, always send it.

## Refunds

Refunds recorded by the Stripe integration appear as dashed bars on top of the revenue chart. They're shown alongside revenue rather than subtracted from it, so you can see both.

## Connect Stripe

If you take payments with Stripe, connect it to record real payments and refunds without sending any events yourself. It's included on every plan. Only owners and admins of a project can connect it.

1. **Add a webhook endpoint in Stripe**

   In your project, open **Settings → Revenue** and copy the webhook URL. In Stripe, open **Developers → Webhooks → Add destination**, paste the URL and select these events:

   - `checkout.session.completed`
   - `checkout.session.async_payment_succeeded`
   - `invoice.paid`
   - `charge.refunded`
2. **Paste the signing secret**

   Stripe shows a signing secret for the new endpoint, starting with `whsec_`. Paste it in **Settings → Revenue** and click **Connect**. It's stored encrypted and never shown again; every delivery is checked against it.

3. **Pass the visitor into Checkout**

   So that each payment is credited to the right visitor, send their AnyAnalytics ids to your checkout endpoint and put them in the Checkout Session's metadata.

`checkout-button.js`:

```ts
// In the browser, when the visitor clicks "Buy" (script tag: window.anyanalytics,
// npm SDK: the analytics instance you initialized).
const res = await fetch("/api/checkout", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    priceId: "price_123",
    visitorId: anyanalytics.distinctId,
    sessionId: anyanalytics.sessionId,
  }),
});
location.href = (await res.json()).url;
```

`api/checkout.js`:

```ts
// On your server (Node, stripe package). The ids also go on the payment /
// subscription so refunds and renewals are attributed to the same visitor.
const metadata = {
  anyanalytics_visitor_id: body.visitorId ?? "",
  anyanalytics_session_id: body.sessionId ?? "",
};
const session = await stripe.checkout.sessions.create({
  mode: "payment", // or "subscription"
  line_items: [{ price: body.priceId, quantity: 1 }],
  success_url: "https://example.com/thanks",
  client_reference_id: body.visitorId,
  metadata,
  payment_intent_data: { metadata }, // mode "payment"
  // subscription_data: { metadata }, // mode "subscription"
});
return { url: session.url };
```

The metadata keys are `anyanalytics_visitor_id` and `anyanalytics_session_id`. If there's no visitor id in the metadata, the Checkout Session's `client_reference_id` is used instead.

> **Test it**
>
> Use **Send test event** on the endpoint in Stripe. The Revenue settings show when the last delivery arrived, and the last error if one was rejected.

### What's recorded

- Paid one-time Checkout payments, as a `$payment` event with `revenue` and `currency`. Payments by bank debit count once they succeed.
- Subscription invoices, the first one and every renewal. Invoices sent through Stripe Invoicing that aren't part of a subscription are not counted.
- Refunds, as a `$refund` event for the amount refunded. Partial refunds are recorded one by one.
- Stripe sometimes delivers the same event twice. Each one is recorded once.

### How payments are matched to visitors

- A payment is credited to the visitor named in its metadata. It takes that visitor's device, location and session, so it lands on the source that brought them.
- Renewals and refunds are matched through the ids on the payment or subscription metadata (the server snippet above sets them), or through the Stripe customer remembered from their first Checkout.
- Payments that can't be matched still count, as a person of their own.

Disconnecting Stripe stops new payments and refunds from being recorded. Revenue already recorded stays.

## Payments from your own backend

Taking payments with Paddle, PayPal, Lemon Squeezy, crypto, bank transfers or your own billing? Your server posts each payment and refund to a webhook, and they're recorded exactly like Stripe's: `$payment` and `$refund` events, credited to the visitor and the source that brought them.

1. **Create the webhook**

   In the site's **Settings → Revenue**, under *Your own backend*, click **Create webhook**. Copy the secret into your server's environment: it's shown once (only a fingerprint is kept), and **Rotate secret** makes a new one if it's lost or leaked.

2. **Keep the visitor on the order**

   At checkout, send `anyanalytics.distinctId` and `anyanalytics.sessionId` from the browser to your server and store them on the order, as in the Stripe snippet above. A signed-in user's id (the one you pass to `identify()`) works too.

3. **Post the payment once it's confirmed**

   `server.js`:

   ```ts
   // On your server, once the payment is confirmed (e.g. in your provider's
   // webhook handler). Store visitorId / sessionId on the order at checkout:
   // in the browser they're anyanalytics.distinctId and anyanalytics.sessionId.
   await fetch("https://api.anyanalytics.org/v1/webhooks/payments/<site id>", {
     method: "POST",
     headers: {
       Authorization: `Bearer ${process.env.ANYANALYTICS_PAYMENTS_SECRET}`,
       "Content-Type": "application/json",
     },
     body: JSON.stringify({
       id: order.id, // the same id again is ignored, so retries are safe
       amount: order.total, // 49.90, not cents
       currency: order.currency,
       distinct_id: order.visitorId,
       session_id: order.sessionId,
       customer_id: order.customerId,
     }),
   });
   
   // A refund: its own id, and the amount refunded this time.
   // { type: "refund", id: refund.id, amount: 10, currency: "EUR", customer_id: "cus_7" }
   ```

### Fields

- `id` (required): Your order, transaction or refund id. Sent twice, counted once.
- `amount` (required): In major units: 49.90, not 4990.
- `currency` (required): 3-letter code: USD, EUR, MAD…
- `type`: "payment" (default) or "refund".
- `distinct_id`: Who paid: anyanalytics.distinctId from the browser, or your identify() id.
- `session_id`: anyanalytics.sessionId at checkout: credits the visit's source.
- `customer_id`: Your customer id. Linked once with a distinct_id, renewals and refunds follow.
- `timestamp`: ISO 8601 or epoch ms; now by default. Up to 60 days back.
- `provider`: Where it came from: "paddle", "paypal"… ("custom" by default).
- `properties`: Anything else to filter by later: plan, product, coupon…

### Answers

- `200`: recorded, or already recorded (the same `id` is only counted once, so retrying is always safe).
- `400`: a field is wrong; `errors` lists what to fix.
- `401`: missing or wrong secret. `402`: the plan doesn't include revenue.
- `503`: busy, try again in a moment.

Like Stripe customers, a `customer_id` sent once together with a `distinct_id` is remembered, so later renewals and refunds for that customer are credited to the same visitor without one. The settings page shows the last payment received and the last request refused, with the reason.

## See also

- [Events and people](https://anyanalytics.org/docs/events.md) for how visitors become people when they sign in.
- [Game events](https://anyanalytics.org/docs/game-events.md#more) for in-app purchase and economy events.

---

Web version: https://anyanalytics.org/docs/revenue. All docs: https://anyanalytics.org/docs.md
