How To

How to Set Notify Customers When Out of Stock Product is Back in Stock Using REST API?

Hello, Magento mates. ?

Welcome to MageComp’s Magento tutorials.

Sometimes, the product/s your customer is willing to buy may be out of stock, and to prevent them from frequently visiting to check the product availability and leaving your website disappointedly, you can choose to notify them about the out of stock products that are restocked again.

Today, in this new Magento tutorial, we will learn to set automated notifications for customers about out of stock Magento 2 products that are back in stock using REST API.

Steps to Set the Customer Notifications for Back in Stock Products

Step 1 – 

First, we need to create a webapi.xml” file inside our Magento 2 extension by following this path ?

app/code/Vendor/Extension/etc

Enter the following code. ?

<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
   <route url="/V1/productalertstock/add/:productId" method="POST">
        <service class="Vendor\Extension\Api\ProductAlertManagementInterface" method="addProductAlertStock"/>
        <resources>
            <resource ref="self" />
        </resources>
        <data>
            <parameter name="customerId" force="true">%customer_id%</parameter>
        </data>
    </route>
</routes>

Step 2 – 

After this, we need to create a “di.xml” file inside our extension by following this path. ?

app/code/Vendor/Extension/etc

Then, enter the following code.?

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Vendor\Extension\Api\ProductAlertManagementInterface" type="Vendor\Extension\Model\ProductAlert"/>
</config>

Step 3 –

Once again, we need to create a “ProductAlertManagementInterface.php” file in the following extension path. ?

app/code/Vendor/Extension/Api

Then, enter the following code. ?

<?php
namespace Vendor\Extension\Api;
use Exception;

/**
 * Interface ProductAlertManagementInterface
 * @api
 */interface ProductAlertManagementInterface
{
    /**
     * Return true if product Added to Alert.
     *
     * @param int $customerId
     * @param int $productId
     * @return bool true on success
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */    public function addProductAlertStock($customerId, $productId);

}

Step 4 – 

After that, we need to create a “ProductAlert.php” file in our following extension path. ?

app/code/Vendor/Extension/Model

Now, enter the following code. ?

<?php

namespace Vendor\Extension\Model;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;
use Magento\ProductAlert\Model\StockFactory;

use Vendor\Extension\Api\ProductAlertManagementInterface;

class ProductAlert implements ProductAlertManagementInterface
{
    protected $productRepository;
    private $storeManager;
    protected $stockFactory;

    public function __construct(
        ProductRepositoryInterface $productRepository,
        StoreManagerInterface $storeManager,
        StockFactory $stockFactory
    ) {
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
        $this->stockFactory = $stockFactory;
    }
    
    public function addProductAlertStock($customerId, $productId)
    {
        try {
        
            /* @var $product \Magento\Catalog\Model\Product */            $product = $this->productRepository->getById($productId);
            $store = $this->storeManager->getStore();
            /** @var \Magento\ProductAlert\Model\Stock $model */            $model = $this->stockFactory->create()
                ->setCustomerId($customerId)
                ->setProductId($product->getId())
                ->setWebsiteId($store->getWebsiteId())
                ->setStoreId($store->getId());
            $model->save();
            return true;
        } catch (NoSuchEntityException $noEntityException) {
            return false;
        }
    } 
}

Output ?

Please Note That

We have defined our API end point in etc/webapi.xml file.

For Add product, we have /V1/productalertstock/add/:productId.

The complete URL will be http://{Magento2Root}/rest/V1/productalertstock/add/123

To access the above API, you need a Customer token, which can be obtained by

http://{Magento2Root}/rest/V1/integration/customer/token

Conclusion

So, this was it. By following the steps mentioned above, you can easily set notifications to notify your customers about product restocking of out-of-stock products. The practice of notifying your customers about products being back in stock will help you gain their trust and increase their loyalty toward your brand.

Hope this tutorial was helpful to you. If you face any trouble with these steps, you can comment your queries in the comment section or contact us through our official Facebook page or hire an experienced Magento 2 developer to help you with the trouble.

Thank you for reading.

Happy Coding!!!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

1 day ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

2 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

4 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

6 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

7 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

7 days ago