Announcement

Collapse
No announcement yet.

Christmas Present: Automatically set second currency rate.

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Christmas Present: Automatically set second currency rate.

    The European Central Bank maintains an publicly available online database of exchange rates for the Euro against major currencies. See http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml for the feed.

    Here's a bit of code which will fetch that data, look up your main and alternate currency and if both have ECB rates available the Actinic database value will be set to the current rate.

    The code only runs on the store top page and only updates the rate if the current rate is more than 5% dfferent from the prior. This saves you from big uploads every day as minor exchange rate changes won't affect the displayed page.

    Some diagnostic info is displayed when on the store top page (only on Preview - not on the live site).

    Note that Actinic caches the exchange rate value so the rate used on your pages will be the one from the last time Actinic started. If you want to force an update - preview the store top page then close and restart Actinic.

    Installation:

    Put the following code into your overall layout (either just after the <body ...> tag or just before the </body> tag is best)
    Code:
    <actinic:block if="%3cactinic%3avariable%20name%3d%22PageType%22%20%2f%3e%20%3d%3d%20%22Section%22" >
    	<actinic:block if="%3cactinic%3avariable%20name%3d%22SectionLevel%22%20%2f%3e%20%3d%3d%200">
    		<actinic:block php="true" >
    			$percentdifference = 5;		// don't change rate unless current outside this range
    			$showdiags = true;			// whether to show diagnostic info (Preview only)
    			$isPreview = <actinic:variable name="IsPreviewMode" encoding="perl" selectable="false" />;
    			$connect = odbc_pconnect("ActinicCatalog<actinic:variable name="ECMajorVersion" encoding="perl" selectable="false" />","","", SQL_CUR_USE_ODBC); 
    
    			// see if we're using an alternate currency - if so, get the existing rate from the DB
    			$query = "SELECT bDisplayEuroPrice, sAltPriceCurrency FROM Setup2 WHERE bDisplayEuroPrice"; 
    			$result = odbc_exec($connect, $query); 
    			odbc_fetch_row($result);
    			$bDisplayEuroPrice = odbc_result($result, 1); 
    			$sAltPriceCurrency = odbc_result($result, 2); 
    
    			// proceed if we're using an alternate currency
    			if ( $bDisplayEuroPrice )
    				{ 
    				// first lookup our base currency and symbol from the Actinic setup
    				$query = "SELECT [Currency of purchase], SINTLSYMBOLS FROM Catalog WHERE SINTLSYMBOLS"; 
    				$result = odbc_exec($connect, $query); 
    				odbc_fetch_row($result);
    				$sBaseCurrencyLong = odbc_result($result, 1); 
    				$sBaseCurrencySymbol = odbc_result($result, 2); 
    
    				// get stored iso code and rate for second currency from the database
    				$query = "SELECT sExchangeRate, SINTLSYMBOL FROM currencies WHERE SINTLSYMBOL='$sAltPriceCurrency'"; 
    				$result = odbc_exec($connect, $query); 
    				odbc_fetch_row($result);
    				$sExchangeRate = odbc_result($result, 1);
    								
    				// Now get ECB rates
    				$exchrate['EUR'] = 1.00;	// rates returned against Euro so we need a dummy entry
    				$rates = file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");	// the ECB XML file
    				if ( ! $rates )
    					{
    					if ( $isPreview )
    						{
    						echo "Unable to get exchange rate data from http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
    						}
    					}
    				else
    					{
    					# Extract data from page - conversion rates between each currency and the Euro
    					foreach ($rates as $line) 
    						{
    						if ( preg_match("/currency='(.*?)' rate='(.*?)'/" , $line, $matches) )
    							{
    							$exchrate[$matches[1]] = $matches[2];
    							}
    						}
    					
    					// now lookup the todays rate
    					if ( array_key_exists($sAltPriceCurrency, $exchrate) && array_key_exists($sBaseCurrencySymbol, $exchrate) )
    						{
    						$todaysbasecurrencyeurorate = 1 / $exchrate[$sBaseCurrencySymbol];	// ECB supplies Euro rates
    						$todayaltcurrencyrate = sprintf('%.4f', $todaysbasecurrencyeurorate * $exchrate[$sAltPriceCurrency]);
    	
    						// see what the percentage change is from prior value
    						$rateratio = $sExchangeRate > $todayaltcurrencyrate ? $sExchangeRate / $todayaltcurrencyrate : $todayaltcurrencyrate / $sExchangeRate;
    						$ratepercentdiff = sprintf('%.1f',($rateratio - 1 ) * 100);
    		
    						// some diagnostic info
    						if ( $showdiags && $isPreview )
    							{
    							echo "N.B. Only shows on Preview. Default: $sBaseCurrencyLong $sBaseCurrencySymbol ";
    							echo " Alternate: $sAltPriceCurrency (Old $sExchangeRate)";
    							echo " Today: EUR $todaysbasecurrencyeurorate $sAltPriceCurrency $todayaltcurrencyrate";
    							echo " Difference: $ratepercentdiff%";
    							}
    							
    						// now update the exchange rate - but only if significant change from previous value
    						if ( $ratepercentdiff >= $percentdifference )		
    							{
    							$query = "UPDATE currencies SET sExchangeRate = '$todayaltcurrencyrate' WHERE SINTLSYMBOL='$sAltPriceCurrency'"; 
    							$result = odbc_exec($connect, $query);
    							}
    						}
    					else	// one or both rates unavailable
    						{
    						$errmsg = '';
    						if ( ! array_key_exists($sAltPriceCurrency, $exchrate) )
    							{
    							$errmsg .= "No rate available for $sAltPriceCurrency ";
    							}
    						if ( ! array_key_exists($sBaseCurrencySymbol, $exchrate) )
    							{
    							$errmsg .= "No rate available for $sBaseCurrencySymbol ";
    							}
    						if ( $isPreview )
    							{
    							echo " Error: $errmsg ";
    							}
    						}
    					}
    				// whew - done with database
    				odbc_close_all();   
    				} 
    		</actinic:block>		
    	</actinic:block>
    </actinic:block>
    Norman - www.drillpine.biz
    Edinburgh, U K / Bitez, Turkey

    #2
    Hi Norman - I have a client who wants to be able to display a 3rd currency.

    Before I delve into it could the code above be used as a basis to do this?
    Regards
    David

    Comment


      #3
      Just looking on your Drillpine site - will NorPrice do this for me?
      Regards
      David

      Comment


        #4
        Norprice wil give you a selectable second currency - which should work for you.

        Comment


          #5
          awesome hack, kudos.

          Comment


            #6
            Just a bit of information for anyone who is interested. This is a simple multi-currency solution not nearly as good as Norman's, but may be useful to people in the same circumstances as me.

            I wanted to let overseas customers see roughly how much the products cost in their currency. I still price and ask for payment in Sterling (GBP) so it was only a display of the price in their chosen currency.

            I've implemented a tool from www.dynamicconverter.com (DC). This only required me to insert one line of coding; and there is no need to change prices or add additional fields or calculations. The customer can select which additional currency they want to see. The exchange rates are updated automatically by DC.

            Perhaps best of all the service is free if you have less than 10000 page requests to them per month.

            As I said not as good, useful or elegant as Norman's solution - but it's horses for course.

            Laura
            http://www.lembrassa.com
            Designs for the Fuller Bust

            Comment


              #7
              That looks interesting Laura - I will take a look at that.

              Please provide me with a link to your site so that I can see it working on an Actinic site.
              Regards
              David

              Comment


                #8
                Skinny,

                My site is www.lembrassa.com - it's for women's lingerie.

                You will see a box on the right hand side just under the navigation tabs where the alternate currency can be selected from a dropdown menu. There were too many currencies available so I have restricted that list to the main ones my customers use. Once selected, the system remembers it for future until changed, but the selection option appears on every page for customer convenience. Once a non-GBP second currency is selected, all the prices on every page get displayed in both the original GBP and the customer selected curency.

                You will see on some pages I have elected not to have the second currency price displayed on occasion - but that was my choice.

                Hope this helps. If you need more information just let me know.

                Laura
                http://www.lembrassa.com
                Designs for the Fuller Bust

                Comment


                  #9
                  Excellent - thanks for sharing that.
                  Regards
                  David

                  Comment

                  Working...
                  X