# Create Offline Claim Source: https://docs.orderprotection.com/api-reference/claims/create-offline-claim openapi-claims POST /v1/claims/offline Create a claim for an in-store or offline purchase (e.g., warranty claims) Warranty claims for orders that were made through an alternative sales channel not through your online store. # Create Online Claim Source: https://docs.orderprotection.com/api-reference/claims/create-online-claim openapi-claims POST /v1/claims/{sourceOrderId} Shipping and Warranty claims for orders that were made on your online store. # Get Claims Source: https://docs.orderprotection.com/api-reference/claims/get-claims openapi-claims GET /v1/claims # Get Claims By Order Source: https://docs.orderprotection.com/api-reference/claims/get-claims-by-order openapi-claims GET /v1/orders/{sourceOrderId}/claims # Create Fulfillment Source: https://docs.orderprotection.com/api-reference/fulfillments/create-fulfillment-for-order post /v1/orders/{sourceOrderId}/fulfillments # Delete Fulfillment Source: https://docs.orderprotection.com/api-reference/fulfillments/delete-fulfillment-for-order delete /v1/orders/{sourceOrderId}/fulfillments/{sourceFulfillmentId} # Get Fulfillment Source: https://docs.orderprotection.com/api-reference/fulfillments/get-fulfillments-for-order get /v1/orders/{sourceOrderId}/fulfillments # Update Fulfillment Source: https://docs.orderprotection.com/api-reference/fulfillments/update-fulfillment-for-order put /v1/orders/{sourceOrderId}/fulfillments/{sourceFulfillmentId} # Introduction Source: https://docs.orderprotection.com/api-reference/introduction Beginning integration with OrderProtection.com > [!NOTE] > > You must be an OrderProtection customer to gain access to the API. If you're > looking to integrate as a Partner integration please reach out to > [partners@orderprotection.com](mailto:partners@orderprotection.com) ## Welcome You can choose to use the documentation on this site or if you'd prefer you can use the raw OpenAPI specification file. > **[OrderProtection Endpoints](https://api.production.orderprotection.com/v1/docs/orders-yaml)** > > View the OpenAPI specification file ## Authentication All API endpoints are authenticated using Bearer tokens. These tokens can be generated in your [OrderProtection Dashboard](https://app.orderprotection.com) ``` Authorization Bearer ``` # Add metadata Source: https://docs.orderprotection.com/api-reference/metadata/add-metadata openapi-metadata POST /v1/orders/metadata/{id} Add metadata to an Order in the form of a Badge or Activity feed item # Delete metadata Source: https://docs.orderprotection.com/api-reference/metadata/delete-metadata openapi-metadata DELETE /v1/orders/metadata/{id}/{key} Delete a specific metadata key # Retrieve order metadata Source: https://docs.orderprotection.com/api-reference/metadata/get-metadata openapi-metadata GET /v1/orders/metadata/{id} Get all order metadata for an order # Update metadata Source: https://docs.orderprotection.com/api-reference/metadata/update-metadata openapi-metadata PUT /v1/orders/metadata/{id}/{key} Update a specific metadata key # Create order Source: https://docs.orderprotection.com/api-reference/orders/create-order post /v1/orders # Delete order Source: https://docs.orderprotection.com/api-reference/orders/delete-order delete /v1/orders/{sourceOrderId} # List Orders Source: https://docs.orderprotection.com/api-reference/orders/get-all-orders get /v1/orders # Retrieve Order Source: https://docs.orderprotection.com/api-reference/orders/get-order-by-source-id GET /v1/orders/{sourceOrderId} # Update order Source: https://docs.orderprotection.com/api-reference/orders/update-order put /v1/orders/{sourceOrderId} # Add product to bundle Source: https://docs.orderprotection.com/api-reference/products/add-product-to-bundle openapi-products POST /v2/products/{productId}/bundle Add products to a product bundle # Add Product Child Source: https://docs.orderprotection.com/api-reference/products/add-variant openapi-products POST /v2/products/{productId}/children Create a new product variant # Create Product Source: https://docs.orderprotection.com/api-reference/products/create-product openapi-products POST /v2/products Create a new product # Delete Product Source: https://docs.orderprotection.com/api-reference/products/delete-product openapi-products DELETE /v2/products/{productId} Deletes a product # Get Product Source: https://docs.orderprotection.com/api-reference/products/get-product openapi-products GET /v2/products/{productId} Retrieves a product # Remove product from bundle Source: https://docs.orderprotection.com/api-reference/products/remove-product-from-bundle openapi-products POST /v2/products/{productId}/bundle/remove Remove product ids from bundle # Remove Product Child Source: https://docs.orderprotection.com/api-reference/products/remove-variant openapi-products DELETE /v2/products/{productId}/children/{childId} Removes a product child # Update Product Source: https://docs.orderprotection.com/api-reference/products/update-product openapi-products PUT /v2/products/{productId} Updates a products attributes # Get Insurance Quote Source: https://docs.orderprotection.com/api-reference/quote/get-quote openapi-quote GET /v1/quote/insurance?store_url={store_url} Retrieves insurance pricing rules. A range of pricing rules is returned, and the logic to determine which rule to use should be handled on the client side. The `store_url` is the URL of the store to get insurance quote for, e.g. `docs.orderprotection.com`. #### Example If the subtotal (the price before add-ons and shipping) is `$1,000`, and one of the pricing rules specifies a minimum of `$0` and a maximum of `$5,000`, this rule should be applied to calculate the price of Order Protection, as the subtotal falls within the specified range. #### Notes * The amounts in pricing rules are always in `USD`. If the subtotal is in a different currency, the amount should be converted to the cart's currency using the current exchange rate. * The `rules` array is sorted by `min` in ascending order. * If the pricing rule has a type of `brand`, Order Protection should not be added to the cart. # Get Test Events Source: https://docs.orderprotection.com/api-reference/tests/test-events openapi-tests GET /v1/split-tests/{id}/events # List Tests Source: https://docs.orderprotection.com/api-reference/tests/tests openapi-tests GET /v1/split-tests # Analytics API Source: https://docs.orderprotection.com/developer/analytics-api Read-only access to your store's order and claim analytics — raw tables and pre-computed metrics. The Analytics API gives you programmatic, read-only access to your store's analytics: raw data tables (orders, claims, addresses, claim items, resolutions, and per-line resolution economics) and pre-computed metrics (attach rate, claim rate, and more). Use it to feed OrderProtection data into your own dashboards, BI tools, or reports. ## Authentication Every request needs a Bearer token carrying the `analytics:read` scope. Two token types work: * A **[Personal Access Token](/developer/personal-access-tokens)** (`op_pat_`) — for accessing your own account's stores. * An **[OAuth access token](/developer/authentication)** (`op_at_`) — for an app a merchant installed and granted `analytics:read`. ```bash theme={null} curl -X GET "https://api.production.orderprotection.com/v1/analytics/metrics/order_attach_rate/timeseries?granularity=month" \ -H "Authorization: Bearer op_pat_8508b7432c45f79827460fea_ajhnyH..." ``` > [!WARNING] > > A token without the `analytics:read` scope receives `403 Forbidden`. Requesting a store outside your token's authorized set receives `403` with code `STORE_OUT_OF_SCOPE`. ### Store scoping Results are always limited to your account and the stores your token is authorized for. By default an endpoint returns data for **all** of the token's authorized stores. Pass `store_ids` to narrow to specific stores: ``` ?store_ids=store_abc123&store_ids=store_def456 ``` The `store_ids` you receive back in the response `meta` reflect the exact scope that was applied. ## Data freshness Analytics tables are rebuilt on a batch schedule (roughly every 8 hours), so data is **not** real-time and can be **up to \~8 hours behind** your live store data. Every response includes a `data_freshness_at` timestamp in its `meta` block — the time the underlying table was last rebuilt by the batch job (not a per-row timestamp): ```json theme={null} "meta": { "data_freshness_at": "2026-07-08T06:00:00.000Z" } ``` ## Tables Tables return raw, row-level records. > [!NOTE] > > **No PII is exposed.** Each table has a fixed allowlist of safe columns; personally identifiable fields (customer name, email, etc.) are never included and cannot be requested. The `fields` parameter can only ever *narrow* to columns within that allowlist — asking for a field outside it is dropped, and a request for *only* disallowed fields returns `400 INVALID_FIELDS`. ### List tables ``` GET /v1/analytics/tables ``` Returns the available tables, each with its selectable columns. ```json theme={null} { "data": [ { "key": "orders", "safeColumns": ["order_id", "store_id", "created_at", "..."], "sortColumns": ["created_at", "order_total"] }, { "key": "claims", "safeColumns": ["claim_id", "order_id", "claim_state", "..."], "sortColumns": ["created_at", "updated_at"] } ], "meta": { "data_freshness_at": "2026-07-08T06:00:00.000Z" } } ``` ### Get rows ``` GET /v1/analytics/tables/{name} ``` | Parameter | Description | | - | - | | `store_ids` | Repeatable. Restrict to specific stores within your scope. | | `from` | Start of the time window (ISO 8601). Defaults to 30 days ago. | | `to` | End of the time window (ISO 8601). Defaults to now. | | `fields` | Comma-separated subset of the table's columns. Defaults to all safe columns. | | `limit` | Page size. Defaults to 1000, maximum 10000. | | `cursor` | Opaque cursor from a previous response's `meta.next_cursor`. | ```json theme={null} { "data": [ { "order_id": "ord_...", "store_id": "store_abc123", "created_at": "2026-07-01T12:00:00.000Z", "order_total": 84.99, "currency": "USD" } ], "meta": { "data_freshness_at": "2026-07-08T06:00:00.000Z", "store_ids": ["store_abc123"], "next_cursor": "eyJ2Ijpbl...", "has_more": true } } ``` To page through results, resend the request with `cursor` set to `meta.next_cursor` until `has_more` is `false`. #### Available tables | Table | Grain | Columns | | - | - | - | | `orders` | one row per order | `order_id`, `store_id`, `account_id`, `policy_id`, `created_at`, `order_total`, `currency`, `platform`, `source_order_number` | | `claims` | one row per claim | `claim_id`, `order_id`, `store_id`, `account_id`, `claim_type`, `claim_state`, `claim_category`, `created_at`, `updated_at` | | `claim_items` | one row per claim line item | `claim_item_id`, `claim_id`, `order_id`, `store_id`, `account_id`, `sku`, `item_name`, `quantity`, `is_additional_item`, `manually_added`, `claim_type`, `claim_subtype_name`, `details`, `resolution_requested`, `source_order_number`, `created_at`, `updated_at` | | `resolutions` | one row per resolution | `resolution_id`, `claim_id`, `order_id`, `store_id`, `account_id`, `resolution_type`, `paid_value`, `paid_currency`, `paid_original_value`, `credit_store`, `include_shipping`, `shipping_amount`, `claim_state`, `claim_category`, `is_ota`, `sales_channel`, `source_order_number`, `source_order_id`, `app_version`, `store_type`, `created_at` | | `resolutions_items` | one row per resolution line (per SKU) | `resolution_line_id`, `resolution_id`, `claim_item_id`, `claim_id`, `order_id`, `store_id`, `account_id`, `parent_account_id`, `source_order_id`, `source_variant_id`, `source_product_id`, `sku`, `item_name`, `product_image`, `claim_type`, `claim_subtype_name`, `claim_category`, `sales_channel`, `claim_filed_from`, `details`, `order_item_quantity`, `total_order_item_amount`, `submitted_quantity`, `submitted_resolution`, `total_item_submitted_resolution_amount`, `actual_resolution`, `actual_resolution_quantity`, `total_item_actual_resolution_amount`, `claim_added_item`, `resolution_qty_less_than_submitted_qty`, `submitted_qty_less_than_order_qty`, `reship_order_number`, `created_at`, `claim_date`, `resolution_date`, `order_date` | | `addresses` | one row per order (deduped) | `order_id`, `claim_id`, `customer_id`, `store_id`, `account_id`, `city`, `state`, `state_abr`, `zip_code`, `country`, `country_abr`, `latitude`, `longitude`, `address_type`, `order_date`, `claim_date` | > [!NOTE] > > **`addresses` is geo-only.** Customer identity fields — name, email, phone, and street lines (`address1`/`address2`) — are excluded and cannot be requested. Coordinates are **rounded to \~1.1 km** (2 decimal places), so `latitude`/`longitude` support regional mapping but never pinpoint an individual address. Its time column is `order_date`. > [!NOTE] > > **Per-item dollars live on `resolutions_items`, not `claim_items`.** A single claim item can be split across multiple resolutions with different types (e.g. partial refund + partial reship on the same SKU). That means one `claim_items` row can map to N `resolutions_items` rows — join them on `claim_item_id` to get every payout tied to its item: > > ``` > claim_items ⟶ resolutions_items (via claim_item_id, one-to-many) > ``` > > `total_item_actual_resolution_amount` on `resolutions_items` is the paid amount for that specific line; `shipping_amount` on `resolutions` is a separate line and is **not** included in `paid_value`. ## Metrics Metrics are pre-defined aggregations computed at query time over the batch-refreshed tables. Query them as a time series or fetch the latest single value. ### List metrics ``` GET /v1/analytics/metrics ``` ```json theme={null} { "data": [ { "key": "order_attach_rate", "description": "Share of orders that carry an Order Protection policy.", "granularitySupport": ["day", "week", "month", "quarter", "year"] } ], "meta": { "data_freshness_at": "2026-07-08T06:00:00.000Z" } } ``` ### Time series ``` GET /v1/analytics/metrics/{key}/timeseries ``` | Parameter | Description | | - | - | | `store_ids` | Repeatable. Restrict to specific stores within your scope. | | `from` | Start of the window (ISO 8601). Defaults to 30 days ago. | | `to` | End of the window (ISO 8601). Defaults to now. Windows are capped at 366 days. | | `granularity` | Bucket size: `day`, `week`, `month`, `quarter`, or `year`. | | `group_by` | Set to `store_id` to return one series per store instead of an aggregate. | ```json theme={null} { "data": [ { "bucket": "2026-05-01T00:00:00.000Z", "value": 0.3712 }, { "bucket": "2026-06-01T00:00:00.000Z", "value": 0.3302 } ], "meta": { "data_freshness_at": "2026-07-08T06:00:00.000Z", "store_ids": ["store_abc123"], "granularity": "month" } } ``` When `group_by=store_id`, each data point also includes a `store_id` field. ### Latest value ``` GET /v1/analytics/metrics/{key} ``` Returns the single most recent value for the metric. ```json theme={null} { "data": { "key": "order_attach_rate", "value": 0.3302 }, "meta": { "data_freshness_at": "2026-07-08T06:00:00.000Z", "store_ids": ["store_abc123"], "from": "2026-06-08T00:00:00.000Z", "to": "2026-07-08T00:00:00.000Z" } } ``` #### Available metrics | Metric | Description | | - | - | | `order_attach_rate` | Share of orders that carry an Order Protection policy. | | `protected_order_count` | Count of protected orders (distinct policies). | | `claim_count` | Count of claims filed. | | `claim_rate` | Claims per protected order, bucketed by granularity. | ## Limits | Limit | Value | | - | - | | Default time window | 30 days | | Maximum metric window | 366 days | | Default table page size | 1000 rows | | Maximum table page size | 10000 rows | > [!TIP] > > For pulls larger than these limits, page through tables with the `cursor` parameter, or narrow your `from`/`to` window and combine the results. # API Reference Source: https://docs.orderprotection.com/developer/api-reference OAuth endpoints and how to use your access tokens with the OrderProtection API. ## Base URL ``` https://api.production.orderprotection.com ``` ## OAuth endpoints These endpoints handle authentication and token management for your app. ### User login ``` POST /v1/auth/login ``` Authenticates a dashboard user (`{"email", "password"}`) and returns `{"data": {"access_token", "refresh_token", "expires_in", ...}}`. The `access_token` is the dashboard user JWT required by the install endpoints below — app access tokens and personal access tokens are rejected there. Refresh with `POST /v1/auth/refresh` `{"refreshToken"}`. See [Installing Your App](/developer/installing-your-app#step-1-obtain-a-user-token). ### Install an app (authorize/approve) ``` POST /v1/oauth/authorize/approve ``` Creates an installation on a store and returns a single-use authorization code. Requires a dashboard user JWT for a user with access to the store. | Parameter | Type | Description | | - | - | - | | `clientId` | string | Your app's client ID | | `redirectUri` | string | Must exactly match a registered redirect URI | | `scopes` | string\[] | Must include every required scope; must not exceed the app's declared scopes | | `storeId` | string | Target store | | `state` | string | Optional; echoed into the returned redirect URL | | `codeChallenge` / `codeChallengeMethod` | string | Optional PKCE (S256 only) | **Response:** `{"data": {"code": "...", "redirectUri": "https://...?code=..."}}`. Full walkthrough and error table: [Installing Your App](/developer/installing-your-app#path-b-api-install). To preview an app's consent payload first: `POST /v1/oauth/authorize` with `{"clientId", "redirectUri"}` (same auth). ### Exchange tokens ``` POST /v1/oauth/token ``` Exchange an authorization code, refresh token, or client credentials for access tokens. See [Authentication](/developer/authentication) for detailed examples. | Parameter | Type | Description | | - | - | - | | `grant_type` | string | `authorization_code`, `refresh_token`, or `client_credentials` | | `client_id` | string | Your app's client ID | | `client_secret` | string | Your app's client secret | | `code` | string | Authorization code (for `authorization_code` grant) | | `redirect_uri` | string | Must match the URI used during authorization | | `code_verifier` | string | PKCE verifier (if code challenge was used) | | `refresh_token` | string | Refresh token (for `refresh_token` grant) | | `store_id` | string | Target store (for `client_credentials` grant) | | `scopes` | string\[] | Scope filter (for `client_credentials` grant) | **Response:** ```json theme={null} { "access_token": "op_at_...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "op_rt_...", "scope": "order:read claim:read" } ``` *** ### Revoke a token ``` POST /v1/oauth/revoke ``` Revoke an access or refresh token. | Parameter | Type | Required | Description | | - | - | - | - | | `token` | string | Yes | The token to revoke | | `client_id` | string | Yes | Your app's client ID | | `client_secret` | string | Yes | Your app's client secret | | `token_type_hint` | string | No | `access_token` or `refresh_token` | **Response:** `200 OK` on success. *** ### Verify session token ``` POST /v1/oauth/session/verify ``` Verify an embedded app session token and retrieve user context. See [Embedded Apps](/developer/embedded-apps) for details. | Parameter | Type | Required | Description | | - | - | - | - | | `session_token` | string | Yes | The JWT session token from the iframe URL | **Response:** ```json theme={null} { "userId": "user_abc123", "email": "merchant@example.com", "firstName": "Jane", "lastName": "Smith", "storeId": "store_xyz789", "installationId": "inst_def456", "applicationId": "app_ghi012", "clientId": "op_app_...", "scopes": ["order:read", "claim:read"] } ``` > [!NOTE] > > This endpoint is rate-limited to 30 requests per minute per IP address. *** ## Using access tokens Once you have an access token, include it in the `Authorization` header of every API request: ```bash theme={null} curl -X GET https://api.production.orderprotection.com/v1/orders \ -H "Authorization: Bearer op_at_af444635983c457a5e..." ``` Your access token is scoped to the store that installed your app and the permissions the merchant granted. You can use it to call any OrderProtection API endpoint that falls within your granted scopes. ### Available APIs With a valid access token, you can access these OrderProtection APIs: > **[Orders](/api-reference/orders/get-all-orders)** > > Read and manage orders. Requires `order:read` or `order:update` scope. > **[Claims](/api-reference/claims/get-claims)** > > Read and manage claims. Requires `claim:read`, `claim:update`, or `claim:manage` scope. > **[Products](/api-reference/products/get-product)** > > Read and manage products. Requires `product:read` or `product:update` scope. > **[Fulfillments](/api-reference/fulfillments/get-fulfillments-for-order)** > > Read and manage fulfillments. Requires `order:read` scope. > **[Partner API (v2)](/developer/endpoints)** > > Manage settings, pricing rules, quotes, widgets, and A/B-test contexts via OAuth. Partner-only endpoints under `/v2`. ## Error responses When a request fails, the API returns a JSON error response: ```json theme={null} { "statusCode": 403, "message": "Insufficient scope: read_analytics required", "error": "Forbidden" } ``` ### Common error codes | Code | Description | | - | - | | `400` | Bad request — check your request body or parameters | | `401` | Unauthorized — your token is invalid, expired, or revoked | | `403` | Forbidden — your token does not have the required scope | | `404` | Not found — the resource does not exist or is not accessible | | `429` | Too many requests — you have exceeded the rate limit | > [!TIP] > > If you receive a `401` response, try refreshing your access token. If that also fails, the merchant may have uninstalled your app. # Authentication Source: https://docs.orderprotection.com/developer/authentication OAuth 2.0 authentication flows for accessing the OrderProtection API. All API access is authenticated using OAuth 2.0. Your app receives access tokens that are scoped to the specific permissions each merchant granted during installation. **Base URL:** ``` https://api.production.orderprotection.com ``` ## Authorization Code Flow This is the primary flow for apps installed by merchants. When a merchant installs your app from the marketplace, OrderProtection delivers an authorization code to your redirect URI. You exchange this code for access and refresh tokens. ### 1. Merchant installs your app When a merchant clicks **Install** on your app, they review and approve the requested scopes. OrderProtection then delivers an authorization code to your first registered redirect URI as a server-to-server `GET` (your endpoint must respond `2xx` within 10 seconds or the install rolls back): ``` GET https://yourapp.example.com/callback?code=a1b2c3d4e5f6&store_id= ``` > [!NOTE] > > Consent happens inside the OrderProtection dashboard (or via the [install API](/developer/installing-your-app#path-b-api-install), where the code comes back in the response body instead) — there is **no hosted `/oauth/authorize` web page** to redirect merchants to. Don't construct an authorize URL by convention from other OAuth providers; the code is delivered from the install/approve step. Full install reference: [Installing Your App](/developer/installing-your-app). | Parameter | Description | | - | - | | `code` | The authorization code to exchange for tokens | | `state` | The state parameter you provided (if any), for CSRF protection | ### 2. Exchange code for tokens Exchange the authorization code for an access token and refresh token: ```bash cURL theme={null} curl -X POST https://api.production.orderprotection.com/v1/oauth/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "authorization_code", "client_id": "op_app_fc6767b5694ba053...", "client_secret": "op_secret_8915e130...", "code": "a1b2c3d4e5f6", "redirect_uri": "https://yourapp.example.com/callback" }' ``` ```javascript Node.js theme={null} const response = await fetch( "https://api.production.orderprotection.com/v1/oauth/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ grant_type: "authorization_code", client_id: "op_app_fc6767b5694ba053...", client_secret: "op_secret_8915e130...", code: "a1b2c3d4e5f6", redirect_uri: "https://yourapp.example.com/callback", }), } ); const tokens = await response.json(); ``` ### Token response ```json theme={null} { "access_token": "op_at_af444635983c457a5e...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "op_rt_27f3894986c211168b...", "scope": "order:read claim:read store:read" } ``` | Field | Description | | - | - | | `access_token` | Bearer token for API calls. Prefixed with `op_at_`. | | `token_type` | Always `Bearer`. | | `expires_in` | Token lifetime in seconds (3600 = 1 hour). | | `refresh_token` | Long-lived token to obtain new access tokens. Prefixed with `op_rt_`. | | `scope` | Space-separated list of granted scopes. | ### PKCE support The authorization code flow supports PKCE (Proof Key for Code Exchange) with the S256 method for enhanced security. If a `code_challenge` was provided during authorization, you must include the `code_verifier` when exchanging the code: ```json theme={null} { "grant_type": "authorization_code", "client_id": "op_app_...", "client_secret": "op_secret_...", "code": "a1b2c3d4e5f6", "redirect_uri": "https://yourapp.example.com/callback", "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" } ``` ## Client Credentials Flow Use this flow for server-to-server access when no user interaction is needed. This is useful for background jobs, data sync, or admin operations. > [!NOTE] > > The client credentials flow requires an **existing installation** on the target store. A merchant must have already installed your app (granting scopes) before you can use this flow. The `store_id` parameter tells OrderProtection which installation to use for determining your granted scopes. ```bash cURL theme={null} curl -X POST https://api.production.orderprotection.com/v1/oauth/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "client_credentials", "client_id": "op_app_fc6767b5694ba053...", "client_secret": "op_secret_8915e130...", "store_id": "store_abc123", "scopes": ["order:read", "claim:read"] }' ``` ```javascript Node.js theme={null} const response = await fetch( "https://api.production.orderprotection.com/v1/oauth/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ grant_type: "client_credentials", client_id: "op_app_fc6767b5694ba053...", client_secret: "op_secret_8915e130...", store_id: "store_abc123", scopes: ["order:read", "claim:read"], }), } ); const tokens = await response.json(); ``` > [!NOTE] > > The `scopes` parameter is optional and acts as a filter. If omitted, the token will include all scopes granted by the merchant during installation. ## Refreshing tokens Access tokens expire after 1 hour. Use the refresh token to obtain a new access token without requiring the merchant to re-authorize: ```bash theme={null} curl -X POST https://api.production.orderprotection.com/v1/oauth/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "refresh_token", "client_id": "op_app_fc6767b5694ba053...", "client_secret": "op_secret_8915e130...", "refresh_token": "op_rt_27f3894986c211168b..." }' ``` The response includes a new access token and a new refresh token. Always store and use the latest refresh token — previous ones are rotated. ## Revoking tokens When a merchant disconnects your app or you need to invalidate tokens, revoke them explicitly: ```bash theme={null} curl -X POST https://api.production.orderprotection.com/v1/oauth/revoke \ -H "Content-Type: application/json" \ -d '{ "token": "op_at_af444635983c457a5e...", "client_id": "op_app_fc6767b5694ba053...", "client_secret": "op_secret_8915e130...", "token_type_hint": "access_token" }' ``` | Parameter | Required | Description | | - | - | - | | `token` | Yes | The token to revoke | | `client_id` | Yes | Your app's client ID | | `client_secret` | Yes | Your app's client secret | | `token_type_hint` | No | Either `access_token` or `refresh_token` | ## Using access tokens Include the access token in the `Authorization` header of every API request: ```bash theme={null} curl -X GET https://api.production.orderprotection.com/v1/orders \ -H "Authorization: Bearer op_at_af444635983c457a5e..." ``` > [!WARNING] > > Access tokens are scoped to the permissions the merchant granted. If you attempt to access an endpoint that requires a scope the merchant did not grant, you will receive a `403 Forbidden` response. ## Token prefixes OrderProtection tokens use prefixes for easy identification: | Prefix | Type | | - | - | | `op_at_` | Access token | | `op_rt_` | Refresh token | | `op_app_` | Client ID | | `op_secret_` | Client secret | # Checkout Extension Source: https://docs.orderprotection.com/developer/checkout-extension Install OrderProtection's Shopify checkout UI extension and point each checkout at a partner A/B cohort. This page is for **partners who render OrderProtection inside Shopify checkout** through the `checkout-widget` UI extension and want each checkout to resolve a specific A/B cohort. It builds on the [Partner Integration Quickstart](/developer/partner-integration-quickstart) — register your OAuth app and create your variants there first, then use this page to wire the extension to them. > [!NOTE] > > The checkout extension calls the **path-based partner endpoints** (`/v2/.../partner/:applicationId`), not the header-based [public read with cohort headers](/developer/endpoints#public-widget-read-with-cohort). The three block settings below are what bind a checkout to your cohort. ## Prerequisites * An **approved OAuth app** — see [Creating an app](/developer/creating-an-app). Note your `Application.id` (looks like `cmpn5in6p000484flmfk9ns4d`). * A **partner context** created for the merchant's store — see [Quickstart, Step 3](/developer/partner-integration-quickstart#step-3-create-your-partner-context). * A **price set** ([Step 4](/developer/partner-integration-quickstart#step-4-create-a-price-set-per-cohort)) and a **widget config** ([Step 5](/developer/partner-integration-quickstart#step-5-create-a-widget-config-per-cohort)) created for each cohort, keyed by your `variantKey`. * The `checkout-widget` extension **installed on the store** — see below. ## How the extension gets installed The OrderProtection Shopify app is **not listed in the Shopify App Store**. It's distributed as a **custom app per store**: OrderProtection creates the app in its Shopify Partners account, deploys the extensions to it, and generates a custom-distribution install link scoped to that store (or, for Shopify Plus, that organization's stores). After install, the `checkout-widget` app block is added to the checkout in the Shopify checkout editor, which is where the block settings below live. For merchant stores this is part of OrderProtection onboarding. For **partner development stores**, contact your OrderProtection engineering contact to have the app provisioned and the install link sent over — there is no self-serve install path. ## Configure the block settings When the `checkout-widget` extension is added to a store's checkout, configure three fields under **checkout-widget → Block settings**. A partner (e.g. PDQ) sets these at install time. ![Shopify checkout editor showing the checkout-widget Block settings: Application ID, Price Set Variant Key, and Widget Config Variant Key, with the OrderProtection — Cohort A widget rendering in the checkout preview at \$9.80.](https://mintcdn.com/orderprotectioncom/70Pwd3NQ5_STOrgU/images/developer/checkout-extension-block-settings.png?fit=max\&auto=format\&n=70Pwd3NQ5_STOrgU\&q=85\&s=540a2c75cd146ed116d8da752ccbce8e) | Setting | Example | What it does | | - | - | - | | **Application ID** | `cmpn5in6p000484flmfk9ns4d` | Your OAuth `Application.id`. Used as the path segment on the partner-scoped endpoints. Set it together with **both** variant keys (static mode) or with **both empty** (runtime mode) — see the mode table below. | | **Price Set Variant Key** | `test-a` | Routes pricing to `GET /v2/quote/insurance/partner/:applicationId?key=:variantKey` for partner-scoped pricing. | | **Widget Config Variant Key** | `test-a` | Routes the widget config fetch to `GET /v2/widget/config/partner/:applicationId?key=:variantKey` instead of the default per-store endpoint. | The block settings state selects one of three modes: | Block settings | Mode | | - | - | | No Application ID | Merchant checkout — the extension uses the store's default widget and pricing; the fields below and the runtime attributes are ignored. | | Application ID + variant keys filled | **Static partner mode** — the checkout is pinned to that cohort. The two keys are independent, so you can pin pricing and appearance separately. | | Application ID + variant keys **empty** | **Runtime mode** — the cohort is supplied per session via cart attributes, and the widget renders nothing until it arrives. See [Runtime cohort binding](#runtime-cohort-binding-cart-attributes). | ## Runtime cohort binding (cart attributes) Static block settings pin every session on a checkout to one cohort. Partners whose experimentation assigns cohorts **during the session** (for example, after the buyer enters their email and address) bind at runtime instead, using two cart attributes: | Attribute | Value | | - | - | | `_op_price_variant` | The `variantKey` of the price set to apply | | `_op_widget_variant` | The `variantKey` of the widget config to apply | Values are the same partner-chosen cohort strings used when creating price sets and widget configs through the API (`^[a-zA-Z0-9_.:-]{1,64}$`) — not ids OrderProtection generates, and not Shopify product variant ids. Your extension writes them with Shopify's [Attributes API](https://shopify.dev/docs/api/checkout-ui-extensions/latest/target-apis/checkout-apis/attributes-api) (`applyAttributeChange`, `type: "updateAttribute"`). Cart attributes are shared checkout state across apps, which is what makes them the cross-extension channel. ### Session lifecycle 1. **Setup, once per store**: the `checkout-widget` block is added with Application ID set and both variant-key fields empty. One `checkout-widget` block — no per-variant blocks, and no checkout-editor changes per test. 2. **Per test, API only**: create a price set and a `CHECKOUT` widget config per `variantKey`. A control arm is a `variantKey` whose price set has `noOp: true`. 3. **Per session**: the widget renders nothing while it waits, and makes no cohort pricing or widget-config requests for a surface until that surface's key exists. When your extension allocates, it writes **both** attributes — the widget stays hidden until both exist. 4. The widget fetches that cohort's pricing and widget config from the [partner endpoints below](#what-the-extension-fetches), renders, and applies the cohort's auto-add behavior. A `noOp` cohort renders nothing and removes any protection line. 5. **Re-allocation** mid-session is supported — the widget refetches and, on toggle-layout cohorts, swaps the protection line (tile-layout cohorts keep the existing line until the buyer interacts) — but it never re-runs the auto-add decision (a buyer's explicit choice is not overridden). Don't clear the attributes after allocating, and never express the control arm by *not* writing them: always allocate explicitly, so "not allocated yet" and "control" stay distinguishable. 6. Cart attributes become note attributes on the resulting Shopify order (standard Shopify behavior), so the cohort keys are available in order payloads and webhooks for your per-order test attribution. ### Rules and edge cases * **Write both attributes at allocation time.** One without the other keeps the widget hidden. * **Don't half-fill the block settings.** Application ID with only one variant-key field filled leaves the other surface waiting for an attribute that may never come, so the widget stays hidden. Fill both fields (static mode) or neither (runtime mode). * **Invalid values are treated as absent** (client-side validation against the key pattern), falling back to the block-setting value if one exists, otherwise back to the hold. * **Attributes override filled block settings** when both are present. But leave the fields empty on runtime checkouts: a filled field pins a cohort that renders immediately on page load and then swaps when the allocation lands — the hold only engages when the fields are empty. Filled fields are useful for debugging a cohort statically, not for live tests. * **Missing cohort data falls back visibly, per surface**: a key with a widget config but no `SHIPPING` price set renders the cohort's appearance with the store's **merchant fallback pricing** (the pricing fetch 404s); a key with a price set but no `CHECKOUT` widget config renders the **merchant's appearance** with cohort pricing. If either half looks wrong during setup, check both resources exist for that exact `variantKey`. * **Wallet checkouts (Apple Pay, Google Pay)** reject extension cart changes — attribute writes and protection line-adds alike — so protection can't be sold in those sessions by any binding mode; in runtime mode they simply stay unallocated and hidden. **Shop Pay is expected to work** — it's the full checkout surface, and buyer details arriving prefilled means allocation can fire immediately — but it hasn't been verified end-to-end yet. * **Unallocated sessions stay hidden indefinitely** by design. The partner owns allocation reliability; there is no timeout fallback to a default widget. ### Impression signal (write-back) On runtime-allocated sessions, the widget reports back through two more cart attributes so your extension can verify — in-session — that the impression actually landed: | Attribute | Written when | | - | - | | `_op_rendered` = `"true"` | Once per session, at the moment the widget first renders the allocated cohort. | | `_op_not_rendered_reason` | Only when the widget is running but **definitively declines** to render after your allocation. Retracted when the widget subsequently renders. | Reason values: `no_op` (the cohort is a noOp control arm — expected behavior), `out_of_range` (cart subtotal outside the cohort's price rules), `country_excluded` (destination or geo exclusion), `not_eligible` (pickup, B2B, hidden shipping method, nothing shippable), `error` (the pricing fetch failed). Read it as a tri-state after writing your allocation attributes: * **`_op_rendered` present** — the impression happened. Treat this as authoritative even if a stale reason briefly coexists (the retraction is best-effort). * **Reason present, no `_op_rendered`** — the widget ran and declined; the value says why. `no_op` is your control arm working correctly, not a failure. * **Neither appears** — the widget never ran: missing block, misconfigured checkout, broken extension, or a wallet flow. This is the setup-problem signal, and it works precisely *because* it's an absence — a missing renderer can't self-report. Two guarantees behind the signal: reasons are only emitted for **definitive** decisions (a country or subtotal that simply hasn't resolved yet never produces a false decline), and neither attribute is ever written on merchant checkouts or statically pinned cohorts — they exist only when both cohort keys arrived via runtime attributes. Like the allocation attributes, they persist onto the order. > [!NOTE] > > **Channel longevity**: `applyAttributeChange` is deprecated in Shopify's 2026+ checkout API versions in favor of cart metafields (it remains fully supported on the API versions the extensions currently pin). When pinned versions sunset, this channel migrates to a shared cart metafield with the same contract — coordinate the swap with OrderProtection before bumping your extension's `api_version`. ## What the extension fetches Once configured, on each checkout render the extension calls the partner-scoped endpoints below. Both are **public** (no OAuth token) and resolve the cohort from the path `applicationId` + `key` query param. ### Pricing — `GET /v2/quote/insurance/partner/:applicationId` | Param | In | Required | Description | | - | - | - | - | | `applicationId` | path | Yes | Your OAuth `Application.id`. | | `key` | query | Yes | The **Price Set Variant Key** (`variantKey`). Must match the partner key format. | | `store_url` | query | Yes | The merchant's store domain, e.g. `example.myshopify.com`. | | `country` | query | No | ISO 2-letter country code. Defaults to `US`. | ```bash theme={null} curl -G https://api.production.orderprotection.com/v2/quote/insurance/partner/cmpn5in6p000484flmfk9ns4d \ --data-urlencode "key=test-a" \ --data-urlencode "store_url=example.myshopify.com" \ --data-urlencode "country=US" ``` The response is the same shaped quote payload as the [public widget read](/developer/endpoints#public-widget-read-with-cohort), computed from the cohort's `SHIPPING` price set. Responses are cached for \~1 hour per `(store_url, country, applicationId, key)` (plus the A/B session token when one is present). **Errors** * `400 Bad Request` — `key` is missing, or `applicationId`/`key` don't match the partner key format. * `404 Not Found` — the store isn't found, the app isn't installed, or the cohort has no `SHIPPING` pricing rules. ### Widget config — `GET /v2/widget/config/partner/:applicationId` | Param | In | Required | Description | | - | - | - | - | | `applicationId` | path | Yes | Your OAuth `Application.id`. | | `key` | query | Yes | The **Widget Config Variant Key** (`variantKey`). Must match the partner key format. | | `store_url` | query | Yes | The merchant's store domain. | | `type` | query | No | Widget type: `CART`, `CHECKOUT`, `INFO_MODAL`, or `SUBSCRIPTION`. Defaults to `CHECKOUT`. | ```bash theme={null} curl -G https://api.production.orderprotection.com/v2/widget/config/partner/cmpn5in6p000484flmfk9ns4d \ --data-urlencode "key=test-a" \ --data-urlencode "store_url=example.myshopify.com" \ --data-urlencode "type=CHECKOUT" ``` ```json theme={null} { "id": "cmokr9v3t000284gkq2m8xw1e", "type": "CHECKOUT", "status": "ACTIVE", "variant": "test-a", "name": "Cohort A — flat-rate", "config": { "...": "schemaless widget configuration — the renderer validates on read" }, "customizationValues": { "...": "read-only mirror of config, for legacy consumers" }, "updatedAt": "2026-05-26T18:46:25.987Z" } ``` `config` and `customizationValues` always hold the same value; `customizationValues` is the legacy column name. Responses are cached for \~1 hour per `(store_url, applicationId, key, type)`. **Errors** * `400 Bad Request` — `key` is missing, or `applicationId`/`key` don't match the partner key format. * `404 Not Found` — the store isn't found, the app has no active context on that store, or no widget config exists for that `(variantKey, type)`. > [!WARNING] > > These endpoints **throw** `400`/`404` rather than silently falling back. Treat any non-`200` as "no partner cohort for this checkout" and render the store's default widget — a partner cohort must never break checkout. ## Default vs. cohort render The explainer below walks the whole flow — authenticate, create variants, configure the extension, and render per shopper: