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

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

8 hours ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

9 hours ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

5 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 week ago