1 | |
2 |
|
3 | |
4 | * Create Discount Code |
5 | * Create a basic code discount that takes a percentage (value 10 = 10% off) or a fixed amount (value in the shop currency, once per order) off all items, for all customers. starts_at defaults to now. Needs the write_discounts scope. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | title: string, |
10 | code: string, |
11 | value_type: "percentage" | "fixed_amount", |
12 | value: number, |
13 | starts_at: string | undefined, |
14 | ends_at: string | undefined, |
15 | usage_limit: number | undefined, |
16 | applies_once_per_customer: boolean | undefined, |
17 | minimum_subtotal: number | undefined |
18 | ) { |
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 ($input: DiscountCodeBasicInput!) { discountCodeBasicCreate(basicCodeDiscount: $input) { codeDiscountNode { id codeDiscount { ... on DiscountCodeBasic { title status summary startsAt endsAt usageLimit appliesOncePerCustomer createdAt codes(first: 10) { nodes { id code } } } } } userErrors { field message } } }`, |
30 | variables: { |
31 | input: { |
32 | title, |
33 | code, |
34 | startsAt: starts_at || new Date().toISOString(), |
35 | endsAt: ends_at || undefined, |
36 | usageLimit: usage_limit ?? undefined, |
37 | appliesOncePerCustomer: applies_once_per_customer || undefined, |
38 | context: { all: "ALL" }, |
39 | customerGets: { |
40 | items: { all: true }, |
41 | value: |
42 | value_type === "percentage" |
43 | ? { percentage: value / 100 } |
44 | : { |
45 | discountAmount: { |
46 | amount: String(value), |
47 | appliesOnEachItem: false, |
48 | }, |
49 | }, |
50 | }, |
51 | minimumRequirement: |
52 | minimum_subtotal != null |
53 | ? { |
54 | subtotal: { |
55 | greaterThanOrEqualToSubtotal: String(minimum_subtotal), |
56 | }, |
57 | } |
58 | : undefined, |
59 | }, |
60 | }, |
61 | }), |
62 | } |
63 | ) |
64 |
|
65 | if (!response.ok) { |
66 | throw new Error(`${response.status} ${await response.text()}`) |
67 | } |
68 |
|
69 | const { data, errors } = await response.json() |
70 | if (errors) { |
71 | throw new Error(JSON.stringify(errors)) |
72 | } |
73 | if (data.discountCodeBasicCreate.userErrors.length) { |
74 | throw new Error(JSON.stringify(data.discountCodeBasicCreate.userErrors)) |
75 | } |
76 |
|
77 | return data.discountCodeBasicCreate |
78 | } |
79 |
|