Skip to content

Instantly share code, notes, and snippets.

@chrisgrabinski
Last active January 16, 2023 20:04
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save chrisgrabinski/db99b2ac12641fbf3b8e to your computer and use it in GitHub Desktop.
Save chrisgrabinski/db99b2ac12641fbf3b8e to your computer and use it in GitHub Desktop.
(Shopify) Automatically change a shop's currency based on the customer's geolocation
// 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
@phonesite
Copy link

Hi, Can you please give more instruction ? Where I paste this code ?

@vemundeldegard
Copy link

Also interested in knowing where we place this code!

@rpvaghela
Copy link

Guys can you please help me where to put this code on shopify so i can get this result on the store .
please help

@nixoncode
Copy link

nixoncode commented Aug 18, 2018

I think adding it to the bottom of theme.liquid file just before the closing </body> tag should work fine.

@nixoncode
Copy link

It won't work because the freegeoip service has been deprecated.

@ejaz-ahmed
Copy link

@nixoncode, replace freegeoip.net with ipgeolocation.io. Its free but requires signup to get API key

@nicholasroubal
Copy link

nicholasroubal commented Oct 14, 2019

@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?

@usmanl
Copy link

usmanl commented Oct 15, 2019

@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/ip-geolocation-api-jquery-sdk@1.0.6/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>

@BabyQuantML
Copy link

@usmanbinliaqat do i just copy the code you sent but put my api in the 'your api key here' section?

@usmanl
Copy link

usmanl commented Sep 30, 2020

@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.

@BabyQuantML
Copy link

@usmanbinliaqat the api is free right and i dont have to pay and can run it on a live store?

@usmanl
Copy link

usmanl commented Oct 1, 2020

@Bemaiin. Yes, this API is free to use but have upper monthly requests cap. You can check it on the pricing page here.

@kwibis
Copy link

kwibis commented Jan 25, 2021

@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 -%} `

@usmanl
Copy link

usmanl commented Feb 4, 2021

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.

@kwibis
Copy link

kwibis commented Feb 6, 2021

@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/ip-geolocation-api-jquery-sdk@1.0.6/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.

@Drewberrysteph
Copy link

Solved it with a little configuration and without API keys.
Check my script below.

https://gist.github.com/Drewberrysteph/e7f44d23d714617134ad7250d9149b06

@usmanl
Copy link

usmanl commented Feb 17, 2021

@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/ip-geolocation-api-jquery-sdk@1.1.0/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>

@hammadCodes
Copy link

@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/ip-geolocation-api-jquery-sdk@1.1.0/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

@kwibis
Copy link

kwibis commented Feb 25, 2021

@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?

@leeban17
Copy link

leeban17 commented Apr 5, 2021

@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/ip-geolocation-api-jquery-sdk@1.1.0/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!

@kwibis
Copy link

kwibis commented Mar 1, 2022

@leeban17 your code has been working great! Any idea on how to work with the new currency selector from shopify?

@mingfengwan
Copy link

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment