Metr Fit / API V1

Shopify authorization and catalog sync

Authorize a Shopify store, refresh expiring tokens, import the catalog and synchronize variant stock.

Configure the standalone app

Set the app launch URL to https://metr.so/console and register https://metr.so/api/console/shopify/callback as the exact redirect. The API requests read_products,read_inventory,write_app_proxy. Existing installations must approve the proxy scope before widget setup. App credentials and the stable token-encryption key belong in server-side Secret Manager configuration, never in themes or browser JavaScript.

Verify the launch

A launch without code and state is not completed authorization. The website backend sends the original signed query in a JSON body to the gateway-only endpoint below. Go verifies HMAC, shop syntax, unique query parameters and freshness. The response contains only shop; it saves no connection and creates no OAuth state.

POST /v1/console/shopify/launch
{
  "query": "<original Shopify-signed launch query without a leading ?>"
}

Retain the signed launch privately for at most ten minutes, require seller sign-in and explicit Metr store selection, and reverify before starting OAuth. An unsigned shop query is never proof of authorization.

Start and complete authorization

The website sends launch_query in the authenticated store-specific start body, or an empty object for the ordinary flow. The backend scopes the selected store to the merchant and binds fresh single-use state to its store-domain snapshot, seller session and the verified Shopify shop. It does not silently rewrite the saved storefront domain.

POST /v1/console/stores/{store_id}/shopify/start
{
  "launch_query": "<original Shopify-signed launch query>"
}

The callback requires Shopify HMAC, a fresh timestamp, the originating session, unexpired single-use state and an exact shop match. Only a successful token exchange with the required scopes saves AES-GCM encrypted tokens. Expiring tokens are refreshed automatically before use. An app launch alone cannot save a connection.

GET /v1/console/shopify/callback

Catalog and stock synchronization

After authorization, trigger catalog sync explicitly. The importer uses Shopify Admin GraphQL 2026-07 and completes product and variant pagination before writing. Authentication, paging and write errors fail the sync without committing a partial catalog. Sizes and product types are normalized. Resync preserves merchant sizing metadata and verified chart links, and marks missing Shopify variants unavailable. Recommendations still require merchant-verified size charts. Webhook subscriptions are not registered automatically; the in-process resync timer is not reliable on scale-to-zero hosting. Stock freshness is not guaranteed. Console sync has a 28-second application deadline. Deadline or cancellation failures return HTTP 504 with sync_unconfirmed: Could not confirm sync completion. Refresh connection status and preserve the last successful sync time; do not automatically retry or infer that reconnecting is required. A timeout response does not prove a commit was rolled back.

POST /v1/console/stores/{store_id}/shopify/sync
POST /v1/webhooks/shopify

Seller catalog and shared size charts

The seller console can browse store-scoped products and variant availability, create or review size charts, and assign one chart to multiple products. Availability is a stored boolean, not a live stock quantity. The website accepts CSV tables, lets the seller review measurements and requires explicit verification before a chart can support recommendations. CSV files are parsed in the browser and submitted as the existing ChartInput JSON schema; there is no image or PDF extraction endpoint.

GET /v1/console/stores/{store_id}/products
GET /v1/console/stores/{store_id}/products/{product_id}/variants
POST /v1/console/stores/{store_id}/size-charts
PUT /v1/console/stores/{store_id}/size-charts/{chart_id}
POST /v1/console/stores/{store_id}/size-charts/{chart_id}/products
{
  "product_ids": [
    "REPLACE_WITH_PRODUCT_ID",
    "REPLACE_WITH_ANOTHER_PRODUCT_ID"
  ]
}

Assignment accepts 1–100 unique product IDs in the same store and category. It atomically replaces only their chart links and update timestamps; all other product fields and unselected links remain unchanged. Draft charts can be assigned but cannot enable recommendations. Editing a shared chart updates it for all linked products. These endpoints require both the server-only console gateway key and the seller session; integration keys cannot call them.

Storefront sizing widget

The initial theme extension is in metr_website/shopify. Configure the Shopify app proxy at /apps/metr-fit to forward to /v1/storefront/shopify on this API; install the Find my size block in the product information section. This requires write_app_proxy and a separate Shopify app release, not just a website deployment.

POST /v1/storefront/shopify/fit
{
  "action": "start",
  "product_id": "123456789",
  "variant_id": "987654321"
}

Shopify must sign the forwarded query. Start resolves synced Shopify IDs and returns a questions array plus a 30-minute quiz token. Send action=next with token, answers and optional skipped question IDs; action=recommend returns size, explanation, warnings and Shopify variant IDs; action=complete with token and variant_id records acceptance. The token binds one session to its shop, merchant, store and signed customer context. No secret API keys or cookies are used by the widget. Maximum request body: 16 KiB. Do not log tokens, queries or customer answers.

The widget rechecks Shopify availability, preserves non-size options, then selects the variant through the product URL. It explicitly skips optional silhouette questions until illustration assets are bundled. A verified assigned chart is required. Unit checks do not replace Atlas isolation tests and a real Shopify development-store test.

Milo store-wide shopping assistant

POST /v1/storefront/shopify/milo
{
  "message": "A casual cotton outfit",
  "action": "outfit",
  "brief": {
    "currency": "PKR",
    "budget_minor": 2000000
  }
}

The optional all-page app embed uses /apps/metr-fit/milo through the same signed app proxy. The server derives the store from the signed shop. Find returns one product, with another-option swaps rather than a ranked product grid. Outfit defaults to top, bottom and shoes; absent catalog categories return transparent partial results. Swap requires swap_slot and the entire returned brief, including selected Shopify numeric product and variant IDs. Unchanged selections are revalidated and preserved. brief.intent stays find or outfit, query retains cumulative refinements, and swaps preserve the original query. Switching find/outfit resets inherited slot defaults. An optional anchor with a Shopify product_id (and optional variant_id) and action outfit builds the look around that product; the anchor is revalidated, kept first and its slot is not filled again.

Responses contain message, mode, brief, products, total_minor, currency and warnings. Each product contains id, title, a safe store-relative /products/handle URL, image_url, slot, currency, price_minor and available variants with id, title, available, price_minor and options. brief.selected identifies one suggested variant per product. Total and displayed product price use that selection; alternatives can cost more. The widget links to the native product page to confirm options and does not infer body size. The widget sets Milo test-group cart attributes and, only after the customer chooses an option and taps Add to cart, adds items through Shopify's cart; the API never writes carts.

Use integer currency minor units, with the explicit server currency exponents rather than browser formatting defaults: PKR 20000 is 2000000 minor units. Supported zero- and three-decimal currencies retain their exponents. Budget phrases in messages must agree with the explicit budget field; otherwise Milo returns no products and asks the customer to confirm the field. Constraints are never silently relaxed to meet a budget. A category with stock that is too expensive is not treated as missing inventory.

Requires a new full catalog sync to populate public product URLs, descriptions, images, base currency and exact variant prices. Older records and new webhook-only products remain excluded until synced. REST product updates preserve GraphQL-only metadata and use the prior verified currency for prices; explicit draft, archived or unpublished products lose their public URL. Availability and prices come from the last catalog sync, not a live stock guarantee. Customer product-page confirmation is required.

Optional AI selection makes at most two closed Choice calls under one five-second deadline, for intent and selection among prevalidated sets, with an explicit none choice. mode=fallback uses catalog text and price rules with a plain warning that style and material preferences have not been verified. Literal single-word exclusions are supported; arbitrary natural-language preferences are best effort. No generative text provider is required. Query and bounded history are transient, but sent to TypeSafe when AI selection is enabled; do not include personal identifiers.

Limits: 16 KiB JSON; message 1000 UTF-8 bytes; eight history turns of 1000 bytes each; cumulative query 2000 bytes; six unique slots/selections; budget 0–9000000000000 minor units; at most 2000 priced public products and 20000 available priced variants per store. Excess catalogs fail rather than silently truncate. Full developer notes are in metr_api/docs/milo.md. Atlas isolation and live Shopify checks remain separate release gates.

Milo attribution and holdout

POST /v1/storefront/shopify/milo/events
GET /v1/console/stores/{store_id}/milo/insights

The app embed assigns each browser a stable group: a merchant-set share (10% by default) becomes a holdout that never sees Milo. Once per browser session and only with Shopify analytics consent, the widget counts an exposure, and later an open or an engagement (opening a recommended product), through the signed proxy. It also sets the _metr_milo cart attribute to milo or holdout and _metr_milo_engaged to 1 after engagement. The backend stores daily aggregate counters only.

The console insights endpoint reads the last 30 days of Shopify orders (at most 1000, newest first), requesting only cart attributes and order totals, and reports visitors, orders, revenue and engaged orders per group. Reading orders needs Shopify protected customer data access; without it orders_status is access_denied and only counters are returned. Group differences are descriptive, not a significance test or causal proof.

Custom-store outdoor Milo

POST /v1/stores/{store_id}/milo/catalog
POST /v1/stores/{store_id}/milo/catalog/image

Server-to-server only, with a catalog-scoped API key and the existing merchant/store ownership checks. The trusted integration injects a fixed USD snapshot taken from a public Shopify feed and names its vertical: outdoor. Never accept the catalog from a browser. No catalog persistence or Shopify dependency. Maximum 256 KiB JSON and 128 products; 1000 UTF-8 message bytes; six history turns; twelve selected IDs; 2000 cumulative query bytes. Thirty requests per store per minute in addition to normal key limits.

Send vertical, message, action (auto, find, bundle, compare or swap), catalog and optional budget_minor, category, kit, selected_ids, owned_categories, swap_id, history and brief. Outdoor bundle requests can use owned_categories to exclude already-packed kit slots from the purchase selection. Each product has id, title, category, brand, explicit integer price_minor, currency USD, explicit boolean available, optional variant_count, url on the vertical's source store, optional cdn.shopify.com image_url, string specs, description and RFC3339 source_fetched_at. Categories: shelter, sleep, stove, camp, water, pack, lighting, poles, footwear, socks, shell, harness, helmet, rope, bike, ski; kits backpacking, dayhike and climbing. Outdoor Milo never recommends sizes or verifies climbing, bike or ski-system compatibility; customers must confirm safety-critical gear with the store.

Responses return message, mode (ai, fallback or catalog), intent, products, total_minor, currency USD, remaining_minor, kit with any missing slots, comparison rows, alternatives with extra_products, follow_ups, warnings and brief. Amounts named in a message must equal the budget field; otherwise intent is confirm_budget, no products are returned and suggested_budget_minor holds a single readable amount. budget_minor 0 clears the budget. Compare returns listed facts only, marking absent values Not listed. One optional AI Choice call selects among at most six prevalidated options plus none, under five seconds; errors use a labeled fallback. Replies are templates.

The image endpoint accepts one base64-encoded PNG or JPEG up to 4 MiB. It returns one broad outdoor category, a normalized bounding box and confidence evidence for customer confirmation. It does not identify exact models, sizes or compatibility and does not persist the image. Full notes: metr_api/docs/milo-catalog.md.

Failures and limits

  • shop_mismatch: the verified callback shop differs from the shop in this session's state. Open the app from Shopify and start a new authorization for its verified shop.
  • invalid_callback: callback signature, timestamp or required fields failed validation.
  • invalid_state: state expired, was consumed, is missing or belongs to another tenant/session.
  • invalid_launch: the launch signature, fields or freshness could not be verified. Open the app again from Shopify.
  • store_changed: the saved store domain changed during authorization.
  • shopify_unavailable: token exchange failed; start a fresh authorization.

Never log launch/callback queries, codes, state, credentials or tokens.