Umbraco Commerce
CMSCloudHeartcoreDXP
15.latest
15.latest
  • Umbraco Commerce Documentation
  • Release Notes
    • v15.1.0-Rc
    • v15.0.0-Rc
  • Commerce Products
    • Commerce Packages
    • Commerce Payment Providers
    • Commerce Shipping Providers
  • Getting Started
    • Requirements
    • Installation
    • Licensing
    • Configuration
    • User Interface
  • Upgrading
    • Upgrading Umbraco Commerce
    • Version Specific Upgrade Notes
    • Migrate from Vendr to Umbraco Commerce
      • Migrate Umbraco Commerce Checkout
      • Migrate custom Payment Providers
  • Tutorials
    • Build a Store in Umbraco using Umbraco Commerce
      • Installation
      • Creating a Store
        • Configuring your Store
      • Creating your first Product
      • Implementing a Shopping Cart
        • Using the Umbraco.Commerce.Cart Drop-in Shopping Cart
        • Creating a Custom Shopping Cart
      • Implementing a Checkout Flow
        • Using the Umbraco.Commerce.Checkout Drop-in Checkout Flow
        • Creating a Custom Checkout Flow
      • Configuring Store Access Permissions
  • How-To Guides
    • Overview
    • Configure SQLite support
    • Use an Alternative Database for Umbraco Commerce Tables
    • Customizing Templates
    • Configuring Cart Cleanup
    • Limit Order Line Quantity
    • Implementing Product Bundles
    • Implementing Member Based Pricing
    • Implementing Dynamically Priced Products
    • Implementing Personalized Products
    • Implementing a Currency Switcher
    • Building a Members Portal
    • Order Number Customization
    • Create an Order via Code
  • Key Concepts
    • Get to know the main features
    • Base Currency
    • Calculators
    • Currency Exchange Rate Service Provider
    • Dependency Injection
    • Discount Rules / Rewards
    • Events
      • List of validation events
      • List of notification events
    • Fluent API
    • Order Calculation State
    • Payment Forms
    • Payment Providers
    • Pipelines
    • Price/Amount Adjustments
    • Price Freezing
    • Product Adapters
    • Product Bundles
    • Product Variants
      • Complex Variants
    • Properties
    • ReadOnly and Writable Entities
    • Sales Tax Providers
    • Search Specifications
    • Settings Objects
    • Shipping Package Factories
    • Shipping Providers
    • Shipping Range/Rate Providers
    • Tax Sources
    • UI Extensions
      • Analytics Widgets
      • Entity Quick Actions
      • Order Line Actions
      • Order Properties
      • Order Collection Properties
      • Order Line Properties
      • Store Menu Items
    • Umbraco Properties
    • Unit of Work
    • Umbraco Commerce Builder
    • Webhooks
  • Reference
    • Stores
    • Shipping
      • Fixed Rate Shipping
      • Dynamic Rate Shipping
      • Realtime Rate Shipping
    • Payments
      • Configure Refunds
      • Issue Refunds
    • Taxes
      • Fixed Tax Rates
      • Calculated Tax Rates
    • Storefront API
      • Endpoints
        • Order
        • Checkout
        • Product
        • Customer
        • Store
        • Currency
        • Country
        • Payment method
        • Shipping method
        • Content
    • Management API
    • Go behind the scenes
    • Telemetry
Powered by GitBook
On this page
  • Configure Countries and Currencies
  • Create a Currency Switcher Component
  • Handle Switching Currencies
  • Result

Was this helpful?

Edit on GitHub
Export as PDF
  1. How-To Guides

Implementing a Currency Switcher

Learn how to implement a currency switcher in Umbraco Commerce.

PreviousImplementing Personalized ProductsNextBuilding a Members Portal

Last updated 1 month ago

Was this helpful?

In a globalized world, it is essential to provide users with the ability to switch between different currencies. This feature is especially important for e-commerce websites that cater to customers from different countries.

In this guide, you can learn how to implement a currency switcher in Umbraco Commerce.

In this guide, it is assumed that each country has a single currency. If your store supports multiple currencies per country, you must adjust the implementation accordingly.

Configure Countries and Currencies

  1. Define the countries and currencies you want to support, in the Umbraco backoffice.

  1. Navigate to the Content section.

  2. Populate the product prices for each currency.

Create a Currency Switcher Component

A partial view is used on the frontend to allow users to toggle between existing currencies.

This is done by creating a CurerrencySwitcher.cshtml partial with the following implementation:

CurerrencySwitcher.cshtml
@using Umbraco.Commerce.Core.Api;
@using Umbraco.Commerce.SwiftShop.Extensions;
@inject IUmbracoCommerceApi UmbracoCommerceApi
@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage

@{
    var store = Model.GetStore();
    var countries = await UmbracoCommerceApi.GetCountriesAsync(store.Id);
    var currencies = await UmbracoCommerceApi.GetCurrenciesAsync(store.Id);
    var currentCountry = await UmbracoCommerceApi.GetDefaultShippingCountryAsync(store.Id);
}

@if (countries.Count() > 1)
{
    @using (Html.BeginUmbracoForm("ChangeCountry", "Culture", FormMethod.Post, new { @name = "changeCountryForm" }))
    {
        @Html.DropDownList("countryIsoCode", countries.Select(x 
            => new SelectListItem(currencies.First(y => y.Id == x.DefaultCurrencyId!.Value).Code, x.Code, x.Code == currentCountry.Code)),
        new
        {
            @class = "form-select form-select-sm",
            @onchange = "document.forms['changeCountryForm'].submit()"
        })
    }
}

This can then be placed in your sites base template by adding the following:

Layout.cshtml
@(await Html.PartialAsync("CurerrencySwitcher"))

Handle Switching Currencies

Switching the culture is handled by a Surface controller.

Create a new Surface controller called CultureSurfaceController and add the following code:

CultureSurfaceController.cs
public class CultureSurfaceController : SurfaceController
{
    private readonly IUmbracoCommerceApi _commerceApi;

    public CultureSurfaceController(
        IUmbracoContextAccessor umbracoContextAccessor, 
        IUmbracoDatabaseFactory databaseFactory, 
        ServiceContext services, 
        AppCaches appCaches, 
        IProfilingLogger profilingLogger, 
        IPublishedUrlProvider publishedUrlProvider,
        IUmbracoCommerceApi commerceApi) 
        : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
    {
        _commerceApi = commerceApi;
    }
    
    [HttpPost]
    public async Task<IActionResult> ChangeCountry(ChangeCountryDto changeCountryDto)
    {
        var store = CurrentPage.GetStore();
        var country = await _commerceApi.GetCountryAsync(store.Id, changeCountryDto.CountryIsoCode);
        var currency = await _commerceApi.GetCurrencyAsync(country.DefaultCurrencyId.Value);
    
        await _commerceApi.SetDefaultPaymentCountryAsync(store.Id, country);
        await _commerceApi.SetDefaultShippingCountryAsync(store.Id, country);
        await _commerceApi.SetDefaultCurrencyAsync(store.Id, currency);
    
        var currentOrder = await _commerceApi.GetCurrentOrderAsync(store.Id);
        if (currentOrder != null)
        {
            await _commerceApi.Uow.ExecuteAsync(async uow =>
            {
                var writableOrder = await currentOrder.AsWritableAsync(uow)
                    .ClearPaymentCountryRegionAsync()
                    .ClearShippingCountryRegionAsync()
                    .SetCurrencyAsync(currency.Id);
    
                await _commerceApi.SaveOrderAsync(writableOrder);
    
                uow.Complete();
            });
        }
    
        return RedirectToCurrentUmbracoPage();
    }
}

The ChangeCountryDto class binds the country ISO code from the form.

ChangeCountryDto.cs
public class ChangeCountryDto
{
    public string CountryIsoCode { get; set; }
}

Result

With the currency switcher implemented, users can switch between countries/currencies on your website.

The changes are reflected on the product details pages.

Countries
Currencies
Product Prices
Currency Switcher
product-gb
product-dk