Update Product QTY right before place order from external remote API

All we need is an easy explanation of the problem, so here it is.

We want to update and check product quantity when user clicks on “Place Order” button. If product is outofstock in remote API and get 0 qty then user should not able to “Place Order” and display default error message.

Default Magento works that way and show message if we update qty through backend while customer is on “Place Order”.

Please suggest.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can create a custom extension with following 2 files.


<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">s
    <type name="Magento\Checkout\Model\PaymentInformationManagement">
        <plugin name="update_qty_from_api" type="{Vendor}\{Module}\Plugin\UpdateQtyFromApi" />



namespace {Vendor}\{Module}\Plugin;

use Magento\Quote\Model\QuoteFactory;

class UpdateQtyFromApi
    public function __construct(
        QuoteFactory $quoteFactory,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
    ) {
        $this->quoteFactory = $quoteFactory;
        $this->stockRegistry = $stockRegistry;

    public function beforeSavePaymentInformationAndPlaceOrder(
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress = null

        return [$cartId, $paymentMethod, $billingAddress];

    public function callApi($cartId)
        $quote = $this->quoteFactory->create()->load($cartId);

        $quoteItems = $quote->getAllItems();

        foreach ($quoteItems as $item) {
            $sku = $item->getProduct()->getSku();
            $qty = $this->getQtyFromCurlCall($sku);

            $this->updateQty($sku, $qty);

    public function getQtyFromCurlCall($sku)
        // make your curl call here to get qty based on sku, and return that qty
        return 0;

    public function updateQty($sku, $qty)
        $stockItem = $this->stockRegistry->getStockItemBySku($sku);
        $this->stockRegistry->updateStockItemBySku($sku, $stockItem);

Replace {Vendor} and {Module} with your actual vendor and module name. And also add your condition accordingly in code. This will not allow user to place order if your condition does not match with your API.

Hope this helps you !!!

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply