craftcms/commerce-sagepay

"Using the legacy basket format" example in markdown does not work

andrewhawkes opened this issue · 0 comments

Description

The demo code supplied in the README.md for enabling product codes when using the legacy basket format for Sage 50 Accounts has a few problems:

  1. Typo of BaseGatewa should be BaseGateway
  2. Missing use for ItemBagEvent
  3. The Omnipay Item description is not sent to SagePay so the SKU needs to be added to the name instead
    (I have tested and confirmed that sending the SKU on the name works correctly with the Sage software)

I have supplied a working example at the bottom:

Current example from README:

use \craft\commerce\omnipay\base\Gateway as BaseGateway;

Event::on(BaseGateway::class, BaseGatewa::EVENT_AFTER_CREATE_ITEM_BAG, function(ItemBagEvent $itemBagEvent) {
    
    $orderLineItems = $itemBagEvent->order->getLineItems();

    /**
     * @var $item Item
    */
    foreach ($itemBagEvent->items as $key => $item) {

        if (!isset($orderLineItems[$key])) {
            return;
        }

        $orderLineItem  = $orderLineItems[$key];

        // Make sure that the description and price are the same as we are relying upon the order
        // of the Order Items and The OmniPay Item Bag to be the same
        if ($orderLineItem->getDescription() != $item->getDescription()) {
            return;
        }

        if ($orderLineItem->price != $item->getPrice()) {
            return;
        }

        $sku = $orderLineItem->getSku();

        // Place the SKU within [] as the Product Record for the Sage 50 Accounts Integration
        $description = '[' . $sku . ']' . $item->getDescription();
        $item->setDescription($description);
    }
});

Suggested change - working example

use craft\commerce\omnipay\base\Gateway as BaseGateway;
use craft\commerce\omnipay\events\ItemBagEvent;

Event::on(BaseGateway::class, BaseGateway::EVENT_AFTER_CREATE_ITEM_BAG, function(ItemBagEvent $itemBagEvent) {
    
    $orderLineItems = $itemBagEvent->order->getLineItems();

    /**
     * @var $item Item
    */
    foreach ($itemBagEvent->items as $key => $item) {

        if (!isset($orderLineItems[$key])) {
            return;
        }

        $orderLineItem  = $orderLineItems[$key];

        // Make sure that the description and price are the same as we are relying upon the order
        // of the Order Items and The OmniPay Item Bag to be the same
        if ($orderLineItem->getDescription() != $item->getDescription()) {
            return;
        }

        if ($orderLineItem->price != $item->getPrice()) {
            return;
        }

        $sku = $orderLineItem->getSku();

        // Place the SKU within [] as the Product Record for the Sage 50 Accounts Integration
        $name = '[' . $sku . ']' . $item->getDescription();
        $item->setName($name);
    }
});