# Orders

List, create, update and cancel orders, change an order's shipping address or
email, and refund or cancel an order in Shopify. To ship an order, see
[Rates & Labels](rates-and-labels.md).

`GET` endpoints need the `read:orders` scope. `POST`, `PUT` and `DELETE`
endpoints need `write:orders`. See [Authentication](authentication.md).

Some keys carry the `deny:raw_fulfillment` permission. They can read orders and
use the address-change, email-change and refund endpoints, but [Create Order](#create-order)
and [Update Order](#update-order) return `403 FORBIDDEN`.

An order that belongs to another account returns `404 NOT_FOUND`, the same as an
order that does not exist.

### Order Status

| Status | Meaning |
|--------|---------|
| `pending` | Waiting to ship |
| `on_hold` | Held for review (for example fraud review or parts verification) |
| `processing` | A label purchase or dropship request is in progress |
| `partially_shipped` | Some items have a label |
| `shipped` | Every item has a label |
| `fulfilled` | Fulfilled outside ShipWave, as reported by the sales channel |
| `cancellation_pending` | The sales channel has an open cancellation request |
| `cancelled` | Cancelled |
| `refunded` | Refunded in full |
| `return_pending` | The sales channel has an open return |

ShipWave sets the status as labels are bought and voided. You can set some
statuses yourself with [Update Order](#update-order).

---

## List Orders

```
GET /api/v1/orders
```

Returns a paginated list of orders for your account, newest order date first.

### Query Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `page` | integer | `1` | Page number |
| `limit` | integer | `50` | Items per page (max 100) |
| `status` | string | — | Filter by one [status](#order-status), or `all` |
| `storeId` | string | — | Filter by store ID. See [Stores](stores.md) |
| `warehouseId` | string | — | Filter by warehouse ID |
| `search` | string | — | Search by order number, customer name, or email |
| `dateFrom` | string | — | Orders dated on or after this time (ISO 8601) |
| `dateTo` | string | — | Orders dated on or before this time (ISO 8601) |

A date without a time (`2026-02-18`) covers that whole UTC day, so
`dateFrom=2026-02-18&dateTo=2026-02-18` returns every order dated February 18
(UTC).

### Example

```bash
curl "https://shipwave.app/api/v1/orders?status=pending&limit=10" \
  -H "Authorization: Bearer sw_live_abc123..."
```

```typescript
const res = await fetch(
  "https://shipwave.app/api/v1/orders?status=pending&limit=10",
  { headers: { Authorization: "Bearer sw_live_abc123..." } }
);
const { data, meta } = await res.json();
```

### Response

```json
{
  "data": [
    {
      "id": "clx1abc2d3efg",
      "storeId": "clw9store1",
      "warehouseId": "clw9wh1",
      "externalId": "shopify_12345",
      "orderNumber": "1042",
      "status": "pending",
      "customerName": "Jane Smith",
      "customerEmail": "jane@example.com",
      "shippingAddress": {
        "name": "Jane Smith",
        "street1": "123 Main St",
        "street2": "Apt 4B",
        "city": "Austin",
        "state": "TX",
        "zip": "78701",
        "country": "US"
      },
      "totalWeight": 32.5,
      "weightOverrideOz": null,
      "lengthOverride": null,
      "widthOverride": null,
      "heightOverride": null,
      "totalValue": 149.99,
      "requestedService": null,
      "tags": ["priority"],
      "notes": null,
      "orderDate": "2026-02-18T14:30:00.000Z",
      "shipByDate": "2026-02-20T00:00:00.000Z",
      "createdAt": "2026-02-18T14:30:00.000Z",
      "updatedAt": "2026-02-18T14:30:00.000Z",
      "store": {
        "id": "clw9store1",
        "shopDomain": "myshop.myshopify.com",
        "platform": "shopify"
      },
      "warehouse": {
        "id": "clw9wh1",
        "name": "Main Warehouse"
      },
      "lineItems": [
        {
          "id": "clx1item1",
          "sku": "WIDGET-001",
          "name": "Blue Widget",
          "quantity": 2,
          "weight": 16.0,
          "price": 49.99,
          "imageUrl": "https://cdn.shopify.com/s/files/1/image.jpg"
        }
      ],
      "shipments": [
        {
          "shipmentId": "clx2ship1",
          "lineItemIds": ["clx1item1"],
          "shipment": {
            "id": "clx2ship1",
            "trackingCode": "9400111899223100012345",
            "status": "purchased",
            "carrierCode": "usps",
            "labelUrl": "https://easypost-files.s3.amazonaws.com/label.png",
            "trackingStatus": "in_transit",
            "voidedAt": null,
            "createdAt": "2026-02-18T16:00:00.000Z",
            "selectedRate": {
              "carrier": "USPS",
              "service": "Priority",
              "rate": "12.50",
              "currency": "USD",
              "deliveryDays": 2,
              "deliveryDate": null,
              "deliveryGuaranteed": false
            }
          }
        }
      ]
    }
  ],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 47,
    "totalPages": 5
  }
}
```

Each `shipments` entry is a label summary. `lineItemIds` lists the line items
in that package. Fetch [`GET /api/v1/shipments/:id`](/docs/api/shipments#get-shipment)
for the full label, addresses and parcel.

---

## Create Order

```
POST /api/v1/orders
```

Creates an order. Requires `write:orders`.

### Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `storeId` | string | see note | The store this order belongs to. See [Stores](stores.md) |
| `orderNumber` | string | yes | Display order number (e.g. "1042") |
| `customerName` | string | yes | Customer's full name |
| `shippingAddress` | object | yes | Shipping address (see below) |
| `customerEmail` | string | no | Customer's email address |
| `lineItems` | array | no | Order line items (see below) |
| `orderDate` | string | no | ISO 8601 date (defaults to now) |
| `notes` | string | no | Internal notes |
| `tags` | string[] | no | Tags for filtering |
| `warehouseId` | string | no | Warehouse to ship from |
| `totalWeight` | number | no | Total weight in ounces |
| `totalValue` | number | no | Total order value |
| `weightOverrideOz` | number | no | Override weight (oz) for rate calculation |
| `lengthOverride` | number | no | Override length (inches) |
| `widthOverride` | number | no | Override width (inches) |
| `heightOverride` | number | no | Override height (inches) |
| `externalId` | string | no | Your unique ID for this order (see [Idempotency](#idempotency)) |

`storeId` can be left out when your account has exactly one active store; that
store is used. With no active store, or more than one, leaving it out returns
`400 VALIDATION_ERROR`. List your stores with
[`GET /api/v1/stores`](stores.md).

**Shipping Address Object:**

| Field | Type | Required |
|-------|------|----------|
| `name` | string | no |
| `company` | string | no |
| `street1` | string | no |
| `street2` | string | no |
| `city` | string | no |
| `state` | string | no |
| `zip` | string | no |
| `country` | string | no (defaults to `US`) |
| `phone` | string | no |
| `email` | string | no |

`shippingAddress` must be present. Its fields are checked when you request
rates or buy a label.

**Line Item Object:**

| Field | Type | Required |
|-------|------|----------|
| `name` | string | yes |
| `sku` | string | no |
| `quantity` | integer | no (defaults to `1`) |
| `weight` | number | no |
| `price` | number | no |
| `imageUrl` | string | no |

A line item without a `name` returns `400` with `lineItems[i].name is required`.

### Idempotency

Retrying a create request is safe when you send either:

1. **`externalId`**: your own unique ID for the order, or
2. **`Idempotency-Key` header**: any unique string. ShipWave stores it as the
   order's `externalId`, prefixed with `idem_`.

If both are sent, `externalId` is used. When an order with the same ID already
exists in the store, ShipWave returns that order with status `200` instead of
creating a new one. You get `409 CONFLICT` only when two identical requests
arrive at the same moment; retry the request and it returns the existing order.

### Example

```bash
curl -X POST https://shipwave.app/api/v1/orders \
  -H "Authorization: Bearer sw_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "storeId": "clw9store1",
    "orderNumber": "1043",
    "customerName": "John Doe",
    "customerEmail": "john@example.com",
    "shippingAddress": {
      "name": "John Doe",
      "street1": "456 Oak Ave",
      "city": "Portland",
      "state": "OR",
      "zip": "97201",
      "country": "US"
    },
    "lineItems": [
      {
        "name": "Red Widget",
        "sku": "WIDGET-002",
        "quantity": 1,
        "weight": 8.5,
        "price": 29.99
      }
    ],
    "warehouseId": "clw9wh1",
    "externalId": "my-system-order-1043"
  }'
```

```typescript
const res = await fetch("https://shipwave.app/api/v1/orders", {
  method: "POST",
  headers: {
    Authorization: "Bearer sw_live_abc123...",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    storeId: "clw9store1",
    orderNumber: "1043",
    customerName: "John Doe",
    customerEmail: "john@example.com",
    shippingAddress: {
      name: "John Doe",
      street1: "456 Oak Ave",
      city: "Portland",
      state: "OR",
      zip: "97201",
      country: "US",
    },
    lineItems: [
      { name: "Red Widget", sku: "WIDGET-002", quantity: 1, weight: 8.5, price: 29.99 },
    ],
    warehouseId: "clw9wh1",
    externalId: "my-system-order-1043",
  }),
});

const { data } = await res.json(); // 201 Created, or 200 for an existing order
```

### Response (201 Created)

Returns the order in the same shape as one item from the list response. A new
order has an empty `shipments` array. A new order also sends an
`order.created` [webhook](webhooks.md).

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 400 | `VALIDATION_ERROR` | A required field is missing, a line item has no `name`, `orderDate` is invalid, or `storeId` was left out and the account does not have exactly one active store |
| 403 | `FORBIDDEN` | The key lacks `write:orders`, or carries `deny:raw_fulfillment` |
| 404 | `NOT_FOUND` | Store or warehouse not found |
| 409 | `CONFLICT` | Two identical create requests arrived at the same moment |
| 422 | `VALIDATION_ERROR` | The order looks like Amazon buyer data. Amazon orders can only come in through a connected Amazon account, not this endpoint |
| 500 | `INTERNAL_ERROR` | `Failed to create order` |

---

## Get Order

```
GET /api/v1/orders/:id
```

Returns a single order in the list shape, plus the warehouse address under
`warehouse.address`.

### Example

```bash
curl https://shipwave.app/api/v1/orders/clx1abc2d3efg \
  -H "Authorization: Bearer sw_live_abc123..."
```

### Response

```json
{
  "data": {
    "id": "clx1abc2d3efg",
    "storeId": "clw9store1",
    "warehouseId": "clw9wh1",
    "externalId": "shopify_12345",
    "orderNumber": "1042",
    "status": "pending",
    "customerName": "Jane Smith",
    "customerEmail": "jane@example.com",
    "shippingAddress": {
      "name": "Jane Smith",
      "street1": "123 Main St",
      "street2": "Apt 4B",
      "city": "Austin",
      "state": "TX",
      "zip": "78701",
      "country": "US",
      "phone": "5125550142"
    },
    "totalWeight": 32.5,
    "weightOverrideOz": null,
    "lengthOverride": null,
    "widthOverride": null,
    "heightOverride": null,
    "totalValue": 149.99,
    "requestedService": null,
    "tags": ["priority"],
    "notes": null,
    "orderDate": "2026-02-18T14:30:00.000Z",
    "shipByDate": "2026-02-20T00:00:00.000Z",
    "createdAt": "2026-02-18T14:30:00.000Z",
    "updatedAt": "2026-02-18T14:30:00.000Z",
    "store": {
      "id": "clw9store1",
      "shopDomain": "myshop.myshopify.com",
      "platform": "shopify"
    },
    "warehouse": {
      "id": "clw9wh1",
      "name": "Main Warehouse",
      "address": {
        "name": "Main Warehouse",
        "street1": "500 Commerce Dr",
        "street2": null,
        "city": "Portland",
        "state": "OR",
        "zip": "97201",
        "country": "US",
        "phone": "5035550100"
      }
    },
    "lineItems": [
      {
        "id": "clx1item1",
        "sku": "WIDGET-001",
        "name": "Blue Widget",
        "quantity": 2,
        "weight": 16.0,
        "price": 49.99,
        "imageUrl": "https://cdn.shopify.com/s/files/1/image.jpg"
      }
    ],
    "shipments": []
  }
}
```

`shippingAddress` contains whichever of `name`, `company`, `street1`,
`street2`, `city`, `state`, `zip`, `country`, `phone`, `email`, and
`residential` were recorded for the order.

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 404 | `NOT_FOUND` | The order does not exist or belongs to another account |

---

## Update Order

```
PUT /api/v1/orders/:id
```

Updates fields on ShipWave's copy of the order. Only the fields you send are
changed. Nothing is sent to Shopify or another sales channel.

### Updatable Fields

| Field | Type | Description |
|-------|------|-------------|
| `status` | string | One of `pending`, `on_hold`, `processing`, `shipped`, `fulfilled`, `cancelled` |
| `notes` | string \| null | Internal notes |
| `tags` | string[] \| null | Tags for filtering |
| `shipByDate` | string \| null | Ship-by date (ISO 8601) |
| `shippingAddress` | object | Replaces the stored address object (see below) |
| `warehouseId` | string \| null | Warehouse ID. An explicit warehouse is kept; automatic warehouse selection will not change it |
| `weightOverrideOz` | number \| null | Weight override (oz) |
| `lengthOverride` | number \| null | Length override (in) |
| `widthOverride` | number \| null | Width override (in) |
| `heightOverride` | number \| null | Height override (in) |

`status` changes only ShipWave's record. The other statuses are set by ShipWave
itself. Setting `cancelled` follows the same rule as
[Cancel Order](#cancel-order): an order with a label that has not been voided
returns `409`.

`shippingAddress` only replaces the stored address. It does not buy a new label,
void an existing one, tell the warehouse, or update Shopify. To change where a
customer's order goes, use [Change Shipping Address](#change-shipping-address).

### Example

```bash
curl -X PUT https://shipwave.app/api/v1/orders/clx1abc2d3efg \
  -H "Authorization: Bearer sw_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "tags": ["rush", "fragile"],
    "notes": "Customer requested gift wrap",
    "shipByDate": "2026-02-22T00:00:00.000Z"
  }'
```

```typescript
const res = await fetch("https://shipwave.app/api/v1/orders/clx1abc2d3efg", {
  method: "PUT",
  headers: {
    Authorization: "Bearer sw_live_abc123...",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    tags: ["rush", "fragile"],
    notes: "Customer requested gift wrap",
    shipByDate: "2026-02-22T00:00:00.000Z",
  }),
});
```

### Response

Returns the updated order in the same shape as [Get Order](#get-order),
including `warehouse.address`, and sends an `order.updated`
[webhook](webhooks.md).

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 400 | `VALIDATION_ERROR` | Invalid request body, invalid `shipByDate`, or a `status` you cannot set |
| 403 | `FORBIDDEN` | The key lacks `write:orders`, or carries `deny:raw_fulfillment` |
| 404 | `NOT_FOUND` | Order or warehouse not found |
| 409 | `CONFLICT` | `status: "cancelled"` on an order with an active label |

---

## Change Shipping Address

```
POST /api/v1/orders/:id/address-change
```

Changes where an order ships. `:id` is the ShipWave order ID or the order
number (with or without `#`).

ShipWave checks where the order is and acts on it:

- **No label yet:** updates the address in ShipWave and Shopify. The label bought
  later goes to the new address.
- **Label not yet scanned:** buys a new label to the new address first, then voids
  the old one, swaps the tracking number in Shopify, and sends the new label to
  the warehouse.
- **Carrier already has the package:** changes nothing. A carrier intercept is
  needed.

### Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `shippingAddress` | object | yes | The new address. String fields: `name`, `company`, `street1`, `street2`, `city`, `state`, `zip`, `country`, `phone` |
| `requestedBy` | string | no | Who asked for the change, for the audit trail (max 200 characters) |
| `dryRun` | boolean | no | Report what would happen without buying, voiding, or sending anything. Default `false` |
| `print` | boolean | no | Print the new label at the warehouse. Default `true` for your own warehouses, `false` for third-party (3PL) warehouses |
| `notifyWarehouse` | boolean | no | Email the warehouse the new label. Default `true`. Warehouses connected by API are always updated |
| `syncShopifyBillingAddress` | boolean | no | Also set the Shopify billing address to the new address. Default `false` |
| `enforceDgCompliance` | boolean | no | Limit the replacement label to carriers allowed for dangerous goods. Default `false` |

### Example

```bash
curl -X POST https://shipwave.app/api/v1/orders/clx1abc2d3efg/address-change \
  -H "Authorization: Bearer sw_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "shippingAddress": {
      "name": "Jane Smith",
      "street1": "77 Harbor Rd",
      "city": "Petersburg",
      "state": "AK",
      "zip": "99833",
      "country": "US"
    },
    "requestedBy": "support ticket 1234"
  }'
```

### Response

Every decision returns a receipt: `201` when a new label was bought, `200`
otherwise. Read `outcome`, `settled` and `message`.

```json
{
  "data": {
    "outcome": "label_replaced",
    "settled": true,
    "dryRun": false,
    "orderId": "clx1abc2d3efg",
    "orderNumber": "1042",
    "message": "Replaced 9400111899223100012345 with USPS Priority 9400111899223100067890 to the new address. Main Warehouse was emailed to put the new label on the box; no confirmation yet.",
    "reason": null,
    "shippingAddress": {
      "name": "Jane Smith",
      "company": null,
      "street1": "77 Harbor Rd",
      "street2": null,
      "city": "Petersburg",
      "state": "AK",
      "zip": "99833",
      "country": "US",
      "phone": null
    },
    "previousLabelAddress": {
      "name": "Jane Smith",
      "company": null,
      "street1": "123 Main St",
      "street2": "Apt 4B",
      "city": "Anchorage",
      "state": "AK",
      "zip": "99501",
      "country": "US",
      "phone": null
    },
    "oldShipment": {
      "shipmentId": "clx2ship1",
      "orderShipmentId": "clx2os1",
      "trackingCode": "9400111899223100012345",
      "carrier": "USPS",
      "service": "Priority",
      "labelUrl": "https://easypost-files.s3.amazonaws.com/label.png",
      "rate": 12.5,
      "deliveryDays": 2,
      "voided": true,
      "refundStatus": "submitted"
    },
    "newShipment": {
      "shipmentId": "clx2ship9",
      "orderShipmentId": "clx2os9",
      "trackingCode": "9400111899223100067890",
      "carrier": "USPS",
      "service": "Priority",
      "labelUrl": "https://easypost-files.s3.amazonaws.com/label-2.png",
      "rate": 14.1,
      "deliveryDays": 3
    },
    "quote": { "carrier": "USPS", "service": "Priority", "rate": 14.1, "deliveryDays": 3 },
    "purchaseAttempts": [
      { "carrier": "USPS", "service": "Priority", "rate": 14.1, "ok": true }
    ],
    "shopify": { "addressSynced": true, "trackingReplaced": true },
    "warehouse": {
      "name": "Main Warehouse",
      "channel": "standard",
      "notified": true,
      "confirmed": false,
      "emailSent": true
    },
    "print": { "requested": true, "jobs": [{ "id": "clx4print1", "status": "pending" }], "skippedReason": null },
    "ownerAlerted": false
  }
}
```

| `outcome` | `settled` | What happened |
|-----------|-----------|---------------|
| `address_updated_no_label` | `true` | No label yet. ShipWave and Shopify were updated |
| `already_current` | `true` | The live label already goes to this address. A retry of a finished change lands here |
| `label_replaced` | `true` | A new label was bought, the old one voided, and Shopify and the warehouse updated |
| `carrier_has_package` | `false` | The carrier has scanned the old label. Nothing changed; request an intercept from the carrier |
| `needs_human` | `false` | The order needs manual handling (for example multi-box, international, or freight, or every carrier refused). Nothing changed. `reason` says why |
| `busy` | `false` | Another label purchase is running for this order. Nothing changed; retry in a minute |

`ownerAlerted` is `true` when ShipWave support was alerted to handle a change
that did not settle. With `dryRun: true`, `outcome` and `message` describe what
would happen and nothing is changed.

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 400 | `VALIDATION_ERROR` | Missing `shippingAddress`, or a field that is not a string |
| 404 | `NOT_FOUND` | Order not found |
| 502 | `INTERNAL_ERROR` | Shopify rejected the update for an order with no label yet |

---

## Change Order Email

```
POST /api/v1/orders/:id/email-change
```

For a customer who typed the wrong email at checkout. `:id` is the ShipWave order
ID or the order number (with or without `#`). Shopify orders only.

ShipWave decides whether the requester placed the order. It reads the live
Shopify order and checks the `proof`:

- **Email:** must equal the order's email, its contact email, or the email on the
  order's customer record (after trimming and lowercasing).
- **Name:** first and last name must match. Case, accents, punctuation, middle
  names, initials and Jr/Sr/II are ignored.
- **ZIP/postal code:** US ZIPs compare on the first five digits. Other postal codes
  compare whole, with spaces and hyphens removed.

Name and ZIP can match the shipping address or the billing address, but both must
match the same one. When the proof matches, ShipWave changes the order's email in
Shopify and in ShipWave. It does not change the Shopify customer record. It then
sends one notice to the old address that names the order and masks the new address.
That notice is sent only from a store's verified brand mailbox (Levy Electric:
support@levyelectric.com). A failed notice never undoes the change.

Every failed proof is journaled, dry runs included. After three failed proofs on an
order in 30 days, the endpoint returns `needs_human` and changes nothing.

### Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `newEmail` | string | yes | The email the order should use |
| `proof` | object | yes | `orderEmail`, `name`, `postalCode`: what the requester says they entered at checkout |
| `requestedBy` | string | no | Who asked, for the audit trail (max 200 characters) |
| `dryRun` | boolean | no | Check the proof and report what would happen. Changes and sends nothing, but a failed proof still counts. Default `false` |
| `notifyPreviousEmail` | boolean | no | Send the old-address notice. Default `true` |

### Example

```bash
curl -X POST https://shipwave.app/api/v1/orders/23123611/email-change \
  -H "Authorization: Bearer sw_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "newEmail": "jane.smith@example.com",
    "proof": { "orderEmail": "jane.smith@exmaple.com", "name": "Jane Smith", "postalCode": "99833" },
    "requestedBy": "support ticket 1234"
  }'
```

### Response

Every decision returns `200`. Read `outcome`, `settled` and `message`. The receipt
never echoes the order's real email, name or ZIP.

```json
{
  "data": {
    "outcome": "email_changed",
    "settled": true,
    "dryRun": false,
    "orderId": "clx1abc2d3efg",
    "orderNumber": "#23123611",
    "message": "The order email changed from j•••@exmaple.com to jane.smith@example.com in Shopify and ShipWave. The old address (j•••@exmaple.com) was told.",
    "reason": null,
    "newEmail": "jane.smith@example.com",
    "previousEmailMasked": "j•••@exmaple.com",
    "proof": {
      "verified": true,
      "emailMatches": true,
      "emailMatchedOn": "order_email",
      "nameMatches": true,
      "postalCodeMatches": true,
      "matchedAddress": "shipping"
    },
    "shopify": { "updated": true },
    "shipwave": { "updated": true },
    "notice": { "status": "sent", "recipientMasked": "j•••@exmaple.com" },
    "auditLogId": "clx9audit"
  }
}
```

| `outcome` | `settled` | Meaning |
|-----------|-----------|---------|
| `email_changed` | `true` | Changed (or, with `dryRun`, would change) |
| `already_current` | `true` | The order already uses `newEmail`. A retry finishes any step an earlier run left undone |
| `not_verified` | `false` | The proof did not match. `reason` is `incomplete_claim`, `email_mismatch`, `name_mismatch`, `postal_code_mismatch` or `name_and_postal_code_on_different_addresses` |
| `needs_human` | `false` | `too_many_failed_proofs`, `not_a_shopify_order` or `invalid_shopify_order_id` |
| `busy` | `false` | Another change to this order is running. Try again in a minute |

`notice.status` is one of `sent`, `already_sent`, `would_send`, `skipped`,
`not_configured`, `unconfirmed` (an earlier send has no receipt; check the Sent
folder) or `failed`.

### Errors

| Status | Code | When |
|--------|------|------|
| 400 | `VALIDATION_ERROR` | Missing `newEmail` or a `proof` field, or `newEmail` is not an email |
| 404 | `NOT_FOUND` | No such order in your stores |
| 502 | `INTERNAL_ERROR` | Shopify could not be read or refused the update. Nothing was changed |

---

## Cancel Order

```
DELETE /api/v1/orders/:id
```

Marks the order `cancelled` in ShipWave. It does not cancel the order or refund
the customer in Shopify. To do that, use
[Cancel or Refund](#cancel-or-refund).

You must void all active labels first. If the order has a label that has not
been voided, the request returns `409 CONFLICT`.

### Example

```bash
curl -X DELETE https://shipwave.app/api/v1/orders/clx1abc2d3efg \
  -H "Authorization: Bearer sw_live_abc123..."
```

```typescript
const res = await fetch("https://shipwave.app/api/v1/orders/clx1abc2d3efg", {
  method: "DELETE",
  headers: { Authorization: "Bearer sw_live_abc123..." },
});
const { data } = await res.json();
// { "id": "clx1abc2d3efg", "status": "cancelled" }
```

### Response

```json
{
  "data": {
    "id": "clx1abc2d3efg",
    "status": "cancelled"
  }
}
```

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 404 | `NOT_FOUND` | Order not found |
| 409 | `CONFLICT` | Order has an active (non-voided) label |

---

## Refund Quote

```
GET /api/v1/orders/:id/refund-quote
```

Shows what a refund would be before you send one, using your return policy's
restocking fee. Call it first, then send the same choices to
[Cancel or Refund](#cancel-or-refund). It changes nothing.

### Query Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `refundScope` | string | `full_order` or `line_items`. Leave it out for a full-order refund |
| `lineItems` | string | URL-encoded JSON array of `{ "orderLineItemId": "...", "quantity": 1 }`. `orderLineItemId` is the line item's ShipWave `id` |

- **Full order:** leave out both parameters, or send every line item at its full
  quantity with `refundScope=full_order`. A full-order selection that leaves out
  any quantity is rejected. The amount includes shipping.
- **Some items:** send the items and quantities with `refundScope=line_items`.
  The amount covers merchandise only, not shipping, and the order is never
  cancelled.

### Example

```bash
curl -G https://shipwave.app/api/v1/orders/clx1abc2d3efg/refund-quote \
  -H "Authorization: Bearer sw_live_abc123..." \
  --data-urlencode 'refundScope=line_items' \
  --data-urlencode 'lineItems=[{"orderLineItemId":"clx1item1","quantity":1}]'
```

### Response

```json
{
  "data": {
    "orderId": "clx1abc2d3efg",
    "orderNumber": "1042",
    "status": "shipped",
    "financialStatus": "paid",
    "recommendedAction": "refund_only",
    "canCancel": false,
    "availableLineItems": [
      {
        "orderLineItemId": "clx1item1",
        "shopifyLineItemId": "13579246801",
        "sku": "WIDGET-001",
        "name": "Blue Widget",
        "unitPrice": 49.99,
        "quantity": 2
      }
    ],
    "orderTotal": 149.99,
    "restockingFeePercent": 15,
    "restockingFee": 7.5,
    "suggestedRefund": 42.49,
    "alreadyRefunded": 0,
    "disputeWithheld": 0,
    "maxRefundable": 149.99,
    "scopeSubtotal": 49.99,
    "refundScope": "line_items",
    "selectedLineItems": [
      {
        "orderLineItemId": "clx1item1",
        "shopifyLineItemId": 13579246801,
        "sku": "WIDGET-001",
        "name": "Blue Widget",
        "unitPrice": 49.99,
        "orderedQuantity": 2,
        "quantity": 1,
        "subtotal": 49.99
      }
    ]
  }
}
```

| Field | Description |
|-------|-------------|
| `recommendedAction` | `cancel_and_refund` when nothing has shipped and the whole order is selected; otherwise `refund_only` |
| `canCancel` | `true` when the refund would also cancel the order |
| `availableLineItems` | Every line item you can select, with its ShipWave `orderLineItemId` |
| `suggestedRefund` | The selected amount minus your restocking fee. Cancel or Refund sends this by default |
| `maxRefundable` | Order total minus earlier refunds and money already returned by a lost chargeback |
| `alreadyRefunded` | Earlier successful refunds on this order |
| `disputeWithheld` | Money already returned to the customer by a lost chargeback |

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 400 | `VALIDATION_ERROR` | Invalid `refundScope` or `lineItems` |
| 404 | `NOT_FOUND` | Order not found |
| 409 | `CONFLICT` | The order has an active return. `details.refundEndpoint` names the return refund endpoint to use instead. Or the order came from a marketplace such as eBay; see [Marketplace orders](#marketplace-orders) |

---

## Cancel or Refund

```
POST /api/v1/orders/:id/cancel-or-refund
```

Refunds the customer in Shopify. If nothing has shipped and the whole order is
selected, it then cancels the order in Shopify and its other sales channels.
Shopify orders only. Orders that came from a marketplace (eBay, Walmart, Amazon,
Mirakl and other channels) are refused; see [Marketplace orders](#marketplace-orders).

### Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `reason` | string | yes | Why the order is being refunded |
| `idempotencyKey` | string | yes | Your unique key for this refund. Repeating it never refunds twice |
| `amount` | number | no | Refund amount. Defaults to the quote's `suggestedRefund` |
| `refundScope` | string | no | `full_order` or `line_items`, as in [Refund Quote](#refund-quote) |
| `lineItems` | array | no | `{ "orderLineItemId", "quantity" }` pairs, as in [Refund Quote](#refund-quote) |
| `feeOverride` | object | no | `{ "confirmed": true, "reason": "..." }`. Required when `amount` differs from `suggestedRefund` |
| `notifyCustomer` | boolean | no | Email the customer about the refund. Default `true` |

### Example

```bash
curl -X POST https://shipwave.app/api/v1/orders/clx1abc2d3efg/cancel-or-refund \
  -H "Authorization: Bearer sw_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "reason": "Customer returned one widget",
    "idempotencyKey": "ticket-1234-order-1042",
    "refundScope": "line_items",
    "lineItems": [{ "orderLineItemId": "clx1item1", "quantity": 1 }]
  }'
```

### Response

```json
{
  "data": {
    "orderId": "clx1abc2d3efg",
    "orderNumber": "1042",
    "status": "refunded",
    "refundedAmount": 42.49,
    "restockingFee": 7.5,
    "shopifyRefundId": "987654321",
    "cancelled": false,
    "financialStatus": "partially_refunded",
    "refundScope": "line_items",
    "scopeSubtotal": 49.99,
    "selectedLineItems": [
      {
        "orderLineItemId": "clx1item1",
        "shopifyLineItemId": 13579246801,
        "sku": "WIDGET-001",
        "name": "Blue Widget",
        "unitPrice": 49.99,
        "orderedQuantity": 2,
        "quantity": 1,
        "subtotal": 49.99
      }
    ]
  }
}
```

`cancelled` is `true` when the order was also cancelled. A repeat of a finished
refund with the same `idempotencyKey` returns the original result with
`"idempotent": true` and moves no money. A successful refund sends an
`order.refunded` [webhook](webhooks.md), and a cancellation also sends
`order.cancelled`.

### Errors

| Status | Code | Cause |
|--------|------|-------|
| 400 | `VALIDATION_ERROR` | Missing `reason` or `idempotencyKey`; an invalid `amount`, `refundScope` or `lineItems`; an amount above `maxRefundable`; nothing left to refund; or the order is not a Shopify order |
| 404 | `NOT_FOUND` | Order not found |
| 409 | `CONFLICT` | `amount` differs from the quote without `feeOverride`; the order has an active return; the order came from a marketplace; or a refund with this `idempotencyKey` is still in progress or failed and needs checking |
| 422 | `VALIDATION_ERROR` | Shopify refused the refund (`details.retryable` and `details.moneyMoved` say whether a retry is safe), or the order has no Shopify line items |

### Marketplace orders

eBay, Walmart, Amazon, Mirakl and other marketplace orders reach ShipWave as
copies in your Shopify store. The marketplace collected the buyer's payment, so a
Shopify refund of the copy would never reach the buyer. Refund Quote and Cancel or
Refund return `409 CONFLICT` for these orders before any refund, cancellation or
warehouse call. `error.message` explains the next step, and `error.details` holds:

| Field | Description |
|-------|-------------|
| `code` | `marketplace_refund_required` |
| `marketplace` | Channel platform, such as `ebay` |
| `marketplaceOrderId` | The marketplace's order number, such as `25-15324-58617` |
| `recommendedAction` | `marketplace_cancel` before the package ships, `marketplace_refund` after |
| `cancelEndpoint` | `/api/admin/orders/:id/cancel`. It cancels on the marketplace, which refunds its buyer; check `marketplaceCancelled: true` in its response |
| `refundEndpoint` | `/api/admin/orders/:id/refund` (marketplace refund), or `null` for Walmart, which refunds through its return (`returnsUrl`) |
| `voidLabelFirst` | `true` when a label with no carrier scan must be voided before the cancel |
| `forceRetry` | `true` when ShipWave already marked the order cancelled; send `{"forceRetry": true}` to the cancel so it reaches the marketplace |
