0

Cancel Order

by
Published Nov 8, 2023

Cancel an order, optionally refunding and restocking it (runs as an async job).

Script shopify Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 2 hours ago
1
//native
2

3
/**
4
 * Cancel Order
5
 * Cancel an order, optionally refunding it to the original payment methods and restocking its items. Cancellation runs asynchronously: the result holds a job id and jobResult (status, errors); fetch the order later to confirm cancelledAt.
6
 */
7
export async function main(
8
  auth: RT.Shopify,
9
  order_id: string,
10
  reason: "CUSTOMER" | "DECLINED" | "FRAUD" | "INVENTORY" | "STAFF" | "OTHER",
11
  refund: boolean | undefined,
12
  restock: boolean | undefined,
13
  notify_customer: boolean | undefined,
14
  staff_note: string | undefined
15
) {
16
  const orderId = order_id.startsWith("gid://")
17
    ? order_id
18
    : `gid://shopify/Order/${order_id}`
19
  const response = await fetch(
20
    `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
21
    {
22
      method: "POST",
23
      headers: {
24
        "X-Shopify-Access-Token": auth.token,
25
        "Content-Type": "application/json",
26
        Accept: "application/json",
27
      },
28
      body: JSON.stringify({
29
        query: `mutation ($orderId: ID!, $reason: OrderCancelReason!, $restock: Boolean!, $refundMethod: OrderCancelRefundMethodInput, $notifyCustomer: Boolean, $staffNote: String) { orderCancel(orderId: $orderId, reason: $reason, restock: $restock, refundMethod: $refundMethod, notifyCustomer: $notifyCustomer, staffNote: $staffNote) { job { id done } jobResult { id done status errors { code field message } } orderCancelUserErrors { code field message } } }`,
30
        variables: {
31
          orderId,
32
          reason,
33
          restock: restock || false,
34
          refundMethod: { originalPaymentMethodsRefund: refund || false },
35
          notifyCustomer: notify_customer || false,
36
          staffNote: staff_note || undefined,
37
        },
38
      }),
39
    }
40
  )
41

42
  if (!response.ok) {
43
    throw new Error(`${response.status} ${await response.text()}`)
44
  }
45

46
  const { data, errors } = await response.json()
47
  if (errors) {
48
    throw new Error(JSON.stringify(errors))
49
  }
50

51
  if (data.orderCancel.orderCancelUserErrors.length) {
52
    throw new Error(JSON.stringify(data.orderCancel.orderCancelUserErrors))
53
  }
54

55
  return data.orderCancel
56
}
57

Other submissions
  • Submitted by hugo697 Typescript (fetch-only)
    Created 528 days ago
    1
    type Shopify = {
    2
      token: string;
    3
      store_name: string;
    4
    };
    5
    /**
    6
     * Cancels an order
    7
     *  Caution For multi-currency orders, the currency property is required whenever the amount property is provided. For more information, see Migrating to support multiple currencies.  Cancels an order. Orders that have a fulfillment object can't be canceled.
    8
     */
    9
    export async function main(
    10
      auth: Shopify,
    11
      api_version: string = "2023-10",
    12
      order_id: string,
    13
      body: {
    14
        amount?: string;
    15
        currency?: string;
    16
        note?: string;
    17
        [k: string]: unknown;
    18
      }
    19
    ) {
    20
      const url = new URL(
    21
        `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/orders/${order_id}/cancel.json`
    22
      );
    23
    
    
    24
      const response = await fetch(url, {
    25
        method: "POST",
    26
        headers: {
    27
          "Content-Type": "application/json",
    28
          "X-Shopify-Access-Token": auth.token,
    29
        },
    30
        body: JSON.stringify(body),
    31
      });
    32
      if (!response.ok) {
    33
        const text = await response.text();
    34
        throw new Error(`${response.status} ${text}`);
    35
      }
    36
      return await response.json();
    37
    }
    38