# Agency API

Send leads in, sell your plans from your own funnel, and get an event when a client pays.

This guide is for agencies on ServiceLocal and the developers and AI agents who build their funnels. It covers three things: sending leads in, selling your plans from your own funnel, and getting a signed event when a client pays or cancels.

> No developer? Once your agency has its own domain (Settings › Domains), every plan has a buy link under Pricing › Plans. Paste it on any page and the lead pays you directly.

## Quick start

1. **Get a key.** In your agency console, open Settings › Funnels & API › API keys and create one. Keep it on your server.
2. **List your plans.**

```bash
curl "https://app.servicelocal.ai/api/public/v1/offers?channel=api" \
  -H "X-ServiceLocal-Key: $SERVICELOCAL_API_KEY"
```

3. **Start a checkout** for one plan and send the buyer to the `url` it returns.

```bash
curl -X POST https://app.servicelocal.ai/api/public/v1/checkouts \
  -H "X-ServiceLocal-Key: $SERVICELOCAL_API_KEY" \
  -H "Idempotency-Key: lead-8812-growth" \
  -H "Content-Type: application/json" \
  -d '{
    "offerKeys": ["<offerKey from step 2>"],
    "offerVersion": 2,
    "buyer": { "email": "owner@sunriseplumbing.com", "name": "Sam Lee", "phone": "+15551234567" },
    "successUrl": "https://youragency.com/thanks",
    "cancelUrl": "https://youragency.com/plans"
  }'
```

4. **Act on the webhook.** Add an endpoint under Settings › Funnels & API › Webhooks. When `client.activated` arrives and its signature checks out, the client has paid and is live.

## Keys and responses

| What | Value |
|---|---|
| Base URL | `https://app.servicelocal.ai` |
| API key | Settings › Funnels & API › API keys (owner only). Header `X-ServiceLocal-Key: sl_live_…` |
| Intake key | Settings › Funnels & API › Leads. Header `X-Intake-Key: …` |
| Success body | `{ "status": "success", "data": … }` |
| Error body | `{ "status": "error", "error": { "code": "<code>", "message": "…" } }`. Validation errors add `error.details` |
| Key and rate-limit refusals | Flat: `{ "status": "error", "code": "UNAUTHORIZED", "message": "…" }` (401) or `"code": "RATE_LIMITED"` (429) |

- Keys belong on your server only: never in browser code, page HTML or a public repository.
- The API key's secret is shown once, when you create it. Revoking it stops every funnel using it at once.
- An API key reads only the checkouts it created itself.

## Send leads

Send each lead from your form or funnel tool. ServiceLocal creates the lead under your agency and starts building their demo site under your brand.

```
POST https://app.servicelocal.ai/api/public/agency-intake
X-Intake-Key: <your intake key>
Content-Type: application/json
```

```json
{
  "businessName": "Sunrise Plumbing",
  "email": "owner@sunriseplumbing.com",
  "phone": "+1 555 123 4567",
  "trade": "plumbing",
  "websiteUrl": "sunriseplumbing.com"
}
```

| Field | Required | What it is |
|---|---|---|
| `businessName` | Yes | The lead's company name |
| `email` | Yes | The lead's email: the demo goes here |
| `phone` | Yes | The lead's phone |
| `trade` | No | The service line, like `plumbing` |
| `websiteUrl` | No | Their current site: the demo builder reads it |

- The answer is `200 { "status": "accepted" }`. Extra fields are ignored, so a funnel tool can send its whole form.
- The same email sent again within 30 minutes is the same lead, not a new one, so retries are safe.
- Intake errors have their own body, `{ "error": { "code", "message" } }`: `401 missing_intake_key` or `invalid_intake_key`, `400 VALIDATION_FAILED` (with `issues`), `409 agency_growth_frozen`, `429 RATE_LIMITED` (10 a minute per IP).
- Making a new intake key stops the old one at once.

**GoHighLevel:** in a workflow, add a **Custom Webhook** action, method POST, the URL above, a header `X-Intake-Key` with your key, and map your form fields to the body.

## Sell your plans

Your plans are the ones you create under Pricing › Plans. Clients pay you directly, on your own connected Stripe account. Two things must be true before anything sells: your agency takes payments (Billing › Getting paid), or checkouts answer `409 agency_cannot_sell`; and your own ServiceLocal plan is paid and active (Billing), or they answer `409 agency_subscription_required`. A free trial makes demos but cannot sell.

### Buy links (no code)

Buy links live on your own domain, so they appear once one is connected under Settings › Domains. Then every active plan has one: open the plan's **Buy link** under Pricing › Plans and copy the link or the button HTML. The page asks for the buyer's email, name and phone, opens a checkout, and the buyer becomes your client. Links from the console arrive on your webhooks with empty `metadata`.

### List your plans

```
GET /api/public/v1/offers?channel=api
X-ServiceLocal-Key: <your API key>
```

`channel=api` is required. The answer is `data.offers`, your active plans:

```json
{
  "offerKey": "7c1e2a90-4b1d-4f0e-9a51-0c6a1d2f3b44",
  "version": 2,
  "kind": "client_plan",
  "merchant": "agency",
  "name": "Growth",
  "price": { "unit": "money", "currency": "usd", "cents": 29900 },
  "interval": "month",
  "setupFee": null,
  "firstPayment": { "unit": "money", "currency": "usd", "cents": 29900 },
  "includedMonthlyCredits": 5000,
  "perClientFee": null,
  "sheet": {
    "kind": "client_plan",
    "modules": [
      { "module": "website", "included": true },
      { "module": "booking", "included": true },
      { "module": "receptionist", "included": false },
      { "module": "web_assistant", "included": true }
    ]
  }
}
```

- `offerKey` is the plan's id and never changes. A price change raises `version`.
- `firstPayment` is what the buyer pays at checkout: the first month plus any `setupFee`.
- `sheet.modules` says what the plan includes: use it to render the plan's feature list.
- **Never hardcode prices.** Read the offers and render the page from them, and read them again before each render.

### Start a checkout

```
POST /api/public/v1/checkouts
X-ServiceLocal-Key: <your API key>
Idempotency-Key: <8 to 200 characters, unique per sale attempt>
Content-Type: application/json
```

```json
{
  "offerKeys": ["7c1e2a90-4b1d-4f0e-9a51-0c6a1d2f3b44"],
  "offerVersion": 2,
  "buyer": { "email": "owner@sunriseplumbing.com", "name": "Sam Lee", "phone": "+15551234567" },
  "successUrl": "https://youragency.com/thanks",
  "cancelUrl": "https://youragency.com/plans",
  "metadata": { "campaign": "spring", "contact_id": "abc123" }
}
```

The answer is `201` with `data.checkoutId` and `data.url` (the Stripe Checkout page). Redirect the buyer to `url`.

- `offerKeys` holds exactly one plan. `offerVersion` is the version you showed: if the price changed since, the call answers `409 offer_version_changed`, so read the offers again and show the new price.
- `buyer.name` and `buyer.phone` are required: every client needs them.
- `successUrl` and `cancelUrl` are required public URLs: no localhost, no private addresses. Use `https`.
- `metadata` is optional: at most 20 pairs, keys of letters, digits, `_`, `.` and `-` (1 to 40 characters), values up to 500 characters. It comes back on your webhooks, so carry your own contact id in it.

**Retries are safe with the same Idempotency-Key:**

- The same key with the same plan, version, buyer email, return URLs and metadata returns the same checkout. The buyer's name and phone are not compared.
- The same key with a different request answers `409 idempotency_key_reused`.
- `409 open_payment_link_required`: that checkout's Stripe session has closed, paid or not. Read the checkout: `complete` means the buyer paid (don't sell again), `expired` means you may start a new checkout with a new Idempotency-Key.
- So make one Idempotency-Key per buy attempt (a fresh id when the buyer clicks Buy), resend that same key only to retry the same request, and never derive it from the buyer and plan alone: after an expired checkout that key can never sell again.
- `409 checkout_not_created`: the first request never reached Stripe. Send it again with a new Idempotency-Key.

**Read a checkout back:**

```
GET /api/public/v1/checkouts/<checkoutId>
```

`data` holds `checkoutId`, `status` (`open`, `complete` or `expired`) and `clientId`, which is set once the client has paid and is live.

## Webhooks

Add up to 5 endpoints under Settings › Funnels & API › Webhooks. Each one gets every event and its own signing secret, shown once. The endpoint must be a public URL; use `https`.

| Event | When |
|---|---|
| `client.activated` | A client paid their first plan and is live |
| `subscription.canceled` | A client's plan ended |

```json
{
  "event": "client.activated",
  "eventId": "6f0b6c1e-2d0a-4c55-9a7e-3d1f4b8e2a10",
  "occurredAt": "2026-11-05T10:00:00.000Z",
  "agencyId": "a1b2c3d4-…",
  "client": { "tenantId": "e5f6a7b8-…", "name": "Sunrise Plumbing", "ownerEmail": "owner@sunriseplumbing.com" },
  "plan": { "offerKey": "7c1e2a90-…", "version": 2, "name": "Growth", "amountCents": 29900, "currency": "usd", "interval": "month" },
  "stripe": { "subscriptionId": "sub_1Qx…" },
  "metadata": { "campaign": "spring", "contact_id": "abc123" }
}
```

- `plan` is `null` when the subscription's price matches none of your plans. `client.ownerEmail` may be `null`.
- `metadata` is what your checkout sent; it is empty for a console buy link.

**How to receive them:**

- **Verify the signature first.** The header is `X-ServiceLocal-Signature: t=<unix seconds>,v1=<hex>`, where `v1` is the HMAC-SHA256 of `<t>.<raw body>` keyed with the endpoint's secret. Sign the raw body bytes, not re-serialised JSON.
- **Drop duplicates by `eventId`.** The same event can arrive more than once.
- **Answer 2xx quickly.** Anything else is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, then given up. Redirects are not followed and the timeout is 10 seconds. The console shows each delivery and its result.

```js
import crypto from 'node:crypto';

export function verifyServiceLocal(rawBody, header, secret, toleranceSec = 300) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const t = Number(parts.t);
  if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  const given = Buffer.from(parts.v1 ?? '', 'hex');
  const want = Buffer.from(expected, 'hex');
  return given.length === want.length && crypto.timingSafeEqual(given, want);
}
```

## Example: a Node funnel server

```js
import express from 'express';
import { verifyServiceLocal } from './verify.js';

const API = 'https://app.servicelocal.ai/api/public/v1';
const headers = { 'X-ServiceLocal-Key': process.env.SERVICELOCAL_API_KEY, 'Content-Type': 'application/json' };
const app = express();

app.get('/plans', async (_req, res) => {
  const answer = await fetch(`${API}/offers?channel=api`, { headers }).then((r) => r.json());
  res.json(answer.data.offers);
});

app.post('/buy', express.json(), async (req, res) => {
  // attemptId: a fresh id the page makes on each Buy click (crypto.randomUUID()) and resends only on a retry.
  const { attemptId, offerKey, offerVersion, email, name, phone, contactId } = req.body;
  const answer = await fetch(`${API}/checkouts`, {
    method: 'POST',
    headers: { ...headers, 'Idempotency-Key': attemptId },
    body: JSON.stringify({
      offerKeys: [offerKey], offerVersion,
      buyer: { email, name, phone },
      successUrl: 'https://youragency.com/thanks', cancelUrl: 'https://youragency.com/plans',
      metadata: { contact_id: contactId },
    }),
  }).then((r) => r.json());
  if (answer.status !== 'success') return res.status(409).json(answer.error ?? answer);
  res.json({ url: answer.data.url });
});

app.post('/servicelocal-webhook', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.get('X-ServiceLocal-Signature') ?? '';
  if (!verifyServiceLocal(req.body.toString('utf8'), signature, process.env.SERVICELOCAL_WEBHOOK_SECRET)) {
    return res.sendStatus(400);
  }
  const event = JSON.parse(req.body.toString('utf8'));
  // Drop an eventId you have seen, then update the contact named in event.metadata.contact_id.
  res.sendStatus(200);
});

app.listen(3000);
```

## Errors

| HTTP | Code | Meaning |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The body failed validation: see `details` |
| 400 | `idempotency_key_required` | A checkout without an `Idempotency-Key` header |
| 401 | `UNAUTHORIZED` | Key missing, wrong or revoked |
| 404 | `offer_not_found` | Unknown or retired plan: read the offers again |
| 404 | `checkout_not_found` | Not a checkout this key started |
| 409 | `offer_version_changed` | The price changed: read the offers again and show the new price |
| 409 | `agency_cannot_sell` | Your agency cannot take payments right now: check Billing › Getting paid |
| 409 | `agency_subscription_required` | Your own ServiceLocal plan is not paid and active: activate it under Billing |
| 409 | `buyer_already_client` | This email already pays you: send the buyer to sign in and manage their plan |
| 409 | `offer_not_on_key_account` | This key cannot sell that offer, or used an API it has no access to (payment links) |
| 409 | `idempotency_key_reused` | That Idempotency-Key was used for a different checkout |
| 409 | `open_payment_link_required` | The retried checkout has closed: read it first |
| 409 | `checkout_not_created` | The first request never reached Stripe: use a new Idempotency-Key |
| 429 | `RATE_LIMITED` | Too many requests from one IP. Per minute: offers 120, checkouts 60 |

## For AI agents

Paste this into your AI agent (Claude, ChatGPT, Cursor or similar), then describe your funnel:

```text
Build a sales funnel for my agency on ServiceLocal.
Read this first: https://servicelocal.ai/developers/agency-api.md

Keys are in server env vars, never in browser code:
  SERVICELOCAL_API_KEY     sells my plans
  SERVICELOCAL_INTAKE_KEY  sends my leads

My funnel: [who it is for, what it sells, which pages, which tools]

Follow the guide: list my plans, start checkouts on the server,
and act only on signed webhooks.
```

- **Skill:** [download the skill](https://servicelocal.ai/developers/skills/servicelocal-agency-funnels/SKILL.md) and add it to your agent. It loads this workflow whenever the agent builds a funnel.
- **Markdown:** this guide as plain text is at [https://servicelocal.ai/developers/agency-api.md](https://servicelocal.ai/developers/agency-api.md).

## Not available yet

| Not available | Use today instead |
|---|---|
| Payment links through the API | The buy link on each plan, or a checkout per buyer |
| Creating or repricing plans through the API | Pricing › Plans in your console |
| Payment on your own page (Stripe Payment Element) | A hosted checkout or a buy link |
| Promotion codes, coupons, and refunds through the API | None. Codes work today only on ServiceLocal's own offers, not on an agency's plans |
