1 | |
2 |
|
3 | |
4 | * Create Gift Card |
5 | * Issue a gift card with an initial value (currency_code defaults to the shop currency). Leave code empty to let Shopify generate one; the full code is only returned now, as giftCardCode. Needs the write_gift_cards scope. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | initial_value: number, |
10 | currency_code: string | undefined, |
11 | code: string | undefined, |
12 | customer_id: string | undefined, |
13 | note: string | undefined, |
14 | expires_on: string | undefined, |
15 | template_suffix: string | undefined |
16 | ) { |
17 | const endpoint = `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json` |
18 | const headers = { |
19 | "X-Shopify-Access-Token": auth.token, |
20 | "Content-Type": "application/json", |
21 | Accept: "application/json", |
22 | } |
23 |
|
24 | let currencyCode = currency_code |
25 | if (!currencyCode) { |
26 | const shopResponse = await fetch(endpoint, { |
27 | method: "POST", |
28 | headers, |
29 | body: JSON.stringify({ query: `query { shop { currencyCode } }` }), |
30 | }) |
31 | if (!shopResponse.ok) { |
32 | throw new Error(`${shopResponse.status} ${await shopResponse.text()}`) |
33 | } |
34 | const shop = await shopResponse.json() |
35 | if (shop.errors) { |
36 | throw new Error(JSON.stringify(shop.errors)) |
37 | } |
38 | currencyCode = shop.data.shop.currencyCode |
39 | } |
40 |
|
41 | const response = await fetch(endpoint, { |
42 | method: "POST", |
43 | headers, |
44 | body: JSON.stringify({ |
45 | query: `mutation ($input: GiftCardCreateInput!) { giftCardCreate(input: $input) { giftCard { id maskedCode lastCharacters enabled expiresOn note templateSuffix createdAt initialValue { amount currencyCode } balance { amount currencyCode } customer { id displayName } } giftCardCode userErrors { field message } } }`, |
46 | variables: { |
47 | input: { |
48 | initialAmount: { amount: String(initial_value), currencyCode }, |
49 | code: code || undefined, |
50 | customerId: customer_id |
51 | ? customer_id.startsWith("gid://") |
52 | ? customer_id |
53 | : `gid://shopify/Customer/${customer_id}` |
54 | : undefined, |
55 | note: note || undefined, |
56 | expiresOn: expires_on || undefined, |
57 | templateSuffix: template_suffix || undefined, |
58 | }, |
59 | }, |
60 | }), |
61 | }) |
62 |
|
63 | if (!response.ok) { |
64 | throw new Error(`${response.status} ${await response.text()}`) |
65 | } |
66 |
|
67 | const { data, errors } = await response.json() |
68 | if (errors) { |
69 | throw new Error(JSON.stringify(errors)) |
70 | } |
71 | if (data.giftCardCreate.userErrors.length) { |
72 | throw new Error(JSON.stringify(data.giftCardCreate.userErrors)) |
73 | } |
74 |
|
75 | return data.giftCardCreate |
76 | } |
77 |
|