I am attempting to set custom prices for my products for specific customers. I am getting the prices through a third party API based on product SKU. I have to do it this way because product prices are calculated on an internal system and is quite complex. I currently have this functionality working, but it is not optimized the way I want it to be. Right now I have my own custom module created that hooks into Magento\Catalog\Model\Product
in the etc/frontend/di.xml
file. This is ok when the customer is viewing the product page because it only ever makes one API call, but when viewing the category pages or searching for products there can be up to 36 requests made through the API on one page load; which is obviously not ideal.
My question is -- is it possible to get all of the SKUs of the products that are going to be loaded on the page and make a single API request to get all of the custom prices at once? If it is possible, how do I do that?
Magento version is 2.4.2
Current working code
etc/frontend/di.xml
<type name="Magento\Catalog\Model\Product">
<plugin name="customprice.product" type="Vendor\Module\Plugin\CustomPriceProduct" sortOrder="1" />
</type>
Plugin/CustomPriceProduct.php
public function afterGetPrice(Product $subject, $result) {
if(!$this->session->getInternalID()) {
return $result;
}
$sku = $subject->getData('sku');
$data = json_encode(array(
'assigned_no' => $this->session->getInternalID(),
'items' => [
array('sku' => $sku, 'order_qty' => 1)
]
));
$response = $this->api->customPrices($data);
$prices = json_decode($response['data']);
if($response['code'] == 200 && count($prices)) {
return $prices[0]->extension;
}
return $result;
}