# upsell.studio as the backend of your website

upsell.studio holds the shop: **categories, products (prices, photos, offers, variants), store info and orders**.
Your website only displays the catalogue and sends the orders; Upsell's AI then confirms every order with the customer
on WhatsApp (Darija), and the seller manages everything (catalogue, orders, delivery) in the Upsell dashboard.

- API base URL: `https://upsell.studio/api/v1`
- Machine-readable spec (OpenAPI 3.1): https://upsell.studio/api/v1/openapi.json
- This guide: https://upsell.studio/integration.md

---

## 1. Security rules — follow all of them

1. **The API key is a secret.** Store it only in a server-side environment variable `UPSELL_API_KEY`
   (`.env.local`, hosting dashboard). Never in client code, never with a `NEXT_PUBLIC_` / `VITE_` / `PUBLIC_` prefix,
   never in the repository (make sure `.env*` is in `.gitignore`), never in logs or error messages.
2. **Call the API only from the server** (server components, route handlers, server actions, a backend). The browser
   talks to YOUR server, never to Upsell with the key.
3. Use a **Website key**: in Upsell → *Connexions › Intégrations › API & webhooks* → « Connecter mon site web ». It has only
   two permissions: `products:read` (read the catalogue) and `orders:write` (send an order). It **cannot** read
   customers or existing orders, nor change the catalogue. One key = one store. The seller can revoke it at any time,
   it expires after one year, and it can be locked to your server's IP addresses.
4. **Never trust prices from the browser.** Compute the order total on the server from the product returned by the API
   (and its `offers`), then send it.
5. Protect your order form against spam (honeypot field and/or captcha, rate limit per IP) and send an idempotency
   reference (`external_ref`) so a double click never creates two orders.
6. Render product texts as **plain text** (escape them); never inject them as raw HTML.
7. If a request returns `401 invalid_api_key` / `expired_api_key`, stop and tell the site owner to create a new
   Website key — don't retry in a loop.

## 2. Setup

```bash
# .env.local (server-side only)
UPSELL_API_URL=https://upsell.studio/api/v1
UPSELL_API_KEY=cai_xxxxxxxxxxxxxxxxxxxxxxxx   # the seller pastes it here — never commit it
```

Every request: `Authorization: Bearer $UPSELL_API_KEY`, JSON in and out.
Errors always look like `{ "error": { "code": "…", "message": "…", "details"?: [] } }`.
Rate limit: 120 requests/minute per key by default (`X-RateLimit-*` headers; `429` + `Retry-After`). **Cache** catalogue
reads (e.g. revalidate every 60 s) instead of calling the API on every page view.

## 3. Endpoints your website needs

### GET /store
Store name, currency, logo, default delivery info and return policy (for the header, footer, product pages).
```json
{ "data": { "id": "…", "name": "Atlas Shop", "currency": "MAD", "country": "MA", "logo_url": "https://…", "delivery_info": "Livraison 24–48h…", "return_policy": "…", "website_url": "https://…" } }
```

### GET /categories?active=true
Sorted list (`sort`, then name). One level of sub-categories via `parent_id`.
```json
{ "data": [ { "id": "…", "slug": "montres", "name": "Montres", "description": null, "image_url": null, "parent_id": null, "sort": 0, "is_active": true, "product_count": 12 } ] }
```

### GET /products?active=true&category={slug}&limit=100&offset=0
Optional filters: `category` (id, slug, or `none`), `q` (name search), `sku`. Paginate with `limit` (max 500) / `offset`.
```json
{
  "data": [{
    "id": "…", "slug": "montre-classic", "name": "Montre Classic", "sku": "MC-01",
    "price": 299, "compare_at_price": 399, "currency": "MAD",
    "short_pitch": "…", "description": "…", "features": ["Étanche"],
    "faq": [{ "q": "…", "a": "…" }],
    "offers": [{ "qty": 2, "price": 499, "label": "Pack duo" }],
    "variants": [{ "name": "Couleur", "options": ["Noir", "Argent", "Or"] }],
    "images": ["https://…"], "videos": [], "delivery_info": null,
    "is_active": true, "category_id": "…", "category": { "id": "…", "slug": "montres", "name": "Montres" },
    "created_at": "…", "updated_at": "…"
  }],
  "paging": { "limit": 100, "offset": 0, "total": 1 }
}
```
Show only `is_active: true` products. `offers` = bundle prices: buying `qty` units costs `price` in total.

### GET /products/{slug}
One product by slug (or id) — your product page. `404` → show your "not found" page.

### POST /orders
Send the order when the customer submits your form. Upsell's AI then confirms it on WhatsApp.
```json
{
  "product_id": "…",               // or "sku"
  "customer_name": "Yassine",
  "customer_phone": "0661482290",  // Moroccan number; +212 / 0 formats accepted
  "city": "Casablanca",
  "address": "Hay Hassani, rue 12",
  "quantity": 1,
  "variant": "Couleur: Noir",
  "total_price": 299,              // computed on YOUR server from the API price/offers
  "notes": "Livrer après 18h",
  "external_ref": "web-7f3a9c"     // your unique order reference (idempotency)
}
```
Response `201 { "data": { "id": "…", "status": "new" | "pending" | "in_conversation", … } }`. The same `external_ref`
sent twice returns the first order with `"duplicate": true` (no second order). Show the customer a thank-you page
saying they'll receive a WhatsApp message to confirm.

## 4. Reference implementation (Next.js App Router, TypeScript)

```ts
// lib/upsell.ts — server-only
import "server-only";
const API = process.env.UPSELL_API_URL ?? "https://upsell.studio/api/v1";

async function upsell<T>(path: string, init: RequestInit & { revalidate?: number } = {}): Promise<T> {
  const key = process.env.UPSELL_API_KEY;
  if (!key) throw new Error("UPSELL_API_KEY is not set");
  const { revalidate = 60, ...rest } = init;
  const res = await fetch(`${API}${path}`, {
    ...rest,
    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", ...(rest.headers ?? {}) },
    next: rest.method && rest.method !== "GET" ? undefined : { revalidate },
    cache: rest.method && rest.method !== "GET" ? "no-store" : undefined,
  });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(`Upsell ${res.status} ${body?.error?.code ?? ""}`); // never include the key
  return body as T;
}

export const getStore = () => upsell<{ data: Store }>("/store");
export const getCategories = () => upsell<{ data: Category[] }>("/categories?active=true");
export const getProducts = (category?: string) =>
  upsell<{ data: Product[] }>(`/products?active=true&limit=200${category ? `&category=${encodeURIComponent(category)}` : ""}`);
export const getProduct = (slug: string) => upsell<{ data: Product }>(`/products/${encodeURIComponent(slug)}`);
export const createOrder = (order: OrderInput) => upsell<{ data: { id: string; status: string } }>("/orders", { method: "POST", body: JSON.stringify(order) });
```

```ts
// app/actions/order.ts — server action: price computed on the server
"use server";
import { getProduct, createOrder } from "@/lib/upsell";

export async function placeOrder(form: FormData) {
  if (form.get("website")) return { ok: false };                 // honeypot
  const { data: p } = await getProduct(String(form.get("slug")));
  const qty = Math.max(1, Math.min(10, Number(form.get("qty")) || 1));
  const offer = p.offers?.find((o) => o.qty === qty);
  const total = offer ? offer.price : p.price * qty;
  const { data } = await createOrder({
    product_id: p.id, quantity: qty, total_price: total,
    customer_name: String(form.get("name") ?? "").slice(0, 200),
    customer_phone: String(form.get("phone") ?? "").slice(0, 30),
    city: String(form.get("city") ?? "").slice(0, 120),
    address: String(form.get("address") ?? "").slice(0, 500),
    variant: String(form.get("variant") ?? "").slice(0, 200) || undefined,
    external_ref: `web-${crypto.randomUUID()}`,
  });
  return { ok: true, orderId: data.id };
}
```

Pages: `/` (categories + featured products), `/c/[slug]` (`getProducts(slug)`), `/p/[slug]` (`getProduct(slug)`, gallery from
`images`, variants as selects, offers as quantity choices, order form calling `placeOrder`), `/merci`.
Other stacks (PHP, Node/Express, Python…): same HTTP calls from the backend with the same rules.

## 5. Optional — order status on your site
Order statuses can be pushed to your server with signed webhooks (`order.confirmed`, `order.cancelled`,
`order.shipping_updated`, …). That needs a **separate** key with the `webhooks` scope (not the Website key), created
by the seller. Verify every call: `X-Upsell-Signature: sha256=<hex HMAC-SHA256 of "<X-Upsell-Timestamp>.<raw body>">`
with the signing secret, reject if the timestamp is older than 5 minutes, compare in constant time. Details in the OpenAPI spec.

## 6. Checklist for the AI assistant doing the integration
1. Ask the site owner to create a **Website key** in Upsell (Connexions › Intégrations › API & webhooks) and to paste it
   themselves into the server env as `UPSELL_API_KEY` — never ask them to paste it in the chat.
2. Add `lib/upsell.ts` (server-only) and the types from the JSON above.
3. Build the category, product and order pages; compute totals on the server; add the honeypot + rate limit.
4. Test: `GET /store` then `GET /products?limit=1` from the server; place one test order with the owner's own phone
   number and check it appears in Upsell → Commandes.
5. Confirm that the key appears in no client bundle (`grep -r "cai_" .next/static` must find nothing) and no commit.
