2016-11-21 120 views
1

在其他api中,我使用「/ rest/V1/guest-carts/e3e1fd447e0e315dd761942cf949ce5d/items」方法獲取magento購物車物品。它效果很好,結果是magento 2 rest api:獲取帶有圖像的購物車項目

[ 
{ 
    "item_id": 100, 
    "sku": "abc-1", 
    "qty": 1, 
    "name": "Product one", 
    "price": 19, 
    "product_type": "simple", 
    "quote_id": "e3e1fd447e0e315dd761942cf949ce5d" 
}, 
{ 
    "item_id": 101, 
    "sku": "abc-2", 
    "qty": 1, 
    "name": "Product two", 
    "price": 54, 
    "product_type": "simple", 
    "quote_id": "e3e1fd447e0e315dd761942cf949ce5d" 
} 
] 

現在我想獲得列表中每個產品的圖像(可能是縮略圖圖像)。有什麼辦法可以達到這個結果嗎?

回答

0
<?php 
namespace Namespace\Modulename\Controller\filename; 


class customapi extends \Magento\Framework\App\Action\Action 
{ 
     public function __construct(
      \Magento\Framework\App\Action\Context $context, 
      \Magento\Checkout\Model\Cart $checkoutCart, 
      \Magento\Customer\Model\Customer $customer, 
      \Magento\Catalog\Model\Product $catalog, 
      \Magento\Directory\Model\Currency $currency, 
      \Magento\Store\Model\StoreManagerInterface $storeManager, 
      \Magento\Catalog\Helper\Image $imageHelper 
     ) { 
      $this->checkoutCart = $checkoutCart; 
      $this->customer = $customer; 
      $this->catalog = $catalog; 
      $this->currency = $currency; 
      $this->storeManager = $storeManager; 
      $this->imageHelper = $imageHelper; 
      parent::__construct($context); 
     } 
     public function execute() 
     { 
       $customerId =$this->getRequest()->getParam('customerid'); 

      if ($customerId) { 

       $customer = $this->customer->load($customerId); 
       try{ 
        $cart = $this->checkoutCart->getQuote(); 

        if(!count($cart->getAllItems())): 
         echo json_encode(array('status'=>'success','message'=>"No item in your cart")); 
        exit; 
        endif; 
        $product_model = $this->catalog; 

        $baseCurrency = $this->storeManager->getStore()->getBaseCurrencyCode(); 
        $currentCurrency = $this->currency; 

        foreach ($cart->getAllVisibleItems() as $item) { 

         $productName= array(); 
         $productName['image'] =$this->imageHelper 
              ->init($item,'product_page_image_large') 
              ->setImageFile($item->getFile()) 
              ->resize('100','100') 
              ->getUrl(); 
         $product['product'][] = $productName; 

        }   

        echo json_encode(array('status'=>'success','message'=>$product)); 

       } 
       catch(exception $e) 
       { 
        echo json_encode(array('status'=>'error','message'=> $e->getMessage())); 
       } 
      } 
     } 
} 
1

按照步驟通過Rest API獲取產品縮略圖圖像在沒有POST任何值的Rest API中。它將採用當前產品的縮略圖圖像。 REST URL:

方法:GET - >休息/ V1 /客推車/ 3f260b6e818d2fe56894ed6222e433f8 /項目

創建一個模塊:代碼/ VENDOR_NAME/MODULE_NAME/

registration.php的

<?php 

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE, 
    'Hopescode_Mobileshop', 
    __DIR__ 
); 

創建module.xml

<?xml version="1.0"?> 
<!-- 
/** 
* Copyright © 2018-2019 Hopescode. All rights reserved. 
*/ 
--> 

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd"> 
     <module name="Hopescode_Mobileshop" setup_version="1.0.0" /> 
    </config> 

科瑞Ë等/ extension_attributes.xml

<?xml version="1.0"?> 
<!-- 
/** 
* Copyright © 2018-2019 Hopescode, Inc. All rights reserved. 
* See COPYING.txt for license details. 
*/ 
--> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd"> 

    <extension_attributes for="Magento\Quote\Api\Data\CartItemInterface"> 
     <attribute code="image_url" type="string" /> 
    </extension_attributes> 

</config> 

創建等/ events.xml

<?xml version="1.0"?> 
<!-- 
/** 
* Copyright © 2018-2019 Hopescode, Inc. All rights reserved. 
* See COPYING.txt for license details. 
*/ 
--> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> 
    <event name="sales_quote_load_after"> 
     <observer name="hopescode_mobileshop_sales_quote_load_after" instance="Hopescode\Mobileshop\Observer\ProductInterface" /> 
    </event> 
</config> 

創建觀察報:VENDOR_NAME/Mocule_name /觀察員/

ProductInterface.php

<?php 
/** 
* Copyright © 2018-2019 Hopescode, Inc. All rights reserved. 
* See COPYING.txt for license details. 
*/ 
namespace Hopescode\Mobileshop\Observer; 

use Magento\Framework\Event\ObserverInterface; 
    use Magento\Catalog\Api\ProductRepositoryInterfaceFactory as ProductRepository; 
    use Magento\Catalog\Helper\ImageFactory as ProductImageHelper; 
    use Magento\Store\Model\StoreManagerInterface as StoreManager; 
    use Magento\Store\Model\App\Emulation as AppEmulation; 
    use Magento\Quote\Api\Data\CartItemExtensionFactory; 

    class ProductInterface implements ObserverInterface 
    { 
     /** 
     * @var ObjectManagerInterface 
     */ 
     protected $_objectManager; 

     /** 
     * @var ProductRepository 
     */ 
     protected $productRepository; 

     /** 
     *@var \Magento\Catalog\Helper\ImageFactory 
     */ 
     protected $productImageHelper; 

     /** 
     *@var \Magento\Store\Model\StoreManagerInterface 
     */ 
     protected $storeManager; 

     /** 
     *@var \Magento\Store\Model\App\Emulation 
     */ 
     protected $appEmulation; 

     /** 
     * @var CartItemExtensionFactory 
     */ 
     protected $extensionFactory; 

     /** 
     * @param \Magento\Framework\ObjectManagerInterface $objectManager 
     * @param ProductRepository $productRepository 
     * @param \Magento\Catalog\Helper\ImageFactory 
     * @param \Magento\Store\Model\StoreManagerInterface 
     * @param \Magento\Store\Model\App\Emulation 
     * @param CartItemExtensionFactory $extensionFactory 
     */ 
     public function __construct(
      \Magento\Framework\ObjectManagerInterface $objectManager, 
      ProductRepository $productRepository, 
      ProductImageHelper $productImageHelper, 
      StoreManager $storeManager, 
      AppEmulation $appEmulation, 
      CartItemExtensionFactory $extensionFactory 
     ) { 
      $this->_objectManager = $objectManager; 
      $this->productRepository = $productRepository; 
      $this->productImageHelper = $productImageHelper; 
      $this->storeManager = $storeManager; 
      $this->appEmulation = $appEmulation; 
      $this->extensionFactory = $extensionFactory; 
     } 

    public function execute(\Magento\Framework\Event\Observer $observer, string $imageType = NULL) 
     { 
      $quote = $observer->getQuote(); 

      /** 
      * Code to add the items attribute to extension_attributes 
      */ 
      foreach ($quote->getAllItems() as $quoteItem) { 
       $product = $this->productRepository->create()->getById($quoteItem->getProductId()); 
       $itemExtAttr = $quoteItem->getExtensionAttributes(); 
       if ($itemExtAttr === null) { 
        $itemExtAttr = $this->extensionFactory->create(); 
       } 


       $imageurl =$this->productImageHelper->create()->init($product, 'product_thumbnail_image')->setImageFile($product->getThumbnail())->getUrl(); 



       $itemExtAttr->setImageUrl($imageurl); 
       $quoteItem->setExtensionAttributes($itemExtAttr); 
      } 
      return; 
     } 

     /** 
     * Helper function that provides full cache image url 
     * @param \Magento\Catalog\Model\Product 
     * @return string 
     */ 
     protected function getImageUrl($product, string $imageType = NULL) 
     { 
      $storeId = $this->storeManager->getStore()->getId(); 

      $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true); 
      $imageUrl = $this->productImageHelper->create()->init($product, $imageType)->getUrl(); 

      $this->appEmulation->stopEnvironmentEmulation(); 

      return $imageUrl; 
     } 

    } 

輸出:

[ 
    { 
     "item_id": 5, 
     "sku": "samplepro", 
     "qty": 1, 
     "name": "samplepro", 
     "price": 1500, 
     "product_type": "simple", 
     "quote_id": "3f260b6e818d2fe56894ed6222e433f8", 
     "extension_attributes": { 
      "image_url": "http://localhost/dashboard/myapi/pub/media/catalog/product/cache//beff4985b56e3afdbeabfc89641a4582/n/u/nutro_crunchy_real_apple.jpg" 
     } 
    } 
] 

之前檢查你出來說,如果你安裝你可以檢查你的VAR /生成/ Magento的/報價/原料藥/數據/ CartItemExtension.php具有這樣的價值的正確方法:

<?php 
namespace Magento\Quote\Api\Data; 

/** 
* Extension class for @see \Magento\Quote\Api\Data\CartItemInterface 
*/ 
class CartItemExtension extends \Magento\Framework\Api\AbstractSimpleObject implements \Magento\Quote\Api\Data\CartItemExtensionInterface 
{ 
    /** 
    * @return string|null 
    */ 
    public function getImageUrl() 
    { 
     return $this->_get('image_url'); 
    } 

    /** 
    * @param string $imageUrl 
    * @return $this 
    */ 
    public function setImageUrl($imageUrl) 
    { 
     $this->setData('image_url', $imageUrl); 
     return $this; 
    } 
} 
+0

謝謝,其實這個答案應該被接受,因爲這是正確的做法。 –

相關問題