Hi there,
My end goal is to trigger a discount on checkout conditionally based on piece of metadata.
I want to make this discount function to be usable by Plus and non-Plus stores.
So I thought that the Input cart.attribute
field might the the trick.
So as a test, on the online storefront I created a sample attribute on the cart discount_qualified
:
fetch('/cart/update.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
attributes: {
discount_qualified: 'true'
}
})
})
.then(response => response.json())
.then(data => {
console.log('Cart attribute updated:', data);
})
.catch((error) => {
console.error('Error:', error);
});
And I set up an input schema like so:
query CartInput {
cart {
attribute(key: "discount_qualified") {
value
}
}
}
I also ran shopify app function typegen
to make sure the schema was updated.
And finally, I created and activated discount function using the cart attribute to qualify the checkout for a discount:
import {
OrderDiscountSelectionStrategy,
ProductDiscountSelectionStrategy,
CartInput,
CartLinesDiscountsGenerateRunResult,
} from "../generated/api";
export function generateCartRun(
input: CartInput
): CartLinesDiscountsGenerateRunResult {
console.log("starting function");
console.log("input", JSON.stringify(input, null, 2));
console.log(
`discount_qualified value: ${input.cart?.attribute?.value}`
);
const isQualified = input.cart.attribute?.value === "true";
if (!isQualified) {
return {
operations: [],
};
}
return {
operations: [
{
orderDiscountsAdd: {
candidates: [
{
message: "10% OFF ORDER",
targets: [
{
orderSubtotal: {
excludedCartLineIds: [],
},
},
],
value: {
percentage: {
value: 10,
},
},
},
],
selectionStrategy: OrderDiscountSelectionStrategy.First,
},
}
],
};
}
But the cart.attribute
value is null
.
Are cart attributes accessible to the discount function not the same as the Online Store AJAX Cart API attributes?
If they aren’t then how can one update them?
I’d really like to be able to offer a discount function to Plus and non-Plus stores.