免费的汇率API

时间:2021-08-23 19:18:57
来自我的博客:http://www.meedee.cn/2016/07/06/%e5%85%8d%e8%b4%b9%e7%9a%84%e6%b1%87%e7%8e%87api/

1 https://currencylayer.com/

documents:https://currencylayer.com/documentation

免费功能:1个月1000次的api记录,可以使用live,historical,可以传currencies获取指定的货币汇率。

不能使用convert,source,from,to,amout等参数

php实现代码

配置文件
'CURRENCY_API'=>"http://apilayer.net/api/historical?access_key=xxx&format=1"

public function testCurrencyApi()
{
$date = I("request.date") ? I("request.date") : "2016-07-02";
$price = I("request.price") ? I("request.price") : "100";
$from = I("request.from") ? I("request.from") : "CNY";
//$currencies = I("request.currencies") ? I("request.currencies") : "HKD,CNY,USD,AUD,MOP,MYR";
$to = "HKD";
$source = "USD";
// AUD:澳幣,MOP:澳門幣,MYR:馬來西亞
$endpoint = C("CURRENCY_API");
//$searchData['currencies'] = $currencies;
$searchData['date'] = $date;
//$searchData['price'] = $price;
$endpoint .= "&" . http_build_query($searchData);
$memcache_key = md5($endpoint);
$cache = S(array('type'=>'memcache','host'=>C("MEMCACHE_HOST"),'port'=>C("MEMCACHE_PORT"),'expire'=>0));
$memcache_data = S($memcache_key);
if ($memcache_data) {
$currency = $memcache_data;
echo "use cache!
";
} else {
$result = addCurl($endpoint);
$currency = json_decode($result,true);
S($memcache_key, $currency);
}
if (!$currency['success']) {
$this->response(false, "get api failed");
}
$quotes = $currency['quotes'];
//dump($quotes);
// to usd
$usdPrice = $price / $quotes[$source . $from];
echo "currency date:" . $currency['date'] . "
";
echo "usd price:{$usdPrice}
";
$hkdPrice = $usdPrice * $quotes[$source . $to];
echo "hk price:" . round($hkdPrice, 2);
}