Skip to content

Redirect to a specific store

I’m trying to redirect on a specific store based on geoip. I added this code on index.php on my root, but I can’t understand why it doesn’t work. I get “main.ERROR: The store that was requested wasn’t found. Verify the store and try again.” but the store exist. Could you help me?

use MagentoFrameworkAppBootstrap;
use MagentoStoreModelStoreManagerInterface;
use MagentoFrameworkAppHttpContext as HttpContext;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

// Store manager
$storeManager = $objectManager->get(StoreManagerInterface::class);
$httpContext = $objectManager->get(HttpContext::class);

// GeoIP
$params = $_SERVER;
$resp = @file_get_contents('http://pro.ip-api.com/json/' . $_SERVER["REMOTE_ADDR"] . '?key=xxxxxxxxx');

if ($resp) {
    $obj = json_decode($resp);
    if ($obj && $obj->status === 'success' && isset($obj->countryCode)) {
        $countryCode = $obj->countryCode;

        if ($_SERVER['HTTP_HOST'] == 'www.xxxx' || $_SERVER['HTTP_HOST'] == 'xxxxx') {
            $storeCode = ($countryCode === 'IT') ? 'xx1' : 'xx2';
        } else {
            $storeCode = ($countryCode === 'IT') ? 'xx3' : 'xx4';
        }

        // Imposta lo store view corrente e aggiorna il contesto HTTP
        try {
            $storeManager->setCurrentStore($storeCode);
            $httpContext->setValue(StoreManagerInterface::CONTEXT_STORE, $storeManager->getStore()->getId());
        } catch (MagentoFrameworkExceptionNoSuchEntityException $e) {
            
        }
    }
}

// Avvia l'applicazione Magento
$app = $bootstrap->createApplication('MagentoFrameworkAppHttp');
$bootstrap->run($app);