I was searching for the answer to this question for a few days and I found various answers that didn’t really help or it added a lot more overhead than was necessary.
I am not going to go into the specifics for why somebody may be wanting to do this or the specifics of the backend code that would need to also be handled. Mostly because the backend code requirements will depend greatly on what exactly is needing to be done.
But the Checkout UI Extension has an API for dealing with GiftCards.
I will try to be as in-depth as I can with the example.
The hook for doing this would be the useAppliedGiftCards hook and it can be used like this.
const applyGiftCardChange = useApplyGiftCardChange();
const handleApplyGiftCard = useCallback(
async (giftCardCode) => {
const giftCardChange = {
type: 'addGiftCard',
code: giftCardCode,
};
const { error, message, type, success } = await applyGiftCardChange(
giftCardChange
);
console.log(
`Error: ${error}, Message: ${message}, Type: ${type}, Success: ${success}`
);
},
[applyGiftCardChange]
);
// THEN MAKE WHATEVER BACKEND CALL YOU NEED TO GET THE RELEVANT INFORMATION
const makePostRequest = async () => {
const response = await fetch(
`https://theurlyoucall/whatever-endpoint`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
dataOne: dataOne,
dataTwo: Two,
}),
}
);
const data = await response.json();
//GET THE GIFT CARD CODE FROM THE RESPONSE OR HOWEVER YOU ARE DOING IT
// THEN CALL THAT FUNCTION WITH THE GIFT CARD CODE
handleApplyGiftCard(data.giftCardNumber);
};