> ## Documentation Index
> Fetch the complete documentation index at: https://stage-docs.oktivo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Capturing Leads via API

> Push leads into Oktivo CRM from forms, chatbots, ad platforms, and your own backend

The Lead API lets any external system drop a lead straight into your Oktivo CRM
dashboard. This guide walks through a working integration end to end.

## 1. Create an API token

The Lead API is authenticated with an account API token. Create one from your
account settings:

**1. Open account settings**

In the dashboard, click your account and open **Settings**
(`app.oktivo.com/account`).

**2. Go to API Tokens**

In the settings sidebar, select the **API Tokens** tab. You'll see the
**API Tokens** panel listing any existing tokens with their expiry and
last-used date.

![Oktivo account API Tokens settings with the Create Token button](https://mintcdn.com/oktivo-stage-docs/c3bIROP6UAjDKw3o/images/create_token.png?fit=max\&auto=format\&n=c3bIROP6UAjDKw3o\&q=85\&s=d7c9b9487b2e7ad498efceaddea85781)

Settings → API Tokens: create, rotate, and delete tokens

**3. Create the token**

Click **Create Token** (top right), give it a recognisable name
(e.g. `website-lead-capture`), and choose an expiry (1–365 days).

**4. Copy and store it**

Copy the `okt_...` value immediately — it is shown **only once**. Store it
as a secret in whatever system will call the API; never commit it to source
control.

> [!NOTE]
>
> Each account can have a **maximum of 5 active tokens**. If you've hit the
> limit, delete an unused token (trash icon) before creating a new one. Use the
> rotate icon to replace a token's value in a single step without changing where
> it's referenced.

See [Authentication](https://stage-docs.oktivo.com/authentication.md) for token rotation and expiry details.

## 2. Send your first lead

The only hard requirement is a **phone or an email**. Everything else is
optional.

```bash theme={null}
curl -X POST https://client-backend.oktivo.com/api/v1/crm/leads \
  -H "Authorization: Bearer okt_your_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Priya Sharma",
    "phone": "9876543210",
    "email": "priya@example.com",
    "metadata": { "source": "website" }
  }'
```

A `201` means a new lead was created; a `200` with `"merged": true` means the
person already existed and your data was merged in. See the full field reference
on [Capture a Lead](https://stage-docs.oktivo.com/api-reference/leads/create-lead.md).

## 3. Attach your own fields

Any key that is not a reserved lead field is stored as a custom field and shows
up as a column on the CRM dashboard. Send them at the top level, or group them
under `customFields`:

```json theme={null}
{
  "name": "Priya Sharma",
  "phone": "9876543210",
  "customFields": {
    "course": "Data Science",
    "budget": "₹2,50,000",
    "preferred_batch": "Weekend"
  }
}
```

You can send up to 50 custom fields per lead.

## 4. Let Oktivo de-duplicate for you

You do not need to check whether a lead already exists. Oktivo keeps one lead
per phone (or email) per account:

* A new acquisition **source** on an existing person merges and records a source
  history entry.
* Self-service sources (`website`, `chatbot`, `whatsapp`, `google_form`,
  `ai_powered_lead`, `payment_page_drop`, `landing`) always merge on repeat and
  keep the latest values — ideal for returning visitors and re-fired events.
* Curated sources (`api`, `webhook`, `manual`, `csv_import`) return a `409` on a
  repeat of the same source, protecting your data from accidental overwrites.

Set `metadata.source` to one of the known values so filtering and the merge
behaviour stay correct. Any unknown source is stored as `api`.

## 5. Forward from an unauthenticated webhook (optional)

If a platform can only send plain, unauthenticated webhooks (no custom headers),
put a tiny proxy in front of the Lead API that attaches your Bearer token. This
repo ships a ready-made Cloudflare Worker at
`cloudflare-lead-worker/` that maps an arbitrary webhook payload into the Lead
API body and forwards it. Set your `OKTIVO_API_TOKEN` as a Worker secret and
point the platform's webhook at the Worker URL.

## Common pitfalls

* **Missing identity** — sending neither `phone` nor `email` returns a `400`.
* **Unexpected `source`** — a typo in `metadata.source` silently becomes `api`;
  use the exact values from the [source table](https://stage-docs.oktivo.com/api-reference/leads/create-lead.md#lead-sources).
* **Hitting the field cap** — more than 50 custom fields returns a `400` rather
  than silently dropping columns.
* **Rate limits** — on a `429`, honour the `Retry-After` header and back off.

## 6. How Channel and Source are determined

Oktivo shows two normalized attribution values on every lead — **Channel** and
**Source** — in the lead's **Details & attribution** panel, the **Marketing**
tab, and the Leads table. You never send these directly; Oktivo derives them
from the signals you do send (`metadata.source`, the `utm*` fields, the
referrer, and the ad platform). Sending the right signals is what makes them
accurate.

### Channel

**Channel** is a fixed, reportable set — a lead always falls into exactly one:

`Website` · `WhatsApp` · `Offline` · `Facebook` · `Email` · `Outbound call` ·
`Inbound` · `Event` · `Affiliate` · `Online Other` · `Offline Other`

It is derived from your `metadata.source`:

| You send `metadata.source` | Channel |
| - | - |
| `website`, `chatbot`, `landing`, `payment_page_drop` | Website |
| `facebook_ad` (any platform, incl. Instagram) | Facebook |
| `whatsapp` | WhatsApp |
| `manual`, `csv_import` | Offline |
| `campaign` (outbound voice) | Outbound call |
| `google_ad`, `google_form`, `google_sheet`, `api`, `webhook`, `apollo`, `ai_powered_lead`, `kalki_intake` | Online Other |
| a landing "live-call" request | Inbound |

A lead that carries no recognizable source but has any digital signal (a UTM, a
referrer, an email, a click id) becomes **Online Other**; with nothing digital
at all it becomes **Offline Other**. For Meta leads, the real ad surface
(Instagram vs Facebook) is preserved as a platform sub-detail and shown next to
the channel, e.g. **Facebook (Instagram)** — so no insight is lost.

### Source

**Source** is derived in this strict order:

1. **Meta leads** (`facebook_ad`) → the real platform: **Instagram** or
   **Facebook** (never the raw `facebook_ad`).
2. **A UTM is present** → the humanized `utm_source` (e.g. `google`, `newsletter`).
3. **No UTM but an external referrer is present** → **Organic**.
4. **Neither** → **Direct**.

So to get accurate Source for a website form, send `utm_source` when the landing
URL has one, and send the page's `document.referrer` when it does not.

> [!NOTE]
>
> Channel and Source are computed once on the server when the lead is created and
> returned on the lead's `classification` object. Leads created before this
> feature are classified on read, so older leads display correctly too.

## 7. Website tracking snippet (referrer + anonymous activity)

Oktivo ships a tiny, dependency-free tracking snippet. Embed it on the
customer's site and it captures marketing attribution (UTMs, **referrer**,
Google/Meta click ids) and anonymous page activity, keyed by a durable
first-party **`visitorId`**. When that same visitor later submits your
lead-capture form carrying the `visitorId`, Oktivo stitches the prior anonymous
activity (including the referrer that drives the **Organic** Source rule) onto
the created lead.

Place this before `</body>`:

```html theme={null}
<script
  src="https://client-backend.oktivo.com/api/v1/crm/track.js"
  data-token="okt_your_token_here"
  data-auto-pageview="true"></script>
```

It exposes a small API on `window.oktivo`:

* `oktivo.getVisitorId()` — the durable visitor id (put it on your forms).
* `oktivo.track(name, props?)` — send a custom event, e.g. `oktivo.track('add_to_cart', { sku })`.
* `oktivo.pageview()` — send a page view for the current URL.

The snippet needs no server work from you; the token in the embed tag authorizes
the data and the tenant is resolved from it, never from the page.

## 8. Complete website form example

A self-contained lead-capture form for a customer's own site. It embeds the
tracking snippet, reads UTM params and the referrer from the landing URL, picks
up the `visitorId`, and POSTs to the Lead API. Channel and Source are derived
server-side from these signals.

```html theme={null}
<!-- 1. Tracking snippet (captures referrer + anonymous activity, mints visitorId) -->
<script
  src="https://client-backend.oktivo.com/api/v1/crm/track.js"
  data-token="okt_your_token_here"
  data-auto-pageview="true"></script>

<!-- 2. The lead form -->
<form id="oktivo-lead-form">
  <input name="name"  placeholder="Full name" required />
  <input name="phone" placeholder="Phone (e.g. +919876543210)" required />
  <input name="email" type="email" placeholder="Email" />
  <button type="submit">Request a callback</button>
</form>

<script>
  // Read UTM params from the landing URL (persisted so they survive navigation).
  function captureUtms() {
    var KEY = "oktivo_form_utms";
    var p = new URLSearchParams(window.location.search);
    var fresh = {
      utmSource:   p.get("utm_source")   || undefined,
      utmMedium:   p.get("utm_medium")   || undefined,
      utmCampaign: p.get("utm_campaign") || undefined,
    };
    var hasFresh = fresh.utmSource || fresh.utmMedium || fresh.utmCampaign;
    try {
      if (hasFresh) localStorage.setItem(KEY, JSON.stringify(fresh));
      return hasFresh ? fresh : JSON.parse(localStorage.getItem(KEY) || "{}");
    } catch (e) {
      return fresh;
    }
  }

  document.getElementById("oktivo-lead-form").addEventListener("submit", function (e) {
    e.preventDefault();
    var form = e.target;
    var utms = captureUtms();

    var metadata = {
      source: "website",                         // drives Channel = Website
      referrer: document.referrer || undefined,  // drives Source = Organic when no UTM
      platform: "web",
    };
    if (utms.utmSource)   metadata.utmSource   = utms.utmSource;   // drives Source = <utm_source>
    if (utms.utmMedium)   metadata.utmMedium   = utms.utmMedium;
    if (utms.utmCampaign) metadata.utmCampaign = utms.utmCampaign;

    // Stitch prior anonymous browsing (incl. referrer) onto this lead.
    if (window.oktivo && window.oktivo.getVisitorId) {
      metadata.visitorId = window.oktivo.getVisitorId();
    }

    var body = {
      name:  form.name.value.trim(),
      phone: form.phone.value.trim(),
      email: form.email.value.trim() || undefined,
      metadata: metadata,
    };

    fetch("https://client-backend.oktivo.com/api/v1/crm/leads", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        // NOTE: a browser-exposed token is capture-only. Scope it to lead
        // capture and rotate it regularly — anyone viewing source can read it.
        "Authorization": "Bearer okt_your_token_here",
      },
      body: JSON.stringify(body),
    })
      .then(function (r) { return r.json(); })
      .then(function (res) {
        if (res.success) {
          form.reset();
          // show your own "thanks" state here
        }
      })
      .catch(function () { /* show a retry message */ });
  });
</script>
```

> [!WARNING]
>
> A token placed in client-side HTML is visible to anyone who views the page
> source. For public websites, prefer routing the form POST through your own
> backend (or the bundled [Cloudflare Worker](#5-forward-from-an-unauthenticated-webhook-optional))
> so the `okt_` token stays server-side. If you must call the API directly from
> the browser, use a token scoped only to lead capture and rotate it on a
> schedule.

### What this produces

For a visitor who arrived at `https://site.com/?utm_source=google&utm_medium=cpc`
and submitted the form, the lead is created with:

* **Channel:** `Website`
* **Source:** `Google`

For a visitor who arrived with no UTM but was referred from another site, the
lead shows **Channel:** `Website` and **Source:** `Organic`. With neither, the
Source is **Direct**.

## Valid `metadata.source` values

Send one of these exact strings so Channel/Source and the duplicate-merge rules
stay reliable. An unrecognized value is stored as `api`.

| Value | Typical use |
| - | - |
| `website` | A form on the customer's own site |
| `chatbot` | A website/app chatbot lead\_creator |
| `landing` | A hosted landing page / "try live call" |
| `whatsapp` | WhatsApp inbound |
| `facebook_ad` | Meta (Facebook/Instagram) lead ads |
| `google_ad` | Google Ads |
| `google_form` | Google Forms capture |
| `google_sheet` | Google Sheets import |
| `campaign` | Outbound voice campaign upload |
| `apollo` | Apollo.io enrichment / import |
| `ai_powered_lead` | Customer's own AI lead-scoring engine |
| `payment_page_drop` | Abandoned checkout / payment page |
| `kalki_intake` | A bespoke per-customer intake form |
| `manual` | Added by hand in the dashboard |
| `csv_import` | Bulk CSV upload |
| `api` | Generic programmatic push (default fallback) |
| `webhook` | Generic webhook ingestion |

## 9. Worked examples — what each capture path produces

Every capture path writes a few raw signals (`metadata.source`, `metadata.platform`,
`utm*`, referrer, `sourceHistory`). Oktivo's classifier folds those into the
**Channel**, **Source**, and **Platform** you see in the Leads table and the
lead's Details & attribution panel. The table below shows, for each real path,
the signals that arrive and the values the user ends up seeing.

> [!NOTE]
>
> **Channel** and **Source** are always derived — no path sets them directly.
> **Platform** is only non-null for Meta ad surfaces (Instagram/Facebook).

| # | Capture path | `metadata.source` | Key signals that arrive | → Channel | → Source | → Platform |
| - | - | - | - | - | - | - |
| 1 | **Meta Lead Ad — Instagram** | `facebook_ad` | `platform: instagram`, `utmSource: instagram`, `metaPlatform: ig`, `sourceHistory[].channel: instagram` | `Facebook` | `Instagram` | `Instagram` |
| 2 | **Meta Lead Ad — Facebook** | `facebook_ad` | `platform: facebook`, `utmSource: facebook`, `metaPlatform: fb`, `sourceHistory[].channel: facebook` | `Facebook` | `Facebook` | `Facebook` |
| 3 | **Meta organic page form** | `facebook_ad` | `metaIsOrganic: true`, `utmMedium: organic_social`, `platform: facebook` | `Facebook` | `Facebook` | `Facebook` |
| 4 | **Google Lead Form / Ads** | `google_ad` | `platform: google`, `utmSource: google`, `utmMedium: cpc`, `sourceHistory[].channel: google` | `Online Other` | `Google` | `null` |
| 5 | **Google Forms capture** | `google_form` | form answers in `industryData` | `Online Other` | `Direct`¹ | `null` |
| 6 | **Google Sheet import** | `google_sheet` | row data in `industryData` | `Online Other` | `Direct`¹ | `null` |
| 7 | **Website form + UTM** (Lead API, `source: website`) | `website` | `utmSource: google`, `utmMedium: cpc`, `utmCampaign: spring` | `Website` | `Google` | `null` |
| 8 | **Website form + referrer only** | `website` | `referrer: https://news.ycombinator.com/...`, no UTM | `Website` | `Organic` | `null` |
| 9 | **Website form, direct** | `website` | no UTM, no referrer | `Website` | `Direct` | `null` |
| 10 | **Oktivo tracking script → stitched lead** | `website` | `visitorId` links prior session's `referrer`/UTMs onto the lead | `Website` | `Google` / `Organic` / `Direct`² | `null` |
| 11 | **Website chatbot (lead\_creator)** | `chatbot` | chat-captured fields in `industryData` | `Website` | `Direct`¹ | `null` |
| 12 | **Landing page "try live call"** | `landing` (+ `landingSource: live-call`) | `platform: web` | `Inbound` | `Direct`¹ | `null` |
| 13 | **Landing page form (no live-call)** | `landing` | `platform: web` | `Website` | `Direct`¹ | `null` |
| 14 | **WhatsApp inbound** | `whatsapp` | `platform: whatsapp` | `WhatsApp` | `Direct`¹ | `null` |
| 15 | **Outbound voice campaign upload** | `campaign` | contact row | `Outbound call` | `Direct`¹ | `null` |
| 16 | **Apollo.io import / enrichment** | `apollo` | company/title/LinkedIn in `industryData` | `Online Other` | `Direct`¹ | `null` |
| 17 | **AI-scored lead (webhook)** | `ai_powered_lead` | course/lead-type bag | `Online Other` | `Direct`¹ | `null` |
| 18 | **Abandoned checkout (webhook)** | `payment_page_drop` | cart/payment bag | `Website` | `Direct`¹ | `null` |
| 19 | **Kalki / bespoke intake form** (JWT path) | `kalki_intake` | rich custom-field bag | `Online Other` | `Direct`¹ | `null` |
| 20 | **Generic API push** (no/unknown `source`) | `api` (fallback) | whatever you send | `Online Other`³ | `Direct`⁴ | `null` |
| 21 | **Generic webhook** | `webhook` | mapped payload | `Online Other` | `Direct`¹ | `null` |
| 22 | **Manual entry (dashboard)** | `manual` | typed by a rep | `Offline` | `Direct` | `null` |
| 23 | **CSV bulk import** | `csv_import` | spreadsheet rows | `Offline` | `Direct`¹ | `null` |
| 24 | **Cloudflare Worker proxy** | (whatever it forwards) | maps a plain webhook → Lead API body; `source` falls back to `api` unless the payload sets `metadata.source` | follows the forwarded `source` | follows the signals | `null`/Meta |

**Footnotes**

1. `Direct` is the terminal default: the path carries no UTM and no referrer, so
   Source rules 2 and 3 don't fire. If the same lead *also* carries a UTM or
   referrer (e.g. a website form that passed them through), Source becomes that
   UTM's `utm_source` or `Organic` instead.
2. The stitched Source depends on what the tracking script captured in the
   visitor's session: a UTM → that `utm_source`; a referrer only → `Organic`;
   neither → `Direct`.
3. A generic `api` lead with any digital signal (UTM, referrer, email, click id)
   lands in **Online Other**; with nothing digital at all it would be
   **Offline Other**. In practice an API lead almost always has an email, so
   **Online Other** is the usual result.
4. If you send `utmSource`/`referrer` alongside a generic `api` push, Source
   follows those (UTM → `utm_source`, referrer → `Organic`) instead of `Direct`.

### Reading it in the Leads table

* The **Source column** shows the derived Channel plus a platform badge where one
  exists, e.g. a Meta/Instagram lead reads **Facebook · Instagram**, a Google
  lead reads **Online Other · Google**, a plain website lead reads
  **Website · Direct**.
* The lead's **Details & attribution** panel shows a **Channel** row
  (e.g. `Facebook (Instagram)`) directly above a **Source** row
  (e.g. `Instagram`). When a lead arrived from more than one source, the Source
  row carries a `+N` badge that opens the full arrival journey.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.