Creating and managing discounts with GraphQL

This guide describes how to create and retrieve discounts by using the Discounts GraphQL API. It provides examples for two different types of discounts (automatic discounts and code discounts), and the recommended best practices for each type.

All of the queries and mutations in this guide are for the unstable API version. You can access them by making your calls to https://.myshopify.com/admin/api/unstable/graphql.json. For a full list of the schema, see the GraphQL Admin API reference.

If you aren’t familiar with GraphQL, then refer to the Getting started guide or The GraphQL Learning Kit to learn more.

Requirements

  • The mutations described here require the write_discounts permission.
  • The queries described here require the read_discounts permission.

Creating automatic discounts

Automatic discounts refer to the set of objects and mutations in GraphQL that let you create and manage discounts that are automatically applied to a cart if prerequisites are met. This method is available only in the GraphQL Admin API.

The following examples show two different types of automatic discounts:

Buy X Get Y automatic discount

This example shows how to create an automatic Buy One Get One discount that will be applied to a single product any time it’s included in a cart. In this case, it applies a 100% discount on the second item in a cart, as long as it’s the same product as the first item.

mutation {
  discountAutomaticBxgyCreate(automaticBxgyDiscount: {
    title: "bxgy test",
    startsAt: "2016-01-01",
    endsAt: "2019-04-18T02:38:45Z",
    usesPerOrderLimit: "1",
    customerBuys: {
      value: {
        quantity: "1"
      }
      items: {
        products: {
          productsToAdd: ["gid://shopify/Product/1536578748438"]
        }
      }
    },
    customerGets: {
      value: {
        discountOnQuantity: {
          quantity: "1",
          effect: {
            percentage: 1.00
          }
        }
      }
      items: {
        products: {
          productsToAdd: ["gid://shopify/Product/1536578748438"]
        }
      }
    }}) {
    userErrors { field message code }
    automaticDiscountNode {
        automaticDiscount {
        ... on DiscountAutomaticBxgy {
          title
          summary
          status
        }
      }
    }
  }
}

Based on that example, you can make a few different changes to offer specific types of discounts:

  • If you want to change the discount amount, then edit customerGets.value.discountOnQuantity.effect.percentage.
  • If you want to apply the discount to a different item, then use customerGets.items.products.productsToAdd and customerGets.items.products.productsToRemove to update the entitlements.
  • If you want to apply the discount to all items, then use customerGets.items.all instead of a specific product ID.
  • If you want a customer to get a discount no matter which item they purchase, then set the customerBuys.items.all prerequisite to true instead of a specific product.

Percentage or fixed-amount automatic discount

This example shows how to create an automatic discount of 10% that will be applied to a single product any time it’s included in a cart. The percentage input requires a value between 0 and 1. In the example below 0.10 represents 10% off. A 100% discount would be 1.0 and a 50% discount would be 0.5.

mutation{
  discountAutomaticBasicCreate(automaticBasicDiscount: {
      title: "AutoDiscountTest"
      startsAt: "2017-04-18T02:38:45Z"
      endsAt: "2018-04-18T02:38:45Z",
      customerGets: {
        value: {
         #Accepts percentage, discount amount, discount on quantity         
         percentage: 0.10
          }
        items: {
          products: {
            productsToAdd: ["gid://shopify/Product/1536578748438"]
          }          
        }
      }
      minimumRequirement: {
        #Accepts quantity, or subtotal
        quantity: {
          greaterThanOrEqualToQuantity: "1"
        }
      }
  })
  {
    userErrors { field message code }
    automaticDiscountNode {
        automaticDiscount {
        ... on DiscountAutomaticBasic {
          title
          shortSummary
          summary
          minimumRequirement {
            ... on DiscountMinimumQuantity { quantity: greaterThanOrEqualToQuantity }
            ... on DiscountMinimumSubtotal { subtotal: greaterThanOrEqualToSubtotal { amount currencyCode }}
          }
        }
      }
    }
  }
}

Creating code discounts

Code discounts refer to the set of objects and mutations in GraphQL that let you create and manage discounts that include a unique code. Code discounts enable specific discounts to be redeemed when the codes are applied manually by the customer during the checkout. This method is available only in the GraphQL Admin API.

The following examples show three different types of code discounts:

Buy X Get Y code discount

This example shows how to create a Buy One Get One discount that requires the customer to enter a code at checkout. In this case, it lets all customers use this code, and offers a buy one get one discount on the same product. You can also change the discount so that it applies to a different product than the original.

mutation {
  discountCodeBxgyCreate(bxgyCodeDiscount: {
    title: "code bxgy test",
    startsAt: "2016-01-01",
    endsAt: "2019-04-18T02:38:45Z",
    usesPerOrderLimit: 1,
    code: "TESTCODE1001234",
    customerSelection: {
      all: true
    }
    customerBuys: {
      value: {
        quantity: "1"
      }
      items: {
        products: {
          productsToAdd: ["gid://shopify/Product/1536578748438"]
        }
      }
    },
    customerGets: {
      value: {
        discountOnQuantity: {
          quantity: "1",
          effect: {
            percentage: 1.00
          }
        }
      }
      items: {
        products: {
          productsToAdd: ["gid://shopify/Product/1536578748438"]
        }
      }
    }}) {
    userErrors { field message code }
    codeDiscountNode {
      id
        codeDiscount {
        ... on DiscountCodeBxgy {
          title
          summary
          status
          codes (first:100) {
            edges {
              node {
                code
              }
            }
          }
        }
      }
    }
  }
}

Percentage or fixed-amount discount code

This example shows how to associate a flat percentage or fixed-amount discount with a code that the customer can use at checkout. Similar in format to creating a buy one get one discount, here we will create a $1.00 off discount for a specific product.

mutation {
  discountCodeBasicCreate(basicCodeDiscount: {
    title: "code basic test",
    startsAt: "2019-01-01",
    endsAt: "2020-01-01",
    usageLimit: 10,
    appliesOncePerCustomer: true,
    customerSelection: {
      all: true
    }
    code: "123456",
    customerGets: {
      value: {
        discountAmount:  {
          amount: 1.00,
          each: true
        }
      }
      items: {
        products: {
          productsToAdd: ["gid://shopify/Product/1536578748438"]
        }
      }
    }}) {
    userErrors { field message code }
    codeDiscountNode {
      id
        codeDiscount {
        ... on DiscountCodeBasic {
          title
          summary
          status
          codes (first:10) {
            edges {
              node {
                code
              }
            }
          }
        }
      }
    }
  }
}

Free Shipping code discount

This example shows how to associate a Free Shipping discount with a code that will grant the customer free shipping when they use it. In this example, the discount applies to a saved search of customers in customerSelection.customerSavedSearches if those customers are from Canada. If you want to provide the discount to all countries, then you can replace destination.countires.add with destination.all set to true. Note that if you specify a country where you want to offer free shipping, the shop must have a shipping zone configured for that country before it will work.

mutation {
  discountCodeFreeShippingCreate(
    freeShippingCodeDiscount:{
      code: "FSCODE"
      title: "Free Shipping"
      startsAt: "2019-05-15T15:02:49Z"
      destination: { countries:{ add: [CA] } }
      customerSelection:{
        customerSavedSearches: {
          add: ["gid://shopify/SavedSearch/1"]
        }
      }
    }
  ) {
    userErrors { field message code }
    codeDiscountNode {
      id
      codeDiscount {
        __typename
        ... on DiscountCodeFreeShipping {
          title
          status
          codes (first:10) {
            edges {
              node {
                code
              }
            }
          }
        }
      }
    }
  }
}

Managing Discounts

You can use the API to manage and make changes to your current discounts.

Query automatic discounts on a shop

When making GraphQL queries, you can return multiple objects at a time. The following example shows how to request the first 10 automatic discount codes, which returns the details about whether they’re either the BxGy or Basic type.

{
automaticDiscountNodes (first: 10) {
  edges {
    node {
      id
      automaticDiscount {
        __typename
        ... on DiscountAutomaticBxgy {
          status
          title
        }
        ... on DiscountAutomaticBasic {
          status
          title
        }        
      }
    }
  }
 }
}

Query a specific automatic discount

To query a specific automatic discount, all you need is its ID. The following example query might look complicated because it uses a concept called fragments. This lets you create a query that returns the information only if it matches your criteria. In this case, we are requesting all possible information about this discount no matter what type it is, in case we don’t know the details of the automatic discount beforehand.

{
  automaticDiscountNode(id: "gid://shopify/DiscountAutomaticNode/298192273430") {
    id
    automaticDiscount {
      __typename
      ... on DiscountAutomaticBxgy {
        createdAt
        customerBuys {
          items {
            __typename
            ... on DiscountProducts {
              productVariants(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
              products(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            ... on DiscountCollections {
              collections(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            ... on AllDiscountItems {
              allItems
            }
          }
          value {
            __typename
            ... on DiscountQuantity {
              quantity
            }
          }
        }
        customerGets {
          items {
            __typename
            ... on DiscountProducts {
              productVariants(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
              products(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            ... on DiscountCollections {
              collections(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            ... on AllDiscountItems {
              allItems
            }
          }
          value {
            __typename
            ... on DiscountOnQuantity {
              effect
              quantity {
                quantity
              }
            }
            ... on DiscountAmount {
              amount {
                amount
                currencyCode
              }
              each
            }
            ... on DiscountPercentage {
              percentage
            }
          }
        }
        startsAt
        endsAt
        status
        summary
        title
        usageCount
        title
      }
      ... on DiscountAutomaticBasic {
        createdAt
        customerGets {
          items {
            __typename
            ... on DiscountProducts {
              productVariants(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
              products(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            ... on DiscountCollections {
              collections(first: 10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            ... on AllDiscountItems {
              allItems
            }
          }
          value {
            __typename
          }
        }
        minimumRequirement {
          __typename
        }
        shortSummary
        startsAt
        endsAt
        status
        summary
        title
        usageCount
        title
      }
    }
    events(first: 10) {
      edges {
        node {
          appTitle
          attributeToApp
          attributeToUser
          createdAt
          criticalAlert
          id
          message
          __typename
        }
      }
    }
  }
}

Activate and deactivate automatic discounts

To activate or deactivate an automatic discount, you can use the mutations discountAutomaticActivate or discountAutomaticDeactivate. The only input required is the ID of the automatic discount to perform the action on.

mutation{
  discountAutomaticActivate(id: "gid://shopify/DiscountAutomaticNode/298196369430"){
    automaticDiscountNode {
      automaticDiscount {
        __typename
        ... on DiscountAutomaticBxgy {
          status
          title
        }
        ... on DiscountAutomaticBasic {
          status
          title
        }        
      }
      id
    }
    userErrors {
      code
      field
      message
    }
  }
}
mutation{
  discountAutomaticDeactivate(id: "gid://shopify/DiscountAutomaticNode/298203152406"){
    automaticDiscountNode {
      automaticDiscount {
        __typename
        ... on DiscountAutomaticBxgy {
          status
          title
        }
        ... on DiscountAutomaticBasic {
          status
          title
        }        
      }
      id
    }
    userErrors {
      code
      field
      message
    }
  }
}

Query code discounts on a shop

The following example shows how to query basic code discounts on a shop. As with all GraphQL queries, you can request only the details that you want in the query to keep it short. We’ll expand on all possible fields here in the next examples so no need to include them all twice.

{
  codeDiscountNodes (first:10) {
    edges {
      node {
        id
        codeDiscount {
          __typename
        }
      }
    }
  }
}

Query a specific discount code

Similar to automatic discounts, you can query a specific code by ID and request only the information you want. Here is an example of all possible fields on a basic discount code. In the following example, you could replace the DiscountCodeBasic fragment with DiscountCodeBxgy or DiscountCodeFreeShipping. Although they all have a slight variation in the return fields, the basic format is the same.

{
  codeDiscountNode (id: "gid://shopify/DiscountCodeNode/4272958227") {
    id
    events (first:10) {
      edges {
        node {
          appTitle
          attributeToApp
          attributeToUser
          createdAt
          criticalAlert
          id
          message
          __typename
        }
      }
    }
    codeDiscount {
      __typename
      ... on DiscountCodeBasic {
        appliesOncePerCustomer
        asyncUsageCount
        codeCount
        codes (first:10) {
          edges {
            node {
              code
            }
          }
        }
        createdAt
        customerGets {
          items {
            __typename
            ... on DiscountProducts {
              products (first:10) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
          }
          value {
            __typename
            ... on DiscountOnQuantity {
              effect {
                __typename
                ... on DiscountPercentage {
                  percentage
                }
              }
              quantity {
                quantity
              }
            }
          }
        }
        customerSelection {
          __typename
          ... on DiscountCustomerAll {
            allCustomers
          }
        }
        endsAt
        shortSummary
        startsAt
        status
        summary
        title
        usageLimit
      }
    }
  }
}

Update an automatic discount

Updating a discount is done in the same way as creating a discount, but it has a unique mutation. Use discountAutomaticBxgyUpdate if it’s a BxGy discount, or discountAutomaticBasicUpdate if it’s a basic discount. Note that when updating a discount code, you have to explicitly add and remove entitled products by using productsToAdd and productsToRemove as shown in the example below. You can add or remove multiple products by passing them in a comma-separated list.

mutation {
  discountAutomaticBxgyUpdate(id: "gid://shopify/DiscountAutomaticNode/298192470038"
    automaticBxgyDiscount: {
      title: "bxgy test3",
      startsAt: "2016-01-01",
      endsAt: "2019-04-18T02:38:45Z",
      usesPerOrderLimit: "1",
      customerBuys: {
        value: {
          quantity: "1"
        }
        items: {
          products: {
            productsToAdd: ["gid://shopify/Product/1536578748438"],
            productsToRemove: ["gid://shopify/Product/1536578748401", "gid://shopify/Product/1536578748400"]
          }
        }
      },
      customerGets: {
        value: {
          discountOnQuantity: {
            quantity: "1",
            effect: {
              percentage: 1.00
            }
          }
        }
        items: {
          products: {
            productsToAdd: ["gid://shopify/Product/1536578748438"]
          }
        }
      }})
  {
    userErrors {
      field
      message
      code
    }
    automaticDiscountNode {
      automaticDiscount {
        ... on DiscountAutomaticBxgy {
          title
          summary
          status  
        }
      }
    }
  }
}

Update a code discount

Updating a discount is done in the same way as creating a discount, but it has a unique mutation. Use discountCodeBxgyUpdate if it’s a BxGy discount, discountCodeBasicUpdate if it's a basic discount, or discountCodeFreeShippingUpdate if it’s a Free Shipping discount. If you want to update a discount, then you need to pass in the ID of the code that you want to update. Also note that you only need to include the fields that you want to update (in the following example, only the title is included).

mutation {
  discountCodeBxgyUpdate(id: "gid://shopify/DiscountCodeNode/298191814678",
    bxgyCodeDiscount: {
      title: "code bxgy test, name updated",
    }) {
    userErrors { field message code }
    codeDiscountNode {
      id
      codeDiscount {
        ... on DiscountCodeBxgy {
          title
          summary
          status
          codes (first:100) {
            edges {
              node {
                code
              }
            }
          }
        }
      }
    }
  }
}

Delete an automatic discount

To delete an automatic discount, all you need is its ID.

mutation {
  discountAutomaticDelete (id: "gid://shopify/DiscountAutomaticNode/298192502806")
  {
  deletedAutomaticDiscountId
  userErrors {
    code
    field
    message
  }
 }
}

Bulk delete automatic discount

The following example shows how to delete automatic discount codes in bulk by specifying an array of IDs.

mutation {
  discountAutomaticBulkDelete (
    ids: [
      "gid://shopify/DiscountAutomaticNode/298192273430",
      "gid://shopify/DiscountAutomaticNode/298192371734"
    ])
  {
    job {
      done
      id
    }
    userErrors {
      code
      field
      message
    }
  }
}

Paginate through discount codes

If you aren't familiar with pagination through GraphQL, then see the Shopify GraphQL Learning Kit. The way that the pageInfo and cursor parameters are structured in the discounts object is similar to how they're structured elsewhere in GraphQL. The following example shows a sample query with these parameters.

{
  codeDiscountNodes (first:10) {
    pageInfo {
      hasNextPage
      hasPreviousPage
    }
    edges {
      cursor
      node {
        id
        codeDiscount {
          __typename
        }
      }
    }
  }
}

Sign up for a Partner account to get started.

Sign up