0

Create Discount Code

by
Published Nov 8, 2023

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.

Script shopify Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 2 hours ago
1
//native
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

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
     * Creates a discount code
    7
     * Creates a discount code
    8
     */
    9
    export async function main(
    10
      auth: Shopify,
    11
      api_version: string = "2023-10",
    12
      price_rule_id: string,
    13
      body: {
    14
        discount_code?: { code?: string; [k: string]: unknown };
    15
        [k: string]: unknown;
    16
      }
    17
    ) {
    18
      const url = new URL(
    19
        `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/price_rules/${price_rule_id}/discount_codes.json`
    20
      );
    21
    
    
    22
      const response = await fetch(url, {
    23
        method: "POST",
    24
        headers: {
    25
          "Content-Type": "application/json",
    26
          "X-Shopify-Access-Token": auth.token,
    27
        },
    28
        body: JSON.stringify(body),
    29
      });
    30
      if (!response.ok) {
    31
        const text = await response.text();
    32
        throw new Error(`${response.status} ${text}`);
    33
      }
    34
      return await response.json();
    35
    }
    36