-
-
Save chrisgrabinski/db99b2ac12641fbf3b8e to your computer and use it in GitHub Desktop.
// Dependencies | |
// - https://github.com/carolineschnapp/currencies | |
// Don't change currency if Cookie has been already set | |
if (Currency.cookie.read() == null) { | |
jQuery.ajax( { | |
url: '//freegeoip.net/json/', | |
type: 'GET', | |
dataType: 'jsonp', | |
success: function(location) { | |
if (location.country_code == 'TH') { // Default shop currency | |
$('[name=currencies][value=THB]').attr('checked', 'checked'); | |
} else if (location.country_code == 'JP') { // Secondary currency | |
$('[name=currencies][value=JPY]').attr('checked', 'checked'); | |
} else { // Fallback currency | |
$('[name=currencies][value=USD]').attr('checked', 'checked'); | |
} | |
// Let the scripts in 'currencies.liquid' handle the rest | |
$('[name=currencies]').change(); | |
} | |
} ); | |
} | |
// Based upon code by Ben Klinger (www.studiove.com) | |
// Source: https://ecommerce.shopify.com/c/shopify-discussion/t/auto-change-currency-based-on-location-tutorial-179134 |
Also interested in knowing where we place this code!
Guys can you please help me where to put this code on shopify so i can get this result on the store .
please help
I think adding it to the bottom of theme.liquid file just before the closing </body>
tag should work fine.
It won't work because the freegeoip service has been deprecated.
@nixoncode, replace freegeoip.net with ipgeolocation.io. Its free but requires signup to get API key
@nixoncode, replace freegeoip.net with ipgeolocation.io. Its free but requires signup to get API key
@ejaz-ahmed -
Do you have a working example of this using ipgeolocation query?
@nixoncode, replace freegeoip.net with ipgeolocation.io. Its free but requires signup to get API key
@ejaz-ahmed -
Do you have a working example of this using ipgeolocation query?
@nicholasroubal Here is the above code using ipgeolocation.io:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/ipgeolocation.min.js"></script>
<script>
if (Currency.cookie.read() == null) {
setAsync(false);
setFieldsParameter('country_code2');
// You can skip API_KEY argument if you're using request origin feature to authenticate your reqeusts.
getGeolocation(handleIPGeolocationResponse, 'YOUR_API_KEY_HERE');
}
function handleIPGeolocationResponse(location) {
if (location.country_code2 == 'TH') {
$('[name=currencies][value=THB]').attr('checked', 'checked'); // Default shop currency
} else if (location.country_code2 == 'JP') {
$('[name=currencies][value=JPY]').attr('checked', 'checked'); // Secondary currency
} else {
$('[name=currencies][value=USD]').attr('checked', 'checked'); // Fallback currency
}
// Let the scripts in 'currencies.liquid' handle the rest
$('[name=currencies]').change();
}
</script>
@usmanbinliaqat do i just copy the code you sent but put my api in the 'your api key here' section?
@Bemaiin. Yes, you can copy the above code as it is and use it after placing your API key in the code.
For more information regarding IPGeolocation API usage, you can take a look at the documentation here.
@usmanbinliaqat the api is free right and i dont have to pay and can run it on a live store?
@Bemaiin. Yes, this API is free to use but have upper monthly requests cap. You can check it on the pricing page here.
@usmanbinliaqat @chrisgrabinski thank you for the code. However, I believe Shopify updated the whole currency integration and I can't seem to get the code to work. We are using Prestige theme, and there is no currency.liquid file anymore. Any suggestions?
This is in the header:
`
The theme currency converter is used in lot of different places so to simply the code it's outputted here once
{%- if settings.currency_conversion_enabled or shop.enabled_currencies.size > 1 -%}
{%- capture currency_conversion_select -%}
{%- if shop.enabled_currencies.size > 1 -%}
{%- form 'currency', id: 'desktop_currency_form' -%}
{%- for currency in shop.enabled_currencies -%} <option value="{{ currency.iso_code }}" {% if cart.currency == currency %}selected="selected"{% endif %}>{{ currency.iso_code }} {%- endfor -%}
{%- endform -%}
{%- else -%}
{%- capture codes -%}USD,EUR,GBP,CAD,ARS,AUD,BBD,BDT,BSD,BHD,BRL,BOB,BND,BGN,BWP,MMK,KYD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,XPF,FJD,GHS,GTQ,GYD,GEL,HKD,HUF,ILS,ISK,INR,IDR,NIS,JMD,JPY,JOD,KZT,KES,KWD,LVL,LTL,MXN,MYR,MUR,MDL,MAD,MNT,MZN,ANG,NZD,NGN,NOK,OMR,PKR,PYG,PEN,PHP,PLN,QAR,RON,RUB,SAR,RSD,SCR,SGD,SYP,ZAR,KRW,LKR,SEK,CHF,TWD,THB,TZS,TTD,TRY,UAH,AED,UYU,VEB,VND,ZMK{%- endcapture -%} {%- assign supported_codes = settings.currency_conversion_supported_currencies | remove_first: shop.currency | upcase | split: ' ' | uniq -%} <option value="{{ shop.currency }}" selected="selected">{{ shop.currency }}</option> {%- for code in supported_codes -%} {%- if codes contains code -%} <option value="{{ code }}">{{ code }}</option> {%- endif -%} {%- endfor -%} </select> {%- endif -%} {%- render 'icon' with 'select-arrow' -%} </div> </div> {%- endcapture -%} {%- endif -%} `
Hi @kwibis,
We have another script to select a location based currency on a shopify store without redirection. Here is the snipper:
<script>
var allowedCountries = ['AU', 'CA', 'DK', 'GB', 'HK', 'JP', 'NZ', 'SG', 'US'];
var defaultCountry = 'GB';
var hasUserAlreadySetCurrency = sessionStorage.getItem('currency_set_by_user') === 'yes';
var cartCurrency = getCookieValue('cart_currency');
if (!hasUserAlreadySetCurrency) {
if (cartCurrency === defaultCurrency) {
var urlParameters = getURLParameters();
if (urlParameters.currency) {
sessionStorage.setItem('currency_set_by_user', 'yes');
}
} else {
sessionStorage.setItem('currency_set_by_user', 'yes');
}
}
hasUserAlreadySetCurrency = sessionStorage.getItem('currency_set_by_user') === 'yes';
if (!hasUserAlreadySetCurrency && cartCurrency === defaultCurrency) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (4 === this.readyState && 200 === this.status) {
var json = JSON.parse(this.responseText);
if (allowedCurrencies.includes(json.currency.code)) {
setCurrencyInURLParameter(json.currency.code);
}
}
}
httpRequest.open('GET', 'https://api.ipgeolocation.io/ipgeo?apiKey=YOUR_API_KEY&fields=currency', false);
httpRequest.setRequestHeader('Accept', 'application/json');
httpRequest.send();
}
function getCookieValue(cookieName) {
var cookiesArray = document.cookie.split(';');
var cookieValue = '';
cookieName = cookieName + '=';
for (var i = 0; i < cookiesArray.length; i++) {
var value = cookiesArray[i].trim();
if (value.indexOf(cookieName) === 0) {
cookieValue = value.substring(cookieName.length, value.length);
break;
}
}
return cookieValue;
}
function getURLParameters() {
var params = {};
var regex = /[?&]([^=#]+)=([^&#]*)/g;
var url = window.location.href;
var match;
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
function setCurrencyInURLParameter(currencyCode) {
sessionStorage.setItem('currency_set_by_user', 'yes');
setURLParameter('currency', currencyCode);
}
function setURLParameter(name, value) {
if (window.location.search) {
window.location.search = window.location.search + '&' + name + '=' + value;
} else {
window.location.search = '?' + name + '=' + value;
}
}
</script>
You can paste it in the liquid.theme file.
@usmanbinliaqat thanks for the update! Unfortunately it doesn't seem to work. Got something working but with redirect.
`
<script src="https://cdn.jsdelivr.net/npm/[email protected]/ipgeolocation.min.js"></script> <script> getGeolocation(handleIPGeolocationResponse, 'API-KEY'); function handleIPGeolocationResponse(location) { console.log(location.currency.code); // Let the scripts in 'currencies.liquid' handle the rest jQuery('button[value="'+location.currency.code+'"]:not([aria-current])').click(); //setCookie('hidebar', 'hide'); } function setCookie(key, value) { var expires = new Date(); expires.setTime(expires.getTime() + 604800); document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ';path=/'; } </script>`
Would like your script to work without redirect. I tried changing the top part to currencies:
<script> var allowedCurrencies = ['AUD', 'CAD', 'GBP', 'SEK', 'CHF', 'TTD', 'USD', 'EUR']; var defaultCurrency = 'GBP'; Still not working.Solved it with a little configuration and without API keys.
Check my script below.
https://gist.github.com/Drewberrysteph/e7f44d23d714617134ad7250d9149b06
@kwibis The above script doesn't redirect the user. It updates the currency if the visitor is from the allowed countries, else set to the default currency i.e., 'GBP'.
Here is the updated script using ipgeolocation.io API as suggested by @Drewberrysteph.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/ipgeolocation.min.js"></script>
<script>
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ';path=/';
}
function setLocalCurrency(response) {
if (response) {
setCookie('cart_currency', response.currency.code, '1');
}
}
_ipgeolocation.makeAsyncCallsToAPI(false);
_ipgeolocation.enableSessionStorage(true);
_ipgeolocation.setFields("currency");
_ipgeolocation.getGeolocation(setLocalCurrency, "YOUR_API_KEY");
</script>
@kwibis The above script doesn't redirect the user. It updates the currency if the visitor is from the allowed countries, else set to the default currency i.e., 'GBP'.
Here is the updated script using ipgeolocation.io API as suggested by @Drewberrysteph.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/ipgeolocation.min.js"></script> <script> function setCookie(key, value, expiry) { var expires = new Date(); expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000)); document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ';path=/'; } function setLocalCurrency(response) { if (response) { setCookie('cart_currency', response.currency.code, '1'); } } _ipgeolocation.makeAsyncCallsToAPI(false); _ipgeolocation.enableSessionStorage(true); _ipgeolocation.setFields("currency"); _ipgeolocation.getGeolocation(setLocalCurrency, "YOUR_API_KEY"); </script>
Can it be somehow modified for location based content. I am trying this but not getting what i want
@usmanbinliaqat thanks a lot! this seems to be working. One problem, it only works after the first page view. Any chance this can be fixed? Or does that mean, page reload?
@kwibis The above script doesn't redirect the user. It updates the currency if the visitor is from the allowed countries, else set to the default currency i.e., 'GBP'.
Here is the updated script using ipgeolocation.io API as suggested by @Drewberrysteph.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/ipgeolocation.min.js"></script> <script> function setCookie(key, value, expiry) { var expires = new Date(); expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000)); document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ';path=/'; } function setLocalCurrency(response) { if (response) { setCookie('cart_currency', response.currency.code, '1'); } } _ipgeolocation.makeAsyncCallsToAPI(false); _ipgeolocation.enableSessionStorage(true); _ipgeolocation.setFields("currency"); _ipgeolocation.getGeolocation(setLocalCurrency, "YOUR_API_KEY"); </script>
Thanks for that. Seems though that it only works second time. The first time you go to a link it will not change currency. If you refresh, then it will. Is there any way to fix this? Thanks!
@leeban17 your code has been working great! Any idea on how to work with the new currency selector from shopify?
@leeban17 your code has been working great! Any idea on how to work with the new currency selector from Shopify?
I built a free auto currency and location app that works with the new currency & region selector of Shopify themes. It's inspired by discussions here with all code optimized for performance.
Hi, Can you please give more instruction ? Where I paste this code ?