app.post(“/api/create-discount”, async (req, res) => {
try {
const session = res.locals.shopify.session;
const discountData = await createDiscount(session, req.body);
if (discountData.error) {
return res.status(400).json(discountData.error);
}
res.json(discountData);
} catch (error) {
console.error(“Discount creation error:”, error);
res.status(500).json({ error: “Failed to create discount” });
}
});
const createDiscount = async (session, body) => {
try {
const client = new shopify.api.clients.Graphql({ session });
const response = await client.query({
data: {
query: mutation discountAutomaticAppCreate($automaticAppDiscount: DiscountAutomaticAppInput!) { discountAutomaticAppCreate(automaticAppDiscount: $automaticAppDiscount) { userErrors { field message } automaticAppDiscount { discountId title startsAt endsAt status appDiscountType { appKey functionId } combinesWith { orderDiscounts productDiscounts shippingDiscounts } } } },
variables: {
automaticAppDiscount: {
title: “$5 discount”,
functionId: “?”, // how to find this or create
startsAt: “2025-02-02T17:09:21Z”,
endsAt: “2025-02-02T17:09:21Z”,
combinesWith: {
orderDiscounts: false,
productDiscounts: false,
shippingDiscounts: false,
},
metafields: [
{
namespace: “default”,
key: “function-configuration”,
type: “json”,
value: JSON.stringify({
discounts: [
{
value: { fixedAmount: { amount: 5 } },
targets: [
{
orderSubtotal: {
excludedVariantIds: ,
},
},
],
},
],
discountApplicationStrategy: “FIRST”,
}),
},
],
},
},
},
});
const result = response.body.data.discountAutomaticAppCreate;
if (result.userErrors.length > 0) {
throw new Error(result.userErrors.map((e) => e.message).join(", "));
}
return { success: true, data: result.automaticAppDiscount };
} catch (error) {
console.error(“Discount creation failed:”, error);
return { error: error.message };
}
};