unseenwolf Hi I have done this functionality for my client to auto-switch currency and auto-detect language. using ipinfo.io
Note: I modified the core function for now
Create new Function to get the country code from IP:
if (! function_exists('get_country_code_from_IP')) {
function get_country_code_from_IP(): ?string
{
$ip = $_SERVER['REMOTE_ADDR'];
$cacheKey = "country_code_for_{$ip}";
// Check if country code for this IP is already cached
if (Cache::has($cacheKey)) {
return Cache::get($cacheKey);
}
$apiKey = 'a0a6428cfbf7c0';
$url = "https://ipinfo.io/{$ip}?token={$apiKey}";
try {
// Fetch data from ipinfo.io
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['country'])) {
$countryCode = strtoupper($data['country']);
// Cache the country code for 24 hours
Cache::put($cacheKey, $countryCode, now()->addDay());
return $countryCode;
}
} catch (Exception $e) {
// Handle exceptions if needed
// Log::error("IP info API failed: " . $e->getMessage());
}
return null;
}
}
then update this function
Path: platform\plugins\ecommerce\src\Supports\CurrencySupport.php
public function detectedCurrencyCode(): string|null
{
$currencies = $this->countryCurrencies();
// new code start
$countryCode = get_country_code_from_IP();
if ($countryCode) {
return Arr::get($currencies, $countryCode);
}
// new code end
// Fallback to HTTP_ACCEPT_LANGUAGE if `ipinfo.io` doesn't work
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
if (extension_loaded('intl') && class_exists('Locale')) {
$httpAcceptLanguage = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
$languages = Language::getListLanguages();
foreach ($languages as $language) {
if ($language[1] == $httpAcceptLanguage) {
$httpAcceptLanguage = $language[4];
break;
}
}
} else {
$httpAcceptLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
return Arr::get($currencies, strtoupper(substr($httpAcceptLanguage, 0, 2)));
}
return null;
}
@Botble please give us the hooks to do that. if you provide hoos then I have a plane to make the plugin for language and currency based on location.