添加 customer_balance_amount 到 Magento 2 的订单 REST API

Adding customer_balance_amount to Magento 2's Order REST API

默认情况下,Magento 的订单 REST API 不会提交用于订单的商店信用额度(customer_balance_amount 数据库中的列)。我需要将其公开给 API 界面,但目前还不能。我尝试了两种方法:

http://magehit.com/blog/how-to-get-value-of-custom-attribute-on-magento-2-rest-api/ - 使用观察者,但这似乎对 API 数据

没有任何反映

http://www.ipragmatech.com/extend-magento2-rest-api-easy-steps/ - 我成功尝试过,但它实际上涉及创建一个新的 ednpoint 而不是 overriding/extending 当前的 API.

我实际上能够通过直接更改模块销售核心模块中的 OrderInterface 和 Order 模型来重现它,但我想通过 "proper" 方式而不是修改核心来实现。

如果有人分享一些如何做到这一点的知识,我将不胜感激。

编辑:添加使解决方案有效的代码,但目标是使其成为正确的方法,而不是像这样编辑核心文件:

vendor/magento/module-sales/Api/Data/OrderInterface.php:

/*
 * Customer Balance Amount
 */
const CUSTOMER_BALANCE_AMOUNT = 'customer_balance_amount';


/**
 * Returns customer_balance_amount
 *
 * @return float Customer Balance Amount
 */
public function getCustomerBalanceAmount();


/**
 * Sets the customer_balance_amount for the order.
 *
 * @param float $amount
 * @return $this
 */
public function setCustomerBalanceAmount($amount);

vendor/magento/module-sales/model/Order.php:

/**
 * Returns customer_balance_amount
 *
 * @return float
 */
public function getCustomerBalanceAmount()
{
    return $this->getData(OrderInterface::CUSTOMER_BALANCE_AMOUNT);
}


/**
 * Sets the customer_balance_amount for the order.
 *
 * @param float $amount
 * @return $this
 */
public function setCustomerBalanceAmount($amount)
{
    return $this->setData(OrderInterface::CUSTOMER_BALANCE_AMOUNT, $amount);
}

此致, 亚历克斯

看起来这实际上是一个错误,因为 Magento 确实在 vendor/magento/module-customer-balance/etc/extension_attributes.xml

中将余额列定义为扩展属性

查看 GiftMessage 模块,方法是通过插件。

vendor/magento/module-gift-message/etc/di.xml

<type name="Magento\Sales\Api\OrderRepositoryInterface">
    <plugin name="save_gift_message" type="Magento\GiftMessage\Model\Plugin\OrderSave"/>
    <plugin name="get_gift_message" type="Magento\GiftMessage\Model\Plugin\OrderGet"/>
</type>

\Magento\GiftMessage\Model\Plugin\OrderGet

/**
 * Get gift message for order
 *
 * @param \Magento\Sales\Api\Data\OrderInterface $order
 * @return \Magento\Sales\Api\Data\OrderInterface
 */
protected function getOrderGiftMessage(\Magento\Sales\Api\Data\OrderInterface $order)
{
    $extensionAttributes = $order->getExtensionAttributes();
    if ($extensionAttributes && $extensionAttributes->getGiftMessage()) {
        return $order;
    }

    try {
        /** @var \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage */
        $giftMessage = $this->giftMessageOrderRepository->get($order->getEntityId());
    } catch (NoSuchEntityException $e) {
        return $order;
    }

    /** @var \Magento\Sales\Api\Data\OrderExtension $orderExtension */
    $orderExtension = $extensionAttributes ? $extensionAttributes : $this->orderExtensionFactory->create();
    $orderExtension->setGiftMessage($giftMessage);
    $order->setExtensionAttributes($orderExtension);

    return $order;
}