1 | |
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 |
|