Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


These support forums are now closed for new topics and comments.
Please head on over to http://eureka.ucommerce.net/ for support.

  • Lasse Kofoed 40 posts 157 karma points
    Feb 02, 2015 @ 23:24
    Lasse Kofoed
    3

    One catalog with multiple currency and currency calculation.

    Giving back some love to the community, hopefully someone can use it or just some feedback is appreciate.  

    Working on 
    Umbraco v6.2.4
    uCommerce for Umbraco v6.5.3.14350

    Features:

    • Change user basket currency and show prices in selected currency
    • PricingService that handles currency based on fixed product currency price, exchange rate on currency or Google currency calculation feed.

    After realizing the different between 

    // The default catalog pricegroup
    SiteContext.Current.CatalogContext.CurrentCatalog.PriceGroup
    SiteContext.Current.CatalogContext.CurrentCatalog.UpdatePriceGroup(pg);
    
    //This is the currenct users pricegroup
    SiteContext.Current.CatalogContext.CurrentPriceGroup
    UCommerce.Api.CatalogLibrary.ChangePriceGroup(pg,true)


    I came up with this

    IPricingService - Remember to register this i the Custom.config file ( see below )

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text.RegularExpressions;
    using System.Web;
    using UCommerce;
    using UCommerce.Catalog;
    using UCommerce.EntitiesV2;
    using UCommerce.Runtime;
    
    namespace YOURPROJECT.Services
    {
        public class CurrencyPricingService : IPricingService
        {
            public Money GetProductPrice(Product product, PriceGroup priceGroup)
            {
                // The Default Pricegroup set on the shop ( eg. the one with the price entered )
                var shopPriceGroup = SiteContext.Current.CatalogContext.CurrentCatalog.PriceGroup;
    
                // The Price of the product in defualt pricegroup - this is the where price is entered in the backend
                var baseprice = product.PriceGroupPrices.FirstOrDefault(x => x.PriceGroup.PriceGroupId == shopPriceGroup.PriceGroupId);
    
                // Some fallback price.. 
                var fallbackprice = new Money(0, priceGroup.Currency);
    
                // Get the current requested pricegroup set ( usede CatalogLibrary.ChangePriceGroup(pg, true); to set the user pricegroup )
                var currentprice = product.PriceGroupPrices.FirstOrDefault(x => x.PriceGroup.PriceGroupId == priceGroup.PriceGroupId);
    
                // If there is a value set in the requred pricegroup return price and currency
                if (currentprice != null && currentprice.Price.HasValue)
                {
                    return new Money(currentprice.Price.GetValueOrDefault(), currentprice.PriceGroup.Currency);
                }
    
    
                // If the product dont have the baseshop pricegroup set
                if (baseprice == null)
                {
                    if (product.IsVariant)
                    {
                        return GetProductPrice(product.ParentProduct, priceGroup);
                    }
    
                    // Fallback, if this is a product and no baseprise to calc from, we show 0
                    return fallbackprice;
    
                }
                decimal exchangeRateCalculatedPrice = 0;
                // If exchangerate is set to 0, use online exchangerate
                if (priceGroup.Currency.ExchangeRate == 0)
                {
                    try
                    {
                        // Use google to make lookup
                        exchangeRateCalculatedPrice = Convert(baseprice.Price.Value, baseprice.PriceGroup.Currency.ISOCode, priceGroup.Currency.ISOCode);
                    }
                    catch(Exception ex)
                    {
                        // Service down ? Report somewhere
                        return fallbackprice;
                    }
                }
                else
                {
                    // Calucate currecy based on ExchangeRate
                        exchangeRateCalculatedPrice = (baseprice.Price.Value / 100) * priceGroup.Currency.ExchangeRate;
                }
    
                return new Money(exchangeRateCalculatedPrice, priceGroup.Currency);
            }
    
    
    
        public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
            {
                string apiURL = String.Format("https://www.google.com/finance/converter?a={0}&from={1}&to={2}&meta={3}", amount, fromCurrency, toCurrency, Guid.NewGuid().ToString());
    
                //Make your Web Request and grab the results
                var request = WebRequest.Create(apiURL);
    
                //Get the Response
                var streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
    
                //Grab your converted value (ie 2.45 USD)
                var result = Regex.Matches(streamReader.ReadToEnd(), "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value;
                result = result.Split(' ')[0].ToString();
                //Get the Result
                decimal returnvalue = 0;
                decimal.TryParse(result, out returnvalue);
                return returnvalue;
            }
        }
    }
    
    

    Custom.config umbraco/ucommerce/Configuration/Custom.config

    //ADD
    <component id="PriceService" service="UCommerce.Catalog.IPricingService, UCommerce" type="YOURPROJECT.Services.CurrencyPricingService, YOURPROJECT" />


    Somewhere on the site where you what the "change currency" function

    var allowedPriceGroups = SiteContext.Current.CatalogContext.CurrentCatalog.AllowedPriceGroups;
    var request = HttpContext.Current.Request;
    
     // Change currency POSTBACK HANDLER
        if (!String.IsNullOrWhiteSpace(request.QueryString["currencyChange"]))
        {
            int pgId = 0;
            //var selectedCurrency = request.QueryString["currencyChange"];
    
            if (int.TryParse(request.QueryString["currencyChange"], out pgId))
            {
                var pg = allowedPriceGroups.FirstOrDefault(p => p.PriceGroupId.Equals(pgId));
    
                if (pg != null)
                {
                    UCommerce.Api.CatalogLibrary.ChangePriceGroup(pg, true); 
    
                    var order = TransactionLibrary.GetBasket(false);
                    order.PurchaseOrder.BillingCurrency = pg.Currency;
                    TransactionLibrary.ExecuteBasketPipeline();
                    order.Save();
    
                    // Redir without the currencyChange paramter
                    // This is done, so that all items are updatede with the new basket, and currency
          // Maybe not needed.
                    var nvc = HttpUtility.ParseQueryString(Request.Url.Query);
                    nvc.Remove("currencyChange");
                    string url = Request.Url.AbsolutePath + "?" + nvc.ToString();
                    Response.Redirect(url);
                }
            }
        }
    @if(allowedPriceGroups.Count > 1)
    {
        <div class="changeCurrency">
    
            @foreach (var pg in allowedPriceGroups)
            {
                if (SiteContext.Current.CatalogContext.CurrentPriceGroup.PriceGroupId == pg.PriceGroupId)
                {
                <span class="selected">@pg.Name</span>
                }
                else
                {
                    var nvc = HttpUtility.ParseQueryString(Request.Url.Query);
                    nvc.Add("currencyChange", pg.PriceGroupId.ToString());
                    string url = Request.Url.AbsolutePath + "?" + nvc.ToString();
                    <span><a href="@url">@pg.Name</a></span>
                }
            }
        </div>
    }


    Allowing the pricegroup on a catalog enables the pricegroup/currency on the website.

    See UCommerce documentation for Pricegroup and currency setup.

  • Søren Spelling Lund 1796 posts 2764 karma points
    Feb 03, 2015 @ 14:02
    Søren Spelling Lund
    100

    Awesome! Thanks for sharing.

Please Sign in or register to post replies

Write your reply to:

Draft