Sectionly B2B Headless integration

API, custom styles, embedded form and server rendering examples.

# Sectionly B2B Headless API v1

Base URL: `https://b2b.sectionly.ai/api/storefront/v1`.

Use the API with your own HTML/CSS/React components, embed the provided form, or call the API from a Hydrogen/other server. All three use the same inquiry validation and draft-order workflow as the Shopify theme integration.

## Authentication

Create a key in **Headless** in the Shopify app. Its value is shown once; the database stores only its SHA-256 digest. Keys are scoped to one shop, have individual permissions and expiry, and can be revoked immediately.

- Public keys (`sb2b_pk_…`) require an exact allowed browser origin. HTTPS is required except for localhost. Origins contain no paths or wildcards.
- Private keys (`sb2b_sk_…`) are server credentials. Keep them in server environment variables. Any request carrying `Origin` is rejected for private keys.
- Send `X-Sectionly-Key: <key>` or `Authorization: Bearer <key>`; do not send both. Keys in URLs are not accepted.
- Send `X-Sectionly-Visitor`, a stable random 16–80 character ID for the current visitor. SSR callers should pass a visitor/session ID, rather than one shared server identity.
- Permissions: `config:read`, `products:read`, `inquiries:write`.

No Shopify Admin token is needed in the storefront. Tenant context comes from the key, never a client-supplied shop query parameter. Uninstall revokes keys; reinstall requires new keys.

## Endpoints

| Method | Path | Permission | Result |
| --- | --- | --- | --- |
| GET | `/form-config` | `config:read` | Custom fields, default MOQ and display settings |
| GET | `/b2b-products?handles=one,two` | `products:read` | `b2bHandles` and per-handle display decisions |
| POST | `/inquiry` | `inquiries:write` | `{success:true,inquiryId}` (201) |
| GET | `/embed.js`, `/embed.css`, `/form.js` | Public assets | Ready-made inquiry form |

Product decisions accept up to 500 unique valid handles; larger catalogs should issue batches. Optional display context: `collectionHandle`, `isLoggedIn`, `countryCode`, `languageCode`. These fields control presentation; customer permissions, price authorization and checkout access remain the storefront server's responsibility.

API responses use `Cache-Control: no-store` and origin-specific CORS. Preflight allows the documented headers and GET/POST/OPTIONS. Asset responses use ETag and a five-minute cache.

### Inquiry body

```json
{
  "customerName": "Test Buyer",
  "customerEmail": "[email protected]",
  "productId": "123456789",
  "productTitle": "Product title",
  "productHandle": "product-handle",
  "lineItems": [{"variantId":"987654321","quantity":10}],
  "customFields": {"Company Name":"Example Company"},
  "note": "Please quote delivery to our warehouse"
}
```

Multi-product requests may supply `items`, each containing `productId`, `productTitle`, `productHandle`, and `lineItems`. Limits: 256 KiB body, 50 products, 250 variant rows, positive integer quantities and total quantity within PostgreSQL's signed integer range. Required configured fields and the server MOQ are enforced. Invalid items reject the whole request. Variant ownership and active product status are checked with Shopify; canonical product/variant names and SKUs replace client descriptions.

Send a random **`Idempotency-Key`** of 16–128 letters, digits, `_` or `-` for each new inquiry. Retain the same key and unchanged payload when retrying after network failure or 5xx. A successful replay returns the same inquiry ID with `Idempotency-Replayed: true`; reuse with different content returns 409. The unique request identity and submit timeline are committed with the inquiry in one database transaction. Concurrent retries do not dispatch another draft-order workflow. Requests rejected before creation can be corrected and submitted again.

The embedded form retains its request identity during an in-page retry. Reloading starts a new form session; custom clients needing retries across reloads should persist the operation ID and immutable payload until they receive a result.

### Own design / React

```js
const visitor = sessionStorage.b2bVisitor ||= crypto.randomUUID();
const operationId = crypto.randomUUID();
const payload = {/* the inquiry body above */};
const response = await fetch('https://b2b.sectionly.ai/api/storefront/v1/inquiry', {
  method: 'POST',
  credentials: 'omit',
  headers: {
    'Content-Type': 'application/json',
    'X-Sectionly-Key': publicKey,
    'X-Sectionly-Visitor': visitor,
    'Idempotency-Key': operationId,
  },
  body: JSON.stringify(payload),
});
const result = await response.json();
if (!response.ok) throw new Error(result.error);
```

Render inputs and success/error states with your own components and styles. Load `/form-config` first so required custom fields and MOQ match the merchant's settings. Keep `operationId` and `payload` unchanged for a retry.

### JavaScript embed

```html
<div id="b2b-quote"></div>
<script src="https://b2b.sectionly.ai/api/storefront/v1/embed.js"></script>
<script>
SectionlyB2B.mount({
  target: '#b2b-quote',
  publicKey: 'sb2b_pk_REPLACE_WITH_PUBLIC_KEY',
  shopDomain: 'example.myshopify.com',
  product: {
    id: '123456789',
    title: 'Product title',
    handle: 'product-handle',
    variants: [{id:'987654321',title:'Blue / Large',sku:'BLUE-L',available:true}],
  },
}).catch(console.error);
</script>
```

Supply product facts from your storefront data. Numeric IDs or Shopify GIDs are accepted. The widget supports one form per page and a quote list across product pages of the same shop. For multiple independent forms, use the API with your own UI. The widget scopes its quote-cart storage to the shop. To customize the embedded appearance, load your stylesheet after `embed.css` and scope overrides to `.sectionly-b2b-form`; custom API integrations have complete control over their styles.

### Hydrogen / server rendering

Keep the private key in the server's secret environment. Fetch configuration in the server loader and render your own UI in the initial HTML. A server action can relay submissions:

```ts
const response = await fetch(`${process.env.SECTIONLY_API_BASE}/inquiry`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${process.env.SECTIONLY_PRIVATE_KEY}`,
    'X-Sectionly-Visitor': visitorSessionId,
    'Idempotency-Key': operationId,
  },
  body: JSON.stringify(validatedFormPayload),
});
```

Authenticate your server action and apply your framework's CSRF protection. Derive `visitorSessionId` on the server and validate fields; do not let the browser choose your API destination or read private credentials. Forward status, JSON and `Retry-After`; retry a lost response with the same operation ID, never silently create a new one. The API does not require Hydrogen-specific packages.

## Buyer email store domain

Buyer inquiry confirmations, quotes and replies use the Shopify Online Store primary domain by default. The displayed domain is applied consistently to the subject, header, body and footer. It does not change inquiry ownership, Shopify admin links, invoice URLs or Sectionly's verified sending address.

If your Headless storefront uses a different primary domain, open **Quote Settings → Notifications & MOQ → Buyer email identity** and set **Email domain override (optional)** to that domain, for example `www.example.com`. Leave it blank to use Shopify's primary domain automatically. Shopify's Online Store primary domain can still be a `myshopify.com` address even when a Headless storefront has connected custom domains.

The setting applies to future emails. It is controlled by the merchant's authenticated settings, not by fields in an inquiry request. Primary-domain lookups are cached per shop and coalesced under concurrent submissions; a failed lookup does not block inquiry acceptance.

## Errors and rate limits

400: malformed/invalid body, missing visitor or operation ID. 401: missing, expired or revoked key. 403: origin or permission mismatch, or a private key used in a browser. 409: conflicting operation or recent duplicate. 413: body too large. 415: non-JSON write. 429: visitor/IP limit (`Retry-After`). 503: unavailable shop authorization, upstream validation or infrastructure.

Limits are per visitor: 120 reads/minute and 20 writes/hour. Public traffic also has separate IP limits of 600 reads/minute and 100 writes/hour. Private SSR traffic is not charged to a shared server-IP bucket. There is no shared hard quota across everyone using a key. Public writes fail closed if a trusted client address cannot be established.

Configure `HEADLESS_CLIENT_IP_HEADER` to a header your trusted reverse proxy controls. With a forwarded chain, `HEADLESS_TRUSTED_PROXY_HOPS` selects from the right (default 1). Behind Cloudflare, `HEADLESS_TRUST_CLOUDFLARE=true` accepts `CF-Connecting-IP` only when the immediate forwarded peer belongs to a verified Cloudflare network; a direct client's forged Cloudflare header is ignored.