# Invoice Gateway API

The Invoice Gateway lets an assistant (a person or an AI agent) create invoices in the company's QuickBooks Online **without** access to the rest of the books. Through this API you can:

- list customers (name and email only),
- list services and their rate-card prices,
- create invoices,
- read the invoices **you** created.

That's all. There are no endpoints to edit or delete anything, and none for reports, balances, payments or other financial data.

Base URL: `https://a-i.botlabs.agency`

## Keys and sandbox

You receive two values from the administrator:

| Value | Example | Notes |
|---|---|---|
| Key ID | `qbg_test_k3m9x2…` | Public identifier, sent with every request |
| Secret | `qbs_…` | **Never sent anywhere.** Used only to sign requests. Keep it in a password manager / environment variable |

- `qbg_test_…` — **sandbox** key. Works against a fake QuickBooks company with made-up customers and services. Use it to build and test your automation. Try requests in the browser at `/sandbox`.
- `qbg_live_…` — **live** key. Creates real invoices. Works only server-to-server (refused from web browsers), may be restricted to specific IP addresses.

Sandbox and live are fully separate: different customers, services, ids and invoices. Sandbox data can be reset by the administrator at any time.

## Signing requests

Every request must carry four headers:

| Header | Value |
|---|---|
| `X-QBG-Key` | your Key ID |
| `X-QBG-Timestamp` | current Unix time in seconds (must be within 5 minutes of server time) |
| `X-QBG-Nonce` | a random string, 16–128 chars of `A-Z a-z 0-9 _ -`, **never reused** |
| `X-QBG-Signature` | lowercase hex HMAC-SHA256 of the canonical string, keyed with your Secret |

Canonical string — five parts joined with `\n`:

```
METHOD
PATH_WITH_QUERY        exactly as sent, e.g. /v1/services?customerId=58
TIMESTAMP
NONCE
SHA256_HEX(BODY)       hash of the exact body bytes; for GET hash the empty string
```

Ready-made clients that do this for you: `client/qbg-client.mjs` (Node.js) and `client/qbg_client.py` (Python). With them:

```bash
export QBG_BASE_URL=https://a-i.botlabs.agency QBG_KEY_ID=qbg_test_… QBG_SECRET=qbs_…
node qbg-client.mjs ping
python3 qbg_client.py customers
```

Minimal signing example (Python):

```python
import hashlib, hmac, json, secrets, time, urllib.request
body = b""
ts, nonce = str(int(time.time())), secrets.token_urlsafe(18)
canonical = "\n".join(["GET", "/v1/customers", ts, nonce, hashlib.sha256(body).hexdigest()])
sig = hmac.new(SECRET.encode(), canonical.encode(), hashlib.sha256).hexdigest()
req = urllib.request.Request(BASE + "/v1/customers", headers={
    "X-QBG-Key": KEY_ID, "X-QBG-Timestamp": ts, "X-QBG-Nonce": nonce, "X-QBG-Signature": sig})
print(json.load(urllib.request.urlopen(req)))
```

## Endpoints

### `GET /v1/ping`
Checks your signature and shows your key's mode and permissions.

```json
{ "ok": true, "mode": "test", "key": { "id": "qbg_test_…", "name": "Nelly", "scopes": ["customers:read", "services:read", "invoices:create", "invoices:read"] }, "serverTime": "2026-11-28T15:00:00.000Z" }
```

### `GET /v1/customers?search=abc`  — scope `customers:read`
Customers the administrator made available. `search` (optional) filters by name.

```json
{ "data": [ { "id": "101", "name": "ABC Title Company", "email": "billing@abctitle.example" } ] }
```

### `GET /v1/services?customerId=101`  — scope `services:read`
Services the administrator made available, with prices. With `customerId` you get that customer's prices from the rate card.

```json
{
  "data": [
    { "id": "201", "name": "Full Title Search", "description": "Full 60-year title search", "price": 165.00, "priceSource": "customer_rate" },
    { "id": "203", "name": "Tax & Assessment Search", "description": "…", "price": 35.00, "priceSource": "quickbooks" }
  ],
  "currency": "USD",
  "customerId": "101",
  "rules": { "maxPriceIncreasePct": 50, "autoApproveMax": 1000.00 }
}
```

`priceSource`: `customer_rate` (special price for this customer) → `service_default` (gateway price) → `quickbooks` (item price in QuickBooks) → `null` (no price; you must send `unitPrice`).

### `POST /v1/invoices`  — scope `invoices:create`
Headers: `Content-Type: application/json` and **`Idempotency-Key`** (required, 8–100 chars of `A-Z a-z 0-9 _ . : -`). Use a stable value per job, e.g. `file-2026-1142`. If a request times out, **retry with the same key and the same body** — you will never create a duplicate invoice. Reusing a key with a different body returns `409`.

```json
{
  "customerId": "101",
  "lines": [
    { "serviceId": "201", "quantity": 1, "description": "File #2026-1142 · 12 Main St, Newark NJ" },
    { "serviceId": "203", "quantity": 1, "unitPrice": 40.00 }
  ],
  "txnDate": "2026-11-28",
  "dueDate": "2026-12-28",
  "memo": "Thank you for your business!",
  "reference": "File #2026-1142",
  "priceNote": "Line 2: 12 extra pages in the tax search"
}
```

| Field | Required | Notes |
|---|---|---|
| `customerId` | yes | from `/v1/customers` |
| `lines` | yes | 1–25 lines |
| `lines[].serviceId` | yes | from `/v1/services` |
| `lines[].quantity` | no | default 1; positive, up to 2 decimals, max 1000 |
| `lines[].unitPrice` | no | default = rate-card price. Send it to adjust for complex work (see rules) |
| `lines[].description` | no | up to 1000 chars, printed on the invoice |
| `txnDate`, `dueDate` | no | `YYYY-MM-DD`; default = today / QuickBooks terms |
| `memo` | no | message to the customer, printed on the invoice (≤1000) |
| `reference` | no | your job/file number, stored in the private note (≤200) |
| `priceNote` | no | why the price differs from the rate card — shown to the approver (≤500) |

Unknown fields are rejected (`400`) so typos are caught early.

**Rules applied to every invoice:**

- A price **above** the rate card is accepted automatically up to `maxPriceIncreasePct` (see `/v1/services`). Higher → the invoice waits for approval.
- A price **below** the rate card, or a line without any rate-card price → waits for approval.
- A total above `autoApproveMax` → waits for approval.
- A total above the hard maximum → refused (`422`).
- An invoice dated more than 31 days in the past → waits for approval.
- Customer-facing text (`memo`, line `description`) that mentions payment details (bank, account number, wire, Zelle, PayPal, crypto…), a link or an email address → waits for approval. Payment instructions come from the company's QuickBooks settings, never from the API.
- Each key has a daily invoice limit (`429` when reached). Every invoice counts, including failed and rejected ones.
- The administrator may switch on "approve everything" mode.

**Responses:**

- `201` — created in QuickBooks: `data.status = "created"`, `data.quickbooks = { "invoiceId": "…", "docNumber": "1042" }`.
- `202` — accepted, **waiting for administrator approval**: `data.status = "pending_approval"`, `data.reviewReasons` explains why. Poll `GET /v1/invoices/{id}` later; status becomes `created` or `rejected` (then `rejectionReason` may hold the administrator's note).
- `200` — a retry with an `Idempotency-Key` already used; returns the original result (`"replayed": true`).
- `502` — QuickBooks refused or was unreachable: `data.status = "failed"`, `data.error` is a short generic message (details are visible to the administrator only). Retry with the **same** `Idempotency-Key` and the same body within 24 hours. A retry is checked against the rules again, so it may come back as `202` (waiting for approval) or `422` (customer/service no longer available).

```json
{
  "data": {
    "id": "inv_k2m4n6p8q2r4s6t8v2w4",
    "status": "created",
    "customer": { "id": "101", "name": "ABC Title Company" },
    "lines": [ { "serviceId": "201", "serviceName": "Full Title Search", "quantity": 1, "unitPrice": 165, "amount": 165, "description": "File #2026-1142 · 12 Main St, Newark NJ" } ],
    "total": 205,
    "currency": "USD",
    "txnDate": "2026-11-28",
    "dueDate": "2026-12-28",
    "memo": "Thank you for your business!",
    "reference": "File #2026-1142",
    "reviewReasons": [],
    "quickbooks": { "invoiceId": "9001", "docNumber": "1042" },
    "error": null,
    "rejectionReason": null,
    "createdAt": "2026-11-28T15:02:11.000Z",
    "decidedAt": null
  }
}
```

### `GET /v1/invoices?status=pending_approval&limit=50`  — scope `invoices:read`
Invoices created **by your key**, newest first. `status` (optional): `pending_approval`, `created`, `rejected`, `failed`. `limit` 1–200.

### `GET /v1/invoices/{id}`  — scope `invoices:read`
One invoice created by your key (`id` = `inv_…`).

## Errors

All errors look like:

```json
{ "error": { "code": "unknown_customer", "message": "Customer 999 is not available to this API" } }
```

| HTTP | code | Meaning / what to do |
|---|---|---|
| 400 | `validation_error`, `invalid_json`, `idempotency_key_required` | Fix the request (message says what) |
| 401 | `auth_missing`, `auth_malformed`, `invalid_credentials` | Check headers and signature |
| 401 | `timestamp_out_of_range` | Sync your clock |
| 401 | `nonce_reused` | Generate a new nonce for every request |
| 401 | `key_revoked`, `key_expired` | Ask the administrator for a new key |
| 403 | `insufficient_scope`, `ip_not_allowed`, `browser_not_allowed` | Key is not allowed to do this from here |
| 404 | `not_found` | Unknown endpoint or invoice |
| 405 | `method_not_allowed` | This API cannot modify or delete data |
| 409 | `idempotency_conflict` | Same Idempotency-Key, different body |
| 409 | `retry_expired` | The invoice failed more than 24 hours ago; ask the administrator to retry it |
| 413 | `payload_too_large` | Body over 64 KB |
| 415 | `unsupported_media_type` | Send `Content-Type: application/json` |
| 422 | `unknown_customer`, `unknown_service` | Not available to this API — ask the administrator to open it |
| 422 | `price_required`, `zero_total`, `total_exceeds_limit` | Fix prices / split the invoice |
| 429 | `rate_limited` | Max 60 requests per minute; see `Retry-After` |
| 429 | `daily_limit_reached`, `too_many_failed_attempts` | Wait / contact the administrator |
| 502 | — | QuickBooks problem; retry later with the same Idempotency-Key |
| 503 | `api_disabled` | The administrator stopped the API |

## Notes for AI agents

- Keep the Secret in an environment variable; never print it, never put it in prompts, logs or files that are shared.
- Always look up `customerId` and `serviceId` via the API — do not guess ids.
- Use the job/file number as `Idempotency-Key` and `reference`.
- When a job is harder than standard, set `unitPrice` and explain why in `priceNote`.
- A `202` is normal: the invoice is waiting for a human. Do not create it again.
- Every request is logged with the key and IP address.
