0

Update Discount Code

by
Published Nov 8, 2023

Update a basic code discount (numeric ID or DiscountCodeNode GID). Only the fields you fill are changed; value needs value_type. Changing code renames the discount's code. 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
 * Update Discount Code
5
 * Update a basic code discount (numeric ID or DiscountCodeNode GID). Only the fields you fill are changed; value needs value_type. Changing code renames the discount's code. Needs the write_discounts scope.
6
 */
7
export async function main(
8
  auth: RT.Shopify,
9
  discount_id: string,
10
  title: string | undefined,
11
  code: string | undefined,
12
  value_type: "percentage" | "fixed_amount" | undefined,
13
  value: number | undefined,
14
  starts_at: string | undefined,
15
  ends_at: string | undefined,
16
  usage_limit: number | undefined,
17
  applies_once_per_customer: "keep" | "true" | "false" | undefined,
18
  minimum_subtotal: number | undefined
19
) {
20
  const id = discount_id.startsWith("gid://")
21
    ? discount_id
22
    : `gid://shopify/DiscountCodeNode/${discount_id}`
23

24
  const input: { [key: string]: any } = {
25
    title: title || undefined,
26
    code: code || undefined,
27
    startsAt: starts_at || undefined,
28
    endsAt: ends_at || undefined,
29
    usageLimit: usage_limit ?? undefined,
30
    appliesOncePerCustomer:
31
      applies_once_per_customer === "true"
32
        ? true
33
        : applies_once_per_customer === "false"
34
          ? false
35
          : undefined,
36
    minimumRequirement:
37
      minimum_subtotal != null
38
        ? {
39
            subtotal: {
40
              greaterThanOrEqualToSubtotal: String(minimum_subtotal),
41
            },
42
          }
43
        : undefined,
44
  }
45
  if (value != null && value_type) {
46
    input.customerGets = {
47
      value:
48
        value_type === "percentage"
49
          ? { percentage: value / 100 }
50
          : {
51
              discountAmount: {
52
                amount: String(value),
53
                appliesOnEachItem: false,
54
              },
55
            },
56
    }
57
  }
58

59
  const response = await fetch(
60
    `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
61
    {
62
      method: "POST",
63
      headers: {
64
        "X-Shopify-Access-Token": auth.token,
65
        "Content-Type": "application/json",
66
        Accept: "application/json",
67
      },
68
      body: JSON.stringify({
69
        query: `mutation ($id: ID!, $input: DiscountCodeBasicInput!) { discountCodeBasicUpdate(id: $id, basicCodeDiscount: $input) { codeDiscountNode { id codeDiscount { ... on DiscountCodeBasic { title status summary startsAt endsAt usageLimit appliesOncePerCustomer updatedAt codes(first: 10) { nodes { id code } } } } } userErrors { field message } } }`,
70
        variables: { id, input },
71
      }),
72
    }
73
  )
74

75
  if (!response.ok) {
76
    throw new Error(`${response.status} ${await response.text()}`)
77
  }
78

79
  const { data, errors } = await response.json()
80
  if (errors) {
81
    throw new Error(JSON.stringify(errors))
82
  }
83
  if (data.discountCodeBasicUpdate.userErrors.length) {
84
    throw new Error(JSON.stringify(data.discountCodeBasicUpdate.userErrors))
85
  }
86

87
  return data.discountCodeBasicUpdate
88
}
89

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