
# Sell on your website

Use this guide when people buy on your site: a SaaS plan, a membership, an online course, a shop
order. There is no app store in the path; your payment provider charges the customer and your
server knows about every charge.

**Example:** Tallybird sells **Tallybird Web**, a browser version of the habit tracker, with a
7-day trial and a $39.99 annual plan through Stripe on `tallybird.example`. It runs Meta and TikTok
ads to `tallybird.example/start`.

## What goes where

| Step | Sent by | How |
|---|---|---|
| Ad click and landing | Browser | The web SDK records the visit with the URL's click id (`fbclid`, `ttclid`, `gclid`) and UTM tags |
| More pages | Browser | Visits on every page (single-page apps: `kerdly.visit()` per route) |
| Sign-up or sign-in | Browser | `kerdly.identify(userId)` |
| Trial, first charge, renewal, one-time purchase, refund | **Your server**, or Paddle / Stripe directly | `POST /v1/s2s/events` from your payment provider's webhook, or the provider connected in Settings → Connections |
| Cancel | Nothing needed | A subscription that stops renewing has ended |
| Conversions to Meta and TikTok | Kerdly's server | Postbacks, from your server events |

Money events come only from your server, or straight from Paddle or Stripe (step 4). The browser
can't be trusted with them: an ad blocker, a
closed tab or a refresh would lose or double them, and refunds and renewals never happen in the
browser at all.

## 1. Set up the project

1. In the dashboard, create the product with **Website** ticked and the site's address. This makes
   the **Tallybird Web** app.
2. Open the Web app's **Settings → SDK**. Its **web key** (`wk_live_…`) is already made and shown
   in the snippet to paste. It is public.
3. Under **Server keys and key rotation** on the same page, create a **server key** (`sk_live_…`). It is shown once; put
   it in your server's secrets as `KERDLY_SERVER_KEY`.

## 2. Add the web SDK to every page

```html
<script src="https://cdn.kerdly.com/v1/kerdly.js" data-key="wk_live_…" async></script>
```

Or with npm, see [Web SDK](https://kerdly.com/docs/sdks/web.md#install) (Next.js and single-page apps included). Load it on
every page, including the checkout and the pages after it.

## 3. Identify the visitor

Call `identify` as soon as you know who the visitor is: after sign-up, after sign-in, and on every
page load of a signed-in session (it is sent once per visitor and user).

```ts
kerdly.identify(user.id); // your own user id, the same one your server sends
```

This one call is what lets a charge your server reports weeks later find the ad that brought the
visitor.

**Guest checkout** (no account): pass `kerdly.visitorId()` to your server with the checkout, store
it on the order or Stripe customer, and put it on each server event as `visitor_id`.

```ts
// when creating the Stripe Checkout Session from the browser
await fetch("/api/checkout", {
  method: "POST",
  body: JSON.stringify({ plan: "annual", kerdlyVisitorId: window.kerdly?.visitorId() }),
});
```

```js
// server: keep it on the customer, so every later charge carries it
const session = await stripe.checkout.sessions.create({
  mode: "subscription",
  line_items: [{ price: "price_tallybird_annual", quantity: 1 }],
  subscription_data: { trial_period_days: 7, metadata: { kerdly_visitor_id: body.kerdlyVisitorId, user_id: user?.id ?? "" } },
  // keep the same two ids on the customer too (customer_creation / customers.update), for refunds
  success_url: "https://tallybird.example/welcome",
});
```

## 4. Paddle or Stripe: connect it, no server code

If you sell through Paddle or Stripe, Kerdly can read every trial, charge, renewal and refund from
the provider itself. Then skip step 5's server code for that provider: Kerdly counts each
provider's money from one place only.

1. In the Web app's **Settings → Connections**, open **Payments through Paddle** or **Payments
   through Stripe** and paste a read-only API key:
   - Paddle: **Developer tools → Authentication → API keys**, with read access to Transactions,
     Adjustments and Subscriptions.
   - Stripe: **Developers → API keys → Create restricted key**, with Read on Charges, Invoices,
     Subscriptions and Balance.

   Kerdly loads your whole history right away, then checks for new charges every hour. Set the
   dialog's **User id field** (step 3) in the same save, since the history is read with it.
2. For charges within seconds, add the webhook the dialog shows (`https://app.kerdly.com/api/paddle?app=…`
   or `/api/stripe?app=…`) and paste its secret (Paddle's destination secret key, Stripe's signing
   secret `whsec_…`). Events: Paddle `transaction.completed`, `subscription.created`,
   `adjustment.created`, `adjustment.updated`; Stripe `charge.succeeded`, `charge.refunded`,
   `charge.refund.updated`, `customer.subscription.created`.
3. Name the buyer on every checkout. This step is what ties revenue to ads: a charge from Paddle
   or Stripe comes from their servers, with no cookie, so Kerdly finds the buyer's visit through
   the user id on the charge, the same id your site passes to `kerdly.identify()` (step 3 above).
   Put it in Paddle's custom data or Stripe's metadata under the dialog's **User id field**,
   `kerdly_user_id` unless you change it. If your checkout already stores your own id there (say
   `orgId` or `account_id`), type that field's name instead and call `identify` with the same id.
   Changing the field later applies to charges read from then on. Guest checkouts also pass the
   visitor id:

```js
// Paddle.js
Paddle.Checkout.open({
  items: [{ priceId: "pri_…", quantity: 1 }],
  customData: { kerdly_visitor_id: window.kerdly?.visitorId(), kerdly_user_id: user?.id },
});
```

```js
// Stripe Checkout, on your server
await stripe.checkout.sessions.create({
  mode: "subscription",
  line_items: [{ price: "price_…", quantity: 1 }],
  subscription_data: { metadata: { kerdly_visitor_id: body.kerdlyVisitorId, kerdly_user_id: user?.id ?? "" } },
  // one-time purchases: payment_intent_data: { metadata: { … } }
  success_url: "https://tallybird.example/welcome",
});
```

Renewals follow their subscription and refunds their charge, so only the checkout needs the ids.
The web app's **Onboarding** page shows **Name the buyer at checkout** as done once your newest
charge carries the id, and says how many of the last 30 days' charges do.
Reports count what you keep after tax and the provider's fee, in the charge's own currency.
The web app's **P&L** reads these charges. When the site sells subscriptions (set **Sells** to
subscriptions, or both, in the web app's settings), its **Retention** page and the Dashboard's
Expected return and Collected + remaining read them too, each plan renewing on its billing period.
A plan change's proration or an extra charge counts as revenue, not as a renewal.
Conversions to the ad networks (step 7) still come from server events for now.

## 5. Send money events from your server

Send one event per business event, from your payment provider's webhook. These are the events
Kerdly reads revenue from:

| What happened | `name` | Stripe webhook that tells you |
|---|---|---|
| A trial started | `start_trial` | `customer.subscription.created` with `status: trialing` |
| The first paid charge of a subscription, no trial | `subscribe` | The subscription's first `invoice.paid` with an amount above 0 |
| The first paid charge after a trial | `trial_conversion` | The same, for a subscription that had a trial (Stripe marks that invoice `subscription_cycle`) |
| Each later charge | `renewal` | Every later `invoice.paid` |
| A one-time purchase | `purchase` | `checkout.session.completed` with `mode: payment`, or `charge.succeeded` |
| A refund | `refund` | `charge.refunded` |

```js
// server/kerdly.js
export async function sendKerdlyEvents(events, key = process.env.KERDLY_SERVER_KEY) {
  const res = await fetch("https://app.kerdly.com/api/v1/s2s/events", {
    method: "POST",
    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    body: JSON.stringify({ events }),
  });
  if (!res.ok) throw new Error(`Kerdly ${res.status}`); // let your webhook retry; repeats are safe
  return res.json(); // { accepted, duplicates, rejected }
}
```

```js
// server: Stripe webhook, invoice.paid (adapt field names to your Stripe API version)
if (invoice.amount_paid === 0) return;             // the $0 invoice that opens a trial
const sub = await stripe.subscriptions.retrieve(invoice.subscription);
const paidBefore = sub.metadata.kerdly_paid === "1";
const name = paidBefore ? "renewal" : sub.trial_start ? "trial_conversion" : "subscribe";
if (!paidBefore) await stripe.subscriptions.update(sub.id, { metadata: { kerdly_paid: "1" } });

await sendKerdlyEvents([{
  event_id: `stripe:${invoice.id}`,                 // one id per business event
  name,
  ts: invoice.status_transitions.paid_at * 1000,
  user_id: sub.metadata.user_id || null,            // the id you passed to identify
  visitor_id: sub.metadata.kerdly_visitor_id || null,
  props: {
    transaction_id: invoice.charge,                 // the charge id: refunds point at it
    subscription_id: sub.id,                        // ties renewals to the first charge
    product_id: "tallybird_web_annual",
    product_kind: "subscription",
    value: invoice.amount_paid / 100,               // what the customer paid
    net_value: netAfterFeesAndTax,                  // what you keep, same currency
    currency: invoice.currency.toUpperCase(),
    store: "stripe",
  },
}]);
```

```js
// server: Stripe webhook, charge.refunded
const customer = await stripe.customers.retrieve(charge.customer);
await sendKerdlyEvents([{
  event_id: `stripe:refund:${charge.refunds.data[0].id}`,
  name: "refund",
  ts: charge.refunds.data[0].created * 1000,
  user_id: customer.metadata.user_id || null,      // the ids you kept on the Stripe customer
  visitor_id: customer.metadata.kerdly_visitor_id || null,
  props: {
    transaction_id: charge.id,                      // the charge being refunded
    value: charge.refunds.data[0].amount / 100,
    currency: charge.currency.toUpperCase(),
    store: "stripe",
  },
}]);
```

Rules for every event:

- `event_id` is yours and unique per business event. Retrying the same request is safe: a repeat is
  answered as a duplicate.
- Every event needs `user_id` or `visitor_id` (or both).
- `transaction_id` with `store` names a charge. Use the provider's charge id, so a refund finds it.
- `subscription_id` on every charge of a subscription, so renewals are credited to the first
  charge's ad.
- `value` is what the customer paid; `net_value` what you keep after fees and taxes. Reports count
  `net_value`; ad networks get `value`.
- Test-mode charges: add `"environment": "sandbox"`.

Paddle, Lemon Squeezy or your own billing work the same way: map their webhooks onto the six names
above and set `store` (`paddle`, or `web` for your own).

## 6. Optional: other events

- **Sign-up** as a funnel step: a custom server event, for example `{ "name": "registration", ... }`
  with `user_id`. It doesn't change revenue.
- **Cancellations** aren't needed: reports work from charges, and a subscription without its next
  `renewal` has ended. If you want them recorded, send a custom event such as `subscription_cancel`
  with the `subscription_id`.

## 7. Send conversions to Meta and TikTok

In the Web app's **Settings → Postbacks**, add Meta (your website's dataset / pixel) or TikTok (your
web pixel). By default trials, first subscriptions and purchases from your server are sent, with the
click id, `fbc` / `fbp` / `ttp` cookies and IP of the visit that brought the buyer.

If the page also fires the Meta or TikTok pixel for the same purchase, give the pixel event the same
id as your server event, so the network counts it once:

```js
// on the success page, with the id your server used as event_id
fbq("track", "Purchase", { value: 39.99, currency: "USD" }, { eventID: "stripe:in_1Q9…" });
```

## 8. Check it

1. Open `https://tallybird.example/start?utm_source=meta&utm_medium=paid&campaign_id=test` in a
   private window, sign up, and buy in Stripe test mode.
2. Your webhook log shows `accepted` for each event.
3. The Web app's **Onboarding** page shows the tag and the server-purchases steps as done; the
   Dashboard shows the visit and the sandbox charge.

## Agent checklist

- [ ] `kerdly.js` (or `createKerdly`) on every page; `visit()` per route in an SPA.
- [ ] `identify(userId)` after sign-up and sign-in; guest checkout passes `visitorId()` to the server.
- [ ] Paddle / Stripe connected: every checkout puts the same user id in custom data / metadata
      under the app's **User id field** (default `kerdly_user_id`).
- [ ] Server key only on the server, from an environment variable.
- [ ] Webhook handler sends `start_trial`, `subscribe` / `trial_conversion`, `renewal`, `purchase`,
      `refund`, each with `event_id`, `ts`, `user_id` or `visitor_id`, `transaction_id`, `store`,
      `value`, `currency`, and `subscription_id` for subscriptions.
- [ ] No money events from the browser.
- [ ] Pixel purchase events use the server event's id.

See also [Client events, server events and deduplication](https://kerdly.com/docs/guides/events-and-dedupe.md).

---

Source: https://kerdly.com/docs/guides/web-checkout. Index of all docs: https://kerdly.com/llms.txt
