Monday 17 February 2020

International Exchange Rate Integration to PHP Website

When we are developing  Ecommerce website for international customers, sometimes we want to show item prices in their local currencies. So to update all country currency manually is not a feasible task. So we have to look for some automated way to do this thing. I will explain steps need to taken for doing the same.

1) First thing we have to do is to fix a Base Currency for our website. Its better to put USD as abse currency since it is not fluctuating very much. So you dont have to worry about your items prices every time..

2) You should have a currency rate table in your database. Its fields should be Currencycode, Formal name, rate .etc.. If you need help creating.. download below sql file and export it. Suppose the table name is currency.
https://github.com/litto/Currency-Mysql-table

3) Now create a cron php file named update_exchangerate.php in your server.

4) Copy below code into that file and use yoor own functions for database operations

 $rss = new DOMDocument();
 $rss->load('http://www.floatrates.com/daily/usd.xml');
 $feed = array();
 foreach ($rss->getElementsByTagName('item') as $node) {

  $item = array ( 
   'baseCurrency' => $node->getElementsByTagName('baseCurrency')->item(0)->nodeValue,
   'targetCurrency' => $node->getElementsByTagName('targetCurrency')->item(0)->nodeValue,
   'exchangeRate' => $node->getElementsByTagName('exchangeRate')->item(0)->nodeValue,
   );
  array_push($feed, $item);
 }
 $limit = count($feed);
 for($x=0;$x<$limit;$x++) {

  $baseCurrency = $feed[$x]['baseCurrency'];
  $targetCurrency = $feed[$x]['targetCurrency'];
  $exchangeRate = $feed[$x]['exchangeRate'];
  
    $result = mysql_query("SELECT *  FROM  cms_currency  WHERE `name`='$targetCurrency'", $link1);
    $productdet=fetchquery($result);
    if(count($productdet)>0){
    $currency_id=$productdet[0]['id'];
    if($currency_id!='' || $currency_id!=0)
    {

$inputs1 = array('conv' => $exchangeRate);

updatequery($inputs1,"cms_currency","id='$currency_id'",$dblink);

    }

  }

 } 

5) You can set this file to run as cronjob as frequent as you want.. so it will update the current rates .
If you have linux hosting you can go to Cpanel. Go to advanced section. Click on Cron Jobs. Add a cron job by selecting once per day. Select the hour you need to update.

Command update as wget https://www.website.com/cron/update_exchangerates.php


No comments:

Post a Comment