Last active
May 15, 2023 20:35
-
-
Save rdraward/5ebc2990d27482ad4ab53aea0300bfdf to your computer and use it in GitHub Desktop.
Code used for Shopify's product discount Function: https://www.youtube.com/watch?v=4ie7HX2HjSk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // input.graphql file for a Shopify product discount Function | |
| query Input { | |
| cart { | |
| attribute(key: "addedPrePurchase") { | |
| value | |
| } | |
| lines { | |
| quantity | |
| merchandise { | |
| ... on ProductVariant { | |
| id | |
| } | |
| } | |
| } | |
| } | |
| } | |
| // default export from src/index.js of a Shopify product discount Function | |
| export default /** | |
| * @param {InputQuery} input | |
| * @returns {FunctionResult} | |
| */ | |
| (input) => { | |
| const attribute = input?.cart?.attribute; | |
| const variantId = attribute?.value?.toString() || ""; | |
| const lines = input.cart.lines; | |
| const isInCart = lines.find((line) => line.merchandise?.id === variantId); | |
| if (isInCart) { | |
| return { | |
| discountApplicationStrategy: DiscountApplicationStrategy.First, | |
| discounts: [ | |
| { | |
| value: { | |
| percentage: { | |
| value: 25, | |
| }, | |
| }, | |
| targets: [ | |
| { | |
| productVariant: { | |
| id: variantId, | |
| }, | |
| }, | |
| ], | |
| message: "25% off", | |
| }, | |
| ], | |
| }; | |
| } | |
| return EMPTY_DISCOUNT; | |
| }; | |
| // Gadget code effect used to create a new Discount in Shopify | |
| // NOTE: if placed on the Shopify Shop install action, you can use `connections.shopify.current` to get the current connection | |
| module.exports = async ({ api, scope, logger, params, connections }) => { | |
| const shopify = await connections.shopify.forShopId("<YOUR SHOP ID>"); | |
| if (shopify) { | |
| // create the discount object to be created in Shopify | |
| const discount = { | |
| functionId: process.env.FUNCTION_ID, | |
| title: "pre-purchase discount", | |
| startsAt: new Date(), | |
| }; | |
| logger.debug({ discount }, "discount to create"); | |
| // query to create a new discount on the current store | |
| const query = ` | |
| mutation discountAutomaticAppCreate($automaticAppDiscount: DiscountAutomaticAppInput!) { | |
| discountAutomaticAppCreate(automaticAppDiscount: $automaticAppDiscount) { | |
| automaticAppDiscount { | |
| title | |
| } | |
| userErrors { | |
| field | |
| message | |
| } | |
| } | |
| } | |
| `; | |
| const discountResponse = await shopify.graphql(query, { | |
| automaticAppDiscount: discount, | |
| }); | |
| logger.info({ discountResponse }, "discount creation response") | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment