Create Price Rule and Discount Code on Shopify using GraphQL mutation

Using GraphQL to create Price Rule and Discount Code on Shopify using GraphQL mutation. Error creating price rule: Target selection can’t be blank

app.post("/api/v1/discount", async (req, res) => {

    const { discountAmount } = req.body;

    // GraphQL mutation สำหรับสร้าง Price Rule

    const priceRuleMutation = `

      mutation priceRuleCreate($priceRule: PriceRuleInput!) {

        priceRuleCreate(priceRule: $priceRule) {

          priceRule {

            id

            status

          }

          userErrors {

            field

            message

          }

        }

      }

    `;

    const priceRuleVariables = {

        priceRule: {

          title: "Point to Cash Discount His&Her",

          target: "LINE_ITEM",

          customerSelection: {

            forAllCustomers: true,

          },

          value: {

            fixedAmountValue: `-${discountAmount}`}, 

          allocationMethod: "ACROSS", 

          usageLimit: 1, 

          oncePerCustomer: true, 

        },

      };

    try {

      const priceRuleResponse = await fetch(

        `https://${shopName}/admin/api/2024-07/graphql.json`,

        {

          method: "POST",

          headers: {

            "Content-Type": "application/json",

            "X-Shopify-Access-Token": accessToken,

          },

          body: JSON.stringify({

            query: priceRuleMutation,

            variables: priceRuleVariables,

          }),

        }

      );

      const priceRuleResult = await priceRuleResponse.json();

      if (!priceRuleResult || !priceRuleResult.data) {

        console.error("Invalid API response:", priceRuleResult);

        throw new Error("Invalid response from API.");

      }

      const priceRuleErrors = priceRuleResult.data.priceRuleCreate.userErrors;

      if (priceRuleErrors.length > 0) {

        throw new Error(

          "Error creating price rule: " + priceRuleErrors[0].message

        );

      }

      const priceRuleId = priceRuleResult.data.priceRuleCreate.priceRule.id;

      console.log("Price Rule ID:", priceRuleId);

      const discountCodeMutation = `

        mutation discountCodeAppCreate($discountCode: DiscountCodeAppInput!) {

          discountCodeAppCreate(discountCode: $discountCode) {

            discountCode {

              id

              code

              combinesWith {

                orderDiscounts

                productDiscounts

                shippingDiscounts

              }

            }

            userErrors {

              field

              message

            }

          }

        }

      `;

      const discountCodeVariables = {

        discountCode: {

          code: `Hisher-Point-${new Date().getTime()}`,

          discountId: priceRuleId,

          combineWith: {

            orderDiscounts: true,

            productDiscounts: true,

            shippingDiscounts: true

          },

        },

      };

      const discountCodeResponse = await fetch(

        `https://${shopName}/admin/api/2024-07/graphql.json`,

        {

          method: "POST",

          headers: {

            "Content-Type": "application/json",

            "X-Shopify-Access-Token": accessToken,

          },

          body: JSON.stringify({

            query: discountCodeMutation,

            variables: discountCodeVariables,

          }),

        }

      );

      const discountCodeResult = await discountCodeResponse.json();

      if (!discountCodeResult || !discountCodeResult.data) {

        console.error("Invalid API response:", discountCodeResult);

        throw new Error("Invalid response from API.");

      }

      const discountCodeErrors =

        discountCodeResult.data.discountCodeAppCreate.userErrors;

      if (discountCodeErrors.length > 0) {

        throw new Error(

          "Error creating discount code: " + discountCodeErrors[0].message

        );

      }

      const discountCode = discountCodeResult.data.discountCodeAppCreate.discountCode.code;

      res.json({ discountCode });

    } catch (error) {

      console.error("Error:", error);

      res.status(500).json({ error: "Failed to create discount code" });

    }

  });

Hi @iccshopping

Your request is missing parameters:

“itemEntitlements”: {
“targetAllLineItems”:true
},
“validityPeriod”:{
“start”: “2024-09-12T00:00:00Z”
},

{
    "priceRule": {
        "allocationMethod": "ACROSS",
        "customerSelection": {
            "forAllCustomers": true
        },
        "itemEntitlements": {
            "targetAllLineItems":true
        },
        "validityPeriod":{
            "start": "2024-09-12T00:00:00Z"
        },
        "oncePerCustomer": true,
        "target": "LINE_ITEM",
        "title": "Point to Cash Discount His&Her",
        "usageLimit": 1,
        "value": {
            "fixedAmountValue": "-50"
        }
    }
}