Magento 2 : How to get Shipping Methods for Specific Customer Group

 To get the available shipping methods for a specific customer group in Magento 2, you can follow these steps:

  1. Inject the necessary dependencies in your class constructor or method. You will need the following dependencies:
php
use MagentoCustomerApiGroupRepositoryInterface; use MagentoQuoteApiShippingMethodManagementInterface; use MagentoQuoteModelQuoteAddressRateCollectorInterface;
  1. Create class properties for the injected dependencies:
php
protected $groupRepository; protected $shippingMethodManagement; protected $rateCollector;
  1. Initialize the dependencies in the constructor:
php
public function __construct( GroupRepositoryInterface $groupRepository, ShippingMethodManagementInterface $shippingMethodManagement, RateCollectorInterface $rateCollector ) { $this->groupRepository = $groupRepository; $this->shippingMethodManagement = $shippingMethodManagement; $this->rateCollector = $rateCollector; }
  1. Use the following code to retrieve the available shipping methods for a specific customer group:
php
$customerGroupId = 1; // Replace with the desired customer group ID try { $group = $this->groupRepository->getById($customerGroupId); $rateRequest = $this->rateCollector->createRateRequest(); $rateRequest->setAllItems([]); $rateRequest->setDestCountryId('US'); // Replace with the desired country ID $rateRequest->setDestPostcode('12345'); // Replace with the desired postal code $rateRequest->setCustomerGroupId($group->getId()); $shippingMethods = $this->shippingMethodManagement->getList($rateRequest); foreach ($shippingMethods as $shippingMethod) { echo $shippingMethod->getMethodCode(); // Output the shipping method code } } catch (Exception $e) { echo $e->getMessage(); // Handle any exceptions that occur }

Make sure to replace the $customerGroupId, 'US', and '12345' with the appropriate values for your specific use case.

By executing this code, you will retrieve the available shipping methods for the specified customer group in Magento 2.

Puneet Kumar Magento Developer
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply