Changing Magento 2 Currency Based on User Location
In your Magento 2 store, you want to set the default currency based on the visitor’s location. By default, the currency is set to USD, but for visitors from Saudi Arabia, you want to display transactions in Riyal (SAR). Let’s explore how to implement this functionality.
Step 1: Identify Visitor’s Country
The first step is to determine the country of your visitor. You can use an API like ipapi or ipstack to get geographical information based on their IP address. For this guide, let’s assume you’re using ipapi.
Create a custom controller to fetch the country code:
// File: app/code/Vendor/Module/etc/frontend/routes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="vendor_module" frontName="vendor_module">
<area>frontend</area>
</route>
</router>
</config>
Create the controller:
// File: app/code/Vendor/Module/Controller/Index/GetCountry.php
namespace Vendor\Module\Controller\Index;
class GetCountry extends \Magento\Framework\App\Action\Action
{
protected $httpClientFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework Http\Client\Curl $httpClientFactory
) {
$this->httpClientFactory = $httpClientFactory;
parent::__construct($context);
}
public function execute()
{
$client = $this->httpClientFactory->create();
$client->setUri('https://ipapi.co/json/');
$response = $client->send();
if ($response->isSuccessful()) {
$data = json_decode($response->getBody());
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData(['country_code' => strtoupper($data->country_code)]);
}
return $this->resultFactory->create(ResultFactory::TYPE_RAW, 'Error: ' . $response->getReasonPhrase(), ResultFactory::HTTP_FORBIDDEN);
}
}
Step 2: Set Currency Based on Country Code
Now that you have the country code, you need to set the currency accordingly. You can create a custom observer for Magento’s controller_action_predispatch event.
// File: app/code/Vendor/Module/etc/events.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/events.xsd">
<event name="controller_action_predispatch">
<observer name="vendor_module_set_currency" instance="Vendor\Module\Model\SetCurrency"/>
</event>
</config>
Create the observer:
// File: app/code/Vendor/Module/Model/SetCurrency.php
namespace Vendor\Module\Model;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
class SetCurrency implements \Magento\Framework\Event\ObserverInterface
{
protected $httpClientFactory;
protected $_storeManager;
public function __construct(
RequestInterface $request,
TimezoneInterface $localeDate,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->request = $request;
$this->_localeDate = $localeDate;
$this->_storeManager = $storeManager;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
if ($this->request->getActionName() == 'index') {
$countryCode = strtoupper($this->request->getParam('country_code', ''));
$currentStoreId = $this->_storeManager->getStore()->getId();
switch ($countryCode) {
case 'SA':
$currency = 'SAR';
break;
default:
$currency = 'USD';
}
$this->_storeManager->setCurrentStore($currentStoreId);
$this->_storeManager->getStore()->setCurrentCurrency($currency);
return $this;
}
}
}
This observer checks the country_code parameter passed to your controller and sets the currency accordingly.
Conclusion
By following these steps, you can successfully set the default currency based on the visitor’s country in your Magento 2 store. Remember to replace “Vendor” with your actual namespace in the file paths and class names.
For more advanced customizations and Magento extensions, consider exploring Laravel Company, a leading provider of e-commerce solutions and services for businesses of all sizes.