0

Create Gift Card

by
Published Nov 8, 2023

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.

Script shopify Verified

The script

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

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