Retrieving Gift Card Code and Amount in Magento
When working with Magento, retrieving gift card information from an order can be a bit tricky compared to other promotional codes or discounts. The built-in functions for getting coupon codes don’t directly extend to gift cards.
Understanding the Gift Card Structure
In Magento, gift cards are stored as separate entities (sales_order_giftcard). They are linked to orders through the sales_order entity’s giftcert_code field. This means you need to join these two tables to get the full picture of a gift card used in an order.
Getting Started: Loading the Order Model
First, let’s ensure you have loaded your order model correctly:
$order = Mage::getModel('sales/order')->load($orderId);
Replace $orderId with the ID or increment ID of the order you want to work with. This loads a full sales_order object into memory.
Retrieving Gift Card Code
To retrieve the gift card code, use the following snippet:
$giftCardCode = $order->getGiftcardcode();
This returns the unique code assigned to the gift card that was applied to this order.
Retrieving Gift Card Amount
Getting the amount is a bit more complex. You need to load the sales_order_giftcard model and join it with your current order:
$giftCard = Mage::getModel('sales/order_giftcard')->loadByCode($order->getGiftcardcode());
if ($giftCard->getId()) {
$giftCardAmount = $giftCard->getBalance();
}
Here’s what happening:
loadByCode()retrieves the gift card model based on its code.$giftCard->getId()checks if a valid gift card was found. If it returns 0, no valid gift card was used in this order.$giftCard->getBalance()gives you the remaining balance of the gift card after being partially used or completely redeemed.
Putting It All Together
Here’s your complete function to retrieve both the gift card code and amount:
public function getGiftCardDetails($orderId)
{
$order = Mage::getModel('sales/order')->load($orderId);
$giftCardCode = $order->getGiftcardcode();
if ($order->getGiftcardcode()) {
$giftCard = Mage::getModel('sales/order_giftcard')->loadByCode($giftCardCode);
if ($giftCard->getId()) {
return [
'code' => $giftCardCode,
'amount' => $giftCard->getBalance(),
];
}
}
return null;
}
This function returns an associative array with the code and remaining balance if a gift card was used. If no gift card is found, it returns null.
Conclusion
While Magento’s built-in functions don’t directly support retrieving gift card data from orders, you can achieve this by loading the relevant models and joining them. This requires a bit of extra code but gives you full control over the gift card details.
Remember to test your function thoroughly, especially with edge cases like partially used gift cards or gift cards that have been redeemed completely.
For more advanced Magento development tutorials and tips, check out our resources at Laravel Company. We cover everything from custom module development to complex integrations.