# olyone Storefront API

Build your own website on an olyone shop. Your site shows the shop's products; olyone keeps the catalogue, the
stock, the checkout, the payments and the orders. This one file is the whole reference.

- Base address: `https://api.olyone.lk/v1/storefront`
- Send the shop's site key with every call: `X-Olyone-Key: oly_pk_...`
- Answers are JSON. Money is a number in Sri Lankan rupees (LKR). Dates are ISO 8601.
- Pictures come ready to use: `{ "src", "srcset", "alt" }`, or `null` when there is none.
- Plans: Grow and Pro, and the 14-day trial.

The shop's owner makes the key in olyone: **Settings > Your own website**. The key is publishable. It is safe in a
website's code because it only reads what any visitor of the shop can already see.

## How a site works

1. Read the shop and its products with the `GET` calls below and render your own pages.
2. Keep the bag on your site (for example in `localStorage`) as a list of `variantId` + `qty`.
3. When the customer presses Checkout, call `POST /bag` and send them to the `checkoutUrl` in the answer.
4. olyone's checkout takes the delivery details and the payment. The order page then shows a link back to your site.

You never build a checkout, take a payment or store an order.

## Rules

- Never show a price you worked out yourself at checkout. `POST /bag` is the truth for prices, delivery and total.
- A variant with `"available": false` cannot be bought. Show "Only a few left" when `"low"` is true. There are no
  stock counts.
- If `GET /shop` says `"opening": true`, the shop has not opened. Show "Opening soon" and no checkout.
- Cache what you read for about a minute. Do not call the API on every keystroke or in a loop.
- Fields are only ever added to these answers, never renamed or removed. Ignore fields you do not know.
- Calls from a browser are answered only for websites on the key's list (the owner adds your site's address,
  for example `https://yourshop.lk`, and `http://localhost:5173` while you build). Calls from a server need no
  listing.

## Quick start

```js
const API = "https://api.olyone.lk/v1/storefront";
const KEY = "oly_pk_your_key";
const olyone = (path, init = {}) =>
  fetch(API + path, { ...init, headers: { "X-Olyone-Key": KEY, "Content-Type": "application/json" } }).then(async (r) => {
    if (!r.ok) throw new Error((await r.json().catch(() => null))?.message ?? "olyone " + r.status);
    return r.json();
  });

const shop = await olyone("/shop");
const { items, next } = await olyone("/products?limit=24");
const product = await olyone("/products/batik-shirt");

// Checkout: the bag is [{ variantId, qty }]
const bag = await olyone("/bag", { method: "POST", body: JSON.stringify({ items: [{ variantId: product.variants[0].id, qty: 1 }] }) });
if (bag.canCheckout) location.href = bag.checkoutUrl;
```

## GET /shop

The shop itself.

```json
{
  "name": "Bloom Batiks",
  "url": "https://bloom.oly.lk",
  "currency": "LKR",
  "opening": false,
  "tagline": "Handmade batik, made in Kandy",
  "description": "…",
  "about": "…",
  "brandColor": "#7A45C2",
  "logo": { "src": "https://…", "srcset": "https://… 160w, https://… 320w, https://… 640w", "alt": "Bloom Batiks" },
  "banner": null,
  "contact": { "phone": "+94771234567", "whatsapp": "+94771234567", "email": null, "instagram": "bloombatiks", "facebook": null, "tiktok": null },
  "policies": { "refund": "…", "privacy": null, "terms": null },
  "delivery": { "fee": 400, "freeOver": 10000 },
  "rating": { "average": 4.8, "count": 37 }
}
```

`delivery.freeOver` is the bag value above which delivery is free, or `null`. `rating` is `null` when the shop has
no published reviews.

## GET /products

Product cards, paged.

| Query | Meaning |
|---|---|
| `limit` | 1 to 50, default 24 |
| `cursor` | the `next` value from the page before |
| `q` | search words |
| `collection` | a collection id, to list only its products |
| `tag` | only products carrying this tag (upper or lower case does not matter) |
| `brand` | only products by this brand |

```json
{
  "total": 58,
  "items": [
    {
      "id": "0b9c6c1e-…",
      "handle": "batik-shirt",
      "name": "Batik Shirt",
      "category": "Shirts",
      "brand": "Louis Sachar",
      "tags": ["Fiction", "Gift"],
      "price": 2700,
      "compareAtPrice": 3200,
      "onSale": true,
      "available": true,
      "image": { "src": "https://…", "srcset": "…", "alt": "Batik Shirt" },
      "rating": { "average": 4.9, "count": 12 },
      "options": [{ "name": "Size", "type": "size", "values": [{ "value": "M", "hex": null }, { "value": "L", "hex": null }] }]
    }
  ],
  "next": "MjQ"
}
```

`tag`, `brand`, `q` and `collection` can be combined. `brand` is who makes the product (a maker, or a book's
author) and is `null` when the shop has not set one; `tags` is the shop's own list of labels, `[]` when empty.

`next` is `null` on the last page. `price` is the starting price; `compareAtPrice` is the crossed-out price, or
`null`. An option value's `hex` is its colour swatch when the option is a colour.

## GET /products/{id or handle}

One product, by its `id` or its `handle` (the readable name for links).

```json
{
  "id": "0b9c6c1e-…",
  "handle": "batik-shirt",
  "name": "Batik Shirt",
  "description": "**Bold** and plain text, as Markdown",
  "descriptionHtml": "<p><strong>Bold</strong> and plain text, as Markdown</p>",
  "category": "Shirts",
  "brand": "Louis Sachar",
  "tags": ["Fiction", "Gift"],
  "fields": [
    { "key": "pages", "label": "Pages", "type": "number", "value": 233, "text": "233" },
    { "key": "signed_copy", "label": "Signed copy", "type": "boolean", "value": false, "text": "No" }
  ],
  "price": 2700,
  "compareAtPrice": null,
  "onSale": false,
  "available": true,
  "images": [{ "src": "https://…", "srcset": "…", "alt": "Batik Shirt", "optionValueId": null }],
  "options": [{ "id": "…", "name": "Size", "type": "size", "values": [{ "id": "…", "value": "L", "hex": null }] }],
  "variants": [
    { "id": "6f4add49-…", "label": "L", "price": 2700, "available": true, "low": false, "optionValues": { "Size": "L" } }
  ],
  "rating": { "average": 4.9, "count": 12 },
  "reviews": [{ "id": "…", "rating": 5, "title": null, "body": "…", "author": "Nimali", "verified": true, "photo": null, "date": "2026-10-02T08:11:00.000Z" }]
}
```

`description` is the shop's own words as Markdown. `descriptionHtml` is the same text as safe HTML (paragraphs,
bold, italic, headings, lists, links) - put it straight into the page.

`fields` are the shop's own details (pages, material, language - whatever the shop defined), in the shop's order,
and only the ones the shop chose to show. `[]` when there are none. `type` is `text`, `number`, `boolean`, `date`
(`value` is `YYYY-MM-DD`), `url` or `choice`. `value` is the typed value; `text` is the same value ready to show
("Yes", "1,233", "20 Aug 1998") - a details table is just `label` beside `text`. A `key` never changes once made.

A customer buys a **variant**. Every product has at least one; send the variant's `id` to the bag. An image's
`optionValueId` says which option value (for example a colour) the picture shows, when the shop set one.

## GET /tags

Every tag and brand on the products on sale, with how many products carry each - most used first. Use it to build
a menu or a filter.

```json
{ "tags": [{ "name": "Fiction", "count": 41 }, { "name": "Gift", "count": 12 }], "brands": [{ "name": "Louis Sachar", "count": 2 }] }
```

## GET /collections

```json
{ "items": [{ "id": "…", "name": "Shirts", "description": null, "image": null, "featured": true, "productCount": 14 }] }
```

## GET /collections/{id}

One collection with its product cards, in the shop's own order.

```json
{ "id": "…", "name": "Shirts", "description": null, "image": null, "products": [ { "id": "…", "handle": "batik-shirt", "…": "the same card as GET /products" } ] }
```

## GET /reviews

Published shop reviews. Empty when the shop keeps reviews off.

```json
{
  "rating": { "average": 4.8, "count": 37 },
  "items": [{ "id": "…", "rating": 5, "title": null, "body": "…", "author": "Nimali", "verified": true, "photo": null, "reply": null, "product": "Batik Shirt", "date": "2026-10-02T08:11:00.000Z" }]
}
```

## POST /bag

Prices a bag and gives the link into the shop's checkout. Nothing is saved and no stock is held, so call it again
whenever the bag changes and always just before checkout.

Send up to 50 lines:

```json
{ "items": [{ "variantId": "6f4add49-…", "qty": 2 }], "discountCode": "TENOFF", "note": "Please gift wrap", "returnTo": "https://yourshop.lk" }
```

Only `items` is required. `discountCode` is a code the customer typed on your site; `note` (up to 500 characters) is
their message for the shop. Both are carried into the checkout, so the customer does not type them again.

`returnTo` is optional and only needed when the call comes from your server: it names the site the customer goes
back to after ordering. It must be a website on the key's list. A call from a browser uses the page's own site.

```json
{
  "currency": "LKR",
  "lines": [
    {
      "variantId": "6f4add49-…",
      "productId": "0b9c6c1e-…",
      "name": "Batik Shirt",
      "label": "L",
      "price": 2700,
      "qty": 2,
      "lineTotal": 5400,
      "image": { "src": "https://…", "srcset": "…", "alt": "Batik Shirt" },
      "available": true,
      "problem": null
    }
  ],
  "subtotal": 5400,
  "deliveryFee": 400,
  "discount": 0,
  "discountLabel": null,
  "discountCode": null,
  "discountMessage": null,
  "total": 5800,
  "canCheckout": true,
  "checkoutUrl": "https://bloom.oly.lk/bag/add?items=…&site=oly_pk_…"
}
```

`problem` on a line:

| Value | Meaning | What to do |
|---|---|---|
| `null` | fine | |
| `sold_out` | none left | ask the customer to remove it |
| `low_stock` | fewer left than asked | ask the customer to lower the quantity (the checkout also offers the fix) |
| `unavailable` | no longer sold | remove it from the bag |

Sold-out and unavailable lines are not counted in the totals and are left out of `checkoutUrl`. `discount` is the
code you sent when it is good (`discountCode` echoes it), otherwise an automatic offer the shop is running, if the
bag qualifies. When a code is not accepted, `discountCode` is `null` and `discountMessage` says why in plain words -
show it to the customer. A customer can also enter a code at checkout. `canCheckout` is
`false`, and `checkoutUrl` is `null`, when nothing in the bag can be bought or the shop has not opened.

Send the customer to `checkoutUrl` in the same tab. Do not change it.

## Cart (optional)

`POST /bag` is all a site needs. If you would rather olyone keeps the cart - so it survives a new device or a
cleared browser - use a cart instead. You store only its `id`. Every answer has the same shape as `POST /bag`, plus
`id`, `note` and `updatedAt`, and is priced at that moment.

| Call | Does |
|---|---|
| `POST /cart` | makes a cart. The body is optional: `{ "items": [...], "discountCode": "…", "note": "…" }` |
| `GET /cart/{id}` | the cart, priced now |
| `POST /cart/{id}` | changes it (below) |

Changing a cart - send any of these together:

```json
{
  "add": [{ "variantId": "6f4add49-…", "qty": 1 }],
  "set": [{ "variantId": "964b922f-…", "qty": 0 }],
  "discountCode": "TENOFF",
  "note": null
}
```

`add` adds to a line's quantity (or starts the line). `set` sets a line's quantity; `0` removes it. `items` replaces
every line. `discountCode` and `note` set a value, and `null` clears it. A cart holds up to 50 different items.

Send the customer to the cart's `checkoutUrl` as with `POST /bag`. Read it fresh just before checkout.

A cart ends when an order is placed from it, or after 30 days without a change. From then on every call answers
`404` with `"code": "cart_gone"`: forget the id and make a new cart. Treat the id like a password for that one
cart - anyone who has it can read and change it.

## Refresh ping (optional)

Most sites do not need this: they read from olyone and show changes within a minute. A pre-built (static) site can
ask to be told when something changed. The shop's owner pastes one address on your site into olyone
(**Settings > Your own website > Keep your site fresh**) and gets a secret for it.

After the owner changes products, prices, collections, discounts, reviews or shop settings, olyone sends one request
(edits made close together are gathered into one):

```
POST https://yourshop.lk/api/olyone-refresh
Content-Type: application/json
X-Olyone-Signature: t=1794590000,v1=5f2b…

{ "event": "shop.updated", "shop": "bloom", "at": "2026-11-13T17:20:00.000Z" }
```

Check the signature before you act: `v1` is the HMAC-SHA256, in hex, of `t + "." + the raw body`, keyed with the
secret. Refuse a `t` more than five minutes old. Then rebuild, or clear your cache, and answer `200` quickly.

```js
import { createHmac, timingSafeEqual } from "node:crypto";

function fromOlyone(rawBody, header, secret) {
  const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  if (!t || !v1 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const want = createHmac("sha256", secret).update(t + "." + rawBody).digest("hex");
  return want.length === v1.length && timingSafeEqual(Buffer.from(want), Buffer.from(v1));
}
```

The address must be public `https`. olyone waits 5 seconds, does not follow redirects and does not retry, so treat
the ping as a hint, not a guarantee: keep reading with a short cache as well. The message never says what changed.
A customer's order does not send one. "Send a test" in olyone sends the same message with `"test": true`.

## Errors

Every error is JSON with a `message` in plain words.

| Status | Meaning |
|---|---|
| 400 | the request is wrong (for example an empty bag or a bad id) |
| 401 | no site key, or the key was switched off |
| 403 | `code: "upgrade_required"` - the shop's plan does not include its own website. Otherwise: a browser on a website that is not on the key's list |
| 404 | no such product or collection, or the shop is closed |
| 429 | too many calls - slow down and cache |

Limits: about 1,200 calls a minute per key, and 240 a minute from one address. A site that caches for a minute
never comes near them.

## The shop's addresses (for the owner)

- **Checkout on your own address.** `checkoutUrl` uses the shop's olyone address (`yourshop.oly.lk`). To keep
  customers on your name, the owner connects a subdomain such as `checkout.yourshop.lk` in olyone (Store settings >
  Custom domain); `checkoutUrl` then uses it. The main address stays with your website.
- **Old links.** When the site is ready, the owner can switch on "Send my olyone shop's visitors to my website".
  Links to the olyone shop then open the same page on your site: a product goes to `/products/{handle}` and a
  collection to `/collections/{id}` unless the owner sets other patterns (`{handle}` and `{id}` are both
  available for products). Build your pages on those links, or tell the owner yours.

## What this API does not do

It has no customer accounts, no orders, no payments and no way to change anything in the shop. Orders are placed
only in olyone's checkout, and the shop's owner sees them in the olyone app and console. A shop owner who wants an
AI assistant to work with orders and stock connects it separately: https://olyone.lk/developers/ai

## Help

WhatsApp 077 204 3588 (+94 77 204 3588). Human guide: https://olyone.lk/developers/storefront-api
