//native
/**
* Create Discount Code
* 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.
*/
export async function main(
auth: RT.Shopify,
title: string,
code: string,
value_type: "percentage" | "fixed_amount",
value: number,
starts_at: string | undefined,
ends_at: string | undefined,
usage_limit: number | undefined,
applies_once_per_customer: boolean | undefined,
minimum_subtotal: number | undefined
) {
const response = await fetch(
`https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
{
method: "POST",
headers: {
"X-Shopify-Access-Token": auth.token,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
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 } } }`,
variables: {
input: {
title,
code,
startsAt: starts_at || new Date().toISOString(),
endsAt: ends_at || undefined,
usageLimit: usage_limit ?? undefined,
appliesOncePerCustomer: applies_once_per_customer || undefined,
context: { all: "ALL" },
customerGets: {
items: { all: true },
value:
value_type === "percentage"
? { percentage: value / 100 }
: {
discountAmount: {
amount: String(value),
appliesOnEachItem: false,
},
},
},
minimumRequirement:
minimum_subtotal != null
? {
subtotal: {
greaterThanOrEqualToSubtotal: String(minimum_subtotal),
},
}
: undefined,
},
},
}),
}
)
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { data, errors } = await response.json()
if (errors) {
throw new Error(JSON.stringify(errors))
}
if (data.discountCodeBasicCreate.userErrors.length) {
throw new Error(JSON.stringify(data.discountCodeBasicCreate.userErrors))
}
return data.discountCodeBasicCreate
}
Submitted by hugo989 3 hours ago