# Signed cart items

> Add a custom-priced item to the Shoprocket cart from your own page, such as a product configurator: sign it on your server with HMAC-SHA256, then call Shoprocket.cart.add({ signed }).

Add a custom-priced item to the cart from a page you built, such as a product configurator. Your server works out the price and signs the item; the page adds it with one call; checkout, emails and the invoice treat it like any other product.

## What it is for

A page that prices a product from the customer's choices (sizes, materials, a calculator, a 3D configurator) cannot send that price to the cart itself: anyone could edit it in their browser. Instead, your server signs the whole item with HMAC-SHA256 and a secret only it knows. Shoprocket verifies the signature when the item is added and again when the order is placed, and refuses it if a single character changed.

The signed item names one real product in your store. The cart line takes that product's tax band, delivery options and stock rules, and the price, name, details, weight and picture you signed. Without a picture of its own, the line shows the product's.

## Signing key

Create one in the dashboard under **Settings › API keys › Signing keys** (part of the Developer tools app). You get a **Key ID** (`sgk_...`, not secret, it goes in every token) and a **Secret** (`srsig_...`, shown once; keep it on your server). A signing key can only make cart lines: it cannot read or change anything in your store.

**Replace key** creates a new key and gives every older one 7 more days, so your pages keep working while you deploy the new secret. **Revoke** stops a key at once, at the add and at checkout.

## The item

A JSON object. Unknown fields are refused, so a typo cannot be silently ignored.

| Field | Type | Description |
| --- | --- | --- |
| `store`required | string | Your publishable key (pk\_...). An item signed for one store is refused by every other. |
| `product`required | string | A product id (prod\_...) in the store. It may be set to Enquire, so it cannot be bought on its own at a catalogue price. |
| `variant` | string | A variant id (var\_...) of that product. Omit for its first variant. |
| `price`required | integer | Price per unit in minor units (cents for USD). |
| `currency`required | string | Must be the store's own currency. A shopper paying in another currency sees it converted like any line. |
| `name` | string | Line name, up to 200 characters. Omit for the product's name. |
| `details` | array | Up to 30 { label, value } pairs, shown under the line in the cart, the order, emails and the invoice. |
| `weightGrams` | integer | Weight of one unit in grams, used by weight-based shipping rates. Omit for the variant's weight. |
| `sku` | string | SKU for this configuration. Omit for the variant's SKU. |
| `image` | string | A picture of this configuration on your own server: an absolute https:// URL, up to 2048 characters. We copy it when the order is placed. To send the shopper's own design instead, see A picture of the item below. Omit for the variant's or product's picture. |
| `expires`required | integer | Unix time in seconds the price holds until. After it the item can no longer be added, and a cart holding it can no longer be checked out. At most 30 days ahead. |
| `nonce` | string | Any string, to make two otherwise identical items two separate lines. |

## Signing it

The token is four parts joined by dots:

Code

```
v1.<keyId>.<payload>.<signature>
```

`payload` is the item's JSON, base64url-encoded without padding. `signature` is HMAC-SHA256, keyed with the secret as text, over the exact string `v1.<keyId>.<payload>`, also base64url without padding. Sign on your server, at the moment the customer clicks, never in the page.

Cloudflare Workers (WebCrypto)

```
// Cloudflare Workers without node:crypto: WebCrypto.
const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

async function signItem(keyId, secret, item) {
  const enc = new TextEncoder();
  const head = `v1.${keyId}.${b64url(enc.encode(JSON.stringify(item)))}`;
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(head)));
  return `${head}.${b64url(sig)}`;
}
```

PHP

```
<?php
function b64url(string $s): string { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); }

function sign_item(string $keyId, string $secret, array $item): string {
  $head = 'v1.' . $keyId . '.' . b64url(json_encode($item, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
  return $head . '.' . b64url(hash_hmac('sha256', $head, $secret, true));
}
```

Node

```
// Node 18+, Cloudflare Workers, Netlify or Vercel functions: no package needed.
import { createHmac } from "node:crypto";

const KEY_ID = process.env.SHOPROCKET_SIGNING_KEY_ID;   // sgk_...
const SECRET = process.env.SHOPROCKET_SIGNING_SECRET;   // srsig_...

export function signItem(item) {
  const payload = Buffer.from(JSON.stringify(item)).toString("base64url");
  const head = `v1.${KEY_ID}.${payload}`;
  const signature = createHmac("sha256", SECRET).update(head).digest("base64url");
  return `${head}.${signature}`;
}

// Work the price out HERE, on the server, from the customer's choices.
const signed = signItem({
  store: "pk_...",                     // your publishable key
  product: "prod_...",                 // the product this belongs to
  price: 456432,                       // per unit, minor units: $4,564.32
  currency: "USD",                     // your store's currency
  name: "Oak pergola 4.2 x 3.0 m",
  details: [
    { label: "Length", value: "4.2 m" },
    { label: "Width", value: "3.0 m" },
    { label: "Rafter profile", value: "Ogee" },
  ],
  weightGrams: 412000,
  expires: Math.floor(Date.now() / 1000) + 3600,
});
```

## Adding it to the cart

With the widget on the page, `Shoprocket.cart.add({ signed, quantity })` adds it the way the widget's own buttons do: the "Added to cart" card shows, analytics hear about it, and the promise resolves with the cart. A refusal rejects with an `Error` whose `reason` names why, and the `shoprocket:cart:error` event carries the same `reason`.

From your own front end, send it to the cart API instead:

Code

```
POST /v3/public/{pk}/cart/items
X-Cart-Token: <the cart's token>
Content-Type: application/json

{ "signed": "v1.sgk_....eyJzdG9yZSI6...", "quantity": 1 }
```

Send nothing else with it but `image` (below): `productId`, `variantId` and personalisation answers are refused next to `signed`.

Your page

```
<script>
  document.querySelector("#add").addEventListener("click", async () => {
    // Ask YOUR server to price and sign the customer's choices.
    const res = await fetch("/api/sign-pergola", { method: "POST", body: JSON.stringify(choices) });
    const signed = await res.text();
    try {
      await Shoprocket.cart.add({ signed, quantity: 1 });   // shows "Added to cart"
    } catch (err) {
      console.warn(err.reason, err.message);                // e.g. "signed_item_expired"
    }
  });
</script>
```

## A picture of the item

To show the customer's own design on the cart line, at checkout, on the order and in its emails, snapshot it in the page and upload it to the cart: `Shoprocket.cart.uploadFile(blob)` answers with a `token`, and `Shoprocket.cart.add({ signed, image: token })` puts it on the line. We keep a resized copy (400 pixels wide, never cropped) on our media host, so nothing on your side has to stay online.

- A JPEG, PNG, WebP or GIF, up to 10MB. A PDF or HEIC upload is refused as a picture.
- The token is not part of the signature. An upload only works on the cart that made it, so a shopper can only swap in their own picture; the price and details stay signed. Another cart's token, or one that no longer exists, is refused with a 422.
- A cart that is never checked out loses its picture with the cart. An order keeps it.
- When you send both, the uploaded picture wins over the signed `image` URL.

From your own front end, upload to the cart API, then add with the token:

Code

```
POST /v3/public/{pk}/cart/uploads?name=pergola.png
X-Cart-Token: <the cart's token>
Content-Type: image/png

<the PNG bytes>

-> 201 { "data": { "token": "0192f0...", "name": "pergola.png", "size": 48213, "contentType": "image/png" } }

POST /v3/public/{pk}/cart/items
X-Cart-Token: <the same cart's token>

{ "signed": "v1.sgk_....eyJzdG9yZSI6...", "image": "0192f0...", "quantity": 1 }
```

A picture already on your own server still works: sign its `https://` URL as the item's `image`. The cart shows it from your server, and when the order is placed we copy it, so the order, its emails and your dashboard stop depending on the file. A copy that fails (the file is gone, slow, over 10MB, not a picture, or on a private address) leaves your URL in place.

Your page

```
<script>
  document.querySelector("#add").addEventListener("click", async () => {
    // 1. Snapshot the configurator's canvas (WebGL: create it with preserveDrawingBuffer: true).
    const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
    // 2. Upload it to this shopper's cart. Private to your store until it is on a line.
    const { token } = await Shoprocket.cart.uploadFile(blob);
    // 3. Sign the item on your server as usual, then add it with the picture's token.
    const signed = await (await fetch("/api/sign-pergola", { method: "POST", body: JSON.stringify(choices) })).text();
    await Shoprocket.cart.add({ signed, image: token, quantity: 1 });
  });
</script>
```

## How a signed line behaves

- Its price never changes: not by the product's price or sale price, not by quantity price breaks. Discount codes and automatic discounts apply as to any line.
- The shopper can change its quantity. The same signed item added again adds quantity; a different item is a separate line (the line's identity includes a hash of the payload).
- `expires` is how long you hold the price, up to 30 days. It is checked when the item is added and again when the order is placed: a cart kept past it is refused with `signed_item_invalid` and `signedItem.reason` `signed_item_expired`, and the cart tells the shopper the price has expired on that line. A payment that has started is never cut off: an order placed before `expires` pays at the signed price however long the payment then takes, and a PayPal payment approved before it still completes. To hold a quote for 14 days, sign it with `expires` 14 days ahead.
- At checkout the signature is checked again too, and a line whose key was revoked since is refused with `signed_item_invalid`.
- The cart line carries `signedExpiresAt`, the hold's end, and the cart shows the shopper "Price held until" that date.
- Stock follows the product's own setting. A made-to-order product should allow selling when out of stock.
- Its `weightGrams` replaces the variant's weight for weight-based rates. Every other shipping rule is the product's.
- A signed `image` URL must be `https://`: an `http://`, `data:` or relative URL is refused with `signed_item_malformed`. It is copied when the order is placed (see [A picture of the item](#picture)).
- The cart line has `signed: true`, and its details arrive as `properties` with field ids `signed-1`, `signed-2` and so on.

Gift cards, bundles and subscriptions

A signed item cannot name a gift card, a bundle or a product sold only by subscription.

## Refusals

A refused add answers 422 with `code: "invalid"` and one of these in `reason`:

| reason | Why |
| --- | --- |
| `signed_item_malformed` | Not a v1.\<keyId>.\<payload>.\<signature> token, or the payload is not a valid item (a field missing, too long or the wrong type). |
| `signed_item_wrong_store` | The payload's store is another store's publishable key. |
| `signing_key_unknown` | No signing key with that id in this store. |
| `signing_key_revoked` | The key was revoked. |
| `signing_key_retired` | The key was replaced more than 7 days ago. |
| `signature_invalid` | The signature does not match: the item was edited, or signed with a different secret. |
| `signed_item_expired` | expires has passed. Sign it again. At checkout it arrives as signedItem.reason on a signed_item_invalid rejection. |
| `signed_item_expires_too_far` | expires is more than 30 days ahead. |
| `signed_item_currency` | currency is not the store's own currency. |
| `signed_item_unsupported` | The product is a gift card, a bundle, or sold only by subscription. |

Code

```
HTTP/1.1 422
{
  "error": {
    "code": "invalid",
    "reason": "signature_invalid",
    "message": "the signature does not match the item: it was changed, or signed with another secret"
  }
}
```

## Without a cart

When you would rather not use the cart at all, your server can create a draft order with a custom line using a secret API key, then send the customer its payment link (`POST /v3/stores/{storeId}/orders/{id}/payment-link`). That suits a quote agreed by email; signed items suit a page where the customer checks out straight away.

---

- HTML version: https://shoprocket.io/docs/signed-items
- Language: English (en)
