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

# Sync bills and payments

> Keep your own copy of the business's bills and payments current: re-read on each payable or payment webhook, and run a scheduled updatedSince poll as the backstop.

This guide keeps a copy of the business's bills and payments in your system without reading every page each time. It has two parts:

1. **Webhooks tell you that something changed.** On each `payable.*` or `payment.*` event, re-read that resource.
2. **A scheduled poll catches everything else.** `GET /v1/payables` and `GET /v1/payments` take `updatedSince`, so each poll reads only what changed.

Webhooks alone are not enough. A delivery can fail all its retries, a paused endpoint misses events, and some changes send no event. The poll covers all of these.

You need a key with `payables:read`, which reads both bills and payments, and `webhooks:manage` to register the endpoint. Webhooks are in early access. Ask your Cleo contact to turn them on for the business.

**1. Load everything once**

Walk `GET /v1/payables?updatedSince=2000-01-01T00:00:00Z&expand=items` and `GET /v1/payments?updatedSince=2000-01-01T00:00:00Z` page by page. Store each record by `id`. Set each resource's cursor to the largest `updatedAt` it returned.

**2. Register a webhook endpoint**

Subscribe to the `payable.*` and `payment.*` events you need. See [Create a webhook endpoint](https://docs.cleo-pay.com/api-reference/webhook-endpoints/create.md).

**3. Re-read on each event**

Fetch the resource the event names and upsert it. Do not move a cursor.

**4. Poll on a schedule**

Every few minutes, or as often as you need, read what changed since 5 minutes before each cursor and upsert it. Then move that cursor to the largest `updatedAt` you read.

## Register the endpoint

```bash theme={null}
curl -X POST https://api.stg.cleo-pay.com/v1/webhook-endpoints \
  --header "Authorization: Bearer $CLEO_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "url": "https://hooks.example.com/cleo",
    "subscribedEventTypes": [
      "payable.created", "payable.updated", "payable.approved", "payable.declined", "payable.cancelled",
      "payable.payment.scheduled", "payable.payment.partially_paid", "payable.paid", "payable.payment.failed",
      "payment.processing", "payment.held", "payment.completed", "payment.failed", "payment.returned",
      "payment.refund_pending", "payment.refunded", "payment.cancelled"
    ],
    "description": "Bill and payment sync"
  }'
```

`payable.*` events reach the payer as well as the business that created the bill. A bill a vendor sends to the business reaches your endpoint. See [Who receives each event](https://docs.cleo-pay.com/reference/webhooks.md#who-receives-each-event).

## Re-read on each event

An event names a resource in `data.object` and `data.id`. It carries no state.

| `data.object` | Fetch with |
| - | - |
| `payable` | [`GET /v1/payables/{data.id}`](https://docs.cleo-pay.com/api-reference/payables/get) |
| `payment` | [`GET /v1/payments/{data.id}`](https://docs.cleo-pay.com/api-reference/payments/get) |

* Upsert what the `GET` returns by `id`.
* Do not rebuild a resource's state from the sequence of event types. Events can arrive late, twice or out of order.
* Do not assume `payable.created` is the first event you get for a bill. Re-read on any event.
* Never move a poll cursor from a record you fetched because of a webhook. That record can carry a newer `updatedAt` than a change the poll has not reached yet. Starting the next poll from it would skip that change.

Store the event and answer the delivery with a `2xx` first, then fetch. See [Webhooks](https://docs.cleo-pay.com/reference/webhooks.md#the-request).

## Poll on a schedule

Keep one cursor for bills and one for payments, stored apart from the records. Each poll:

1. Calls the list with `updatedSince` set a fixed safety window, such as 5 minutes, before the cursor. A change's `updatedAt` is set before it commits, so a change can appear after a poll has passed its timestamp. The overlap catches it.
2. Reads every page. Results come oldest change first, by `updatedAt` and then `id`.
3. Upserts each record by `id`. `updatedSince` is inclusive and the window overlaps the last poll, so expect to see some records again.
4. Sets the cursor to the largest `updatedAt` the poll returned. Never set it to the current time: a change that has not committed yet would fall behind the cursor and never be read. Bulk changes send no webhook, so the poll is the only way to find them.

```js theme={null}
const LOOKBACK_MS = 5 * 60 * 1000;
const PAGE_SIZE = 100;

async function poll(resource, store) {
  // resource is "payables" or "payments"
  const cursor = await store.getCursor(resource);
  const since = new Date(Date.parse(cursor) - LOOKBACK_MS).toISOString();
  let largest = cursor;

  for (let page = 1; ; page++) {
    const url = new URL(`https://api.stg.cleo-pay.com/v1/${resource}`);
    url.searchParams.set("updatedSince", since);
    url.searchParams.set("page", String(page));
    url.searchParams.set("pageSize", String(PAGE_SIZE));
    if (resource === "payables") url.searchParams.set("expand", "items");

    const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.CLEO_API_KEY}` } });
    if (!res.ok) throw new Error(`Cleo answered ${res.status}`);
    const { items, totalCount } = await res.json();

    for (const record of items) {
      await store.upsert(resource, record);
      if (Date.parse(record.updatedAt) > Date.parse(largest)) largest = record.updatedAt;
    }
    if (items.length === 0 || page * PAGE_SIZE >= totalCount) break;
  }

  await store.setCursor(resource, largest);
}
```

Move the cursor only after every page is stored. If a poll fails partway, the next poll starts from the old cursor and reads the same changes again.

Each call counts against your rate limit. With `expand=items`, one call returns up to 100 bills with their line items, so you do not need one call per bill.

## What moves `updatedAt`

A bill's `updatedAt` moves when anything the API returns about it changes: its fields, status, line items, custom field answers, categories, tags and attachments. A payment's `updatedAt` moves when the payment changes.

Some changes send no `payable.updated` but still move `updatedAt`, so only the poll finds them: merging a category, disconnecting an accounting integration, and deleting a tag.

Some changes alter what the API returns for many bills without moving their `updatedAt`. Neither webhooks nor the poll report them:

* renaming or archiving a category;
* renaming a tag;
* relabelling a custom field or one of its options;
* renaming a contact.

If you show these names, read them again from their own source, such as [`GET /v1/payable-custom-fields`](https://docs.cleo-pay.com/api-reference/payable-custom-fields/list) or [`GET /v1/contacts`](https://docs.cleo-pay.com/api-reference/contacts/list), or re-read the affected bills.

A bill's `paymentStatus` comes from its payments. Poll payments as well as bills to follow payment progress.

## Related

* [List payables](https://docs.cleo-pay.com/api-reference/payables/list.md#read-only-what-changed)
* [List payments](https://docs.cleo-pay.com/api-reference/payments/list.md#read-only-what-changed)
* [Webhooks](https://docs.cleo-pay.com/reference/webhooks.md)
* [Payables](https://docs.cleo-pay.com/concepts/payables.md#timestamps)


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