| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace app\common\library;
- use think\Cache;
- use think\Hook;
- /**
- * 根据汇率转换金额
- * Class CoinRate
- * @package app\common\library
- */
- class CoinRate
- {
- protected static $apiUrl = 'https://api.it120.cc/gooking/forex/rate?fromCode=%s&toCode=%s';
- /**
- * 转换汇率金额
- * @param $amount
- * @param string $from
- * @param string $to
- * @return float|mixed
- */
- public static function transfer($amount, $from='CNY', $to='USD')
- {
- if(empty($from) || empty($to)){
- return $amount;
- }
- $cacheKey = "cache:rates:{$from}_{$to}";
- $data = Cache::get($cacheKey);
- $rate = isset($data['rate'])? floatval($data['rate']) : 0.00;
- $expired = isset($data['expired'])? intval($data['expired']) : 0;
- if($rate<=0 || $expired<time()){
- $result = curl_api_get(sprintf(self::$apiUrl, $to, $from));
- $result = $result? json_decode($result, true) : [];
- $data = isset($result['data'])? $result['data'] : [];
- $rate = isset($data['rate'])? floatval($data['rate']) : 0.00;
- if($rate > 0){
- $data['expired'] = time() + 300;
- Cache::set($cacheKey, $data, time() + 300);
- }
- }
- return $rate>0? floatval($rate * $amount) : $amount;
- }
- /**
- * 转换汇率金额
- * @param $amount
- * @param string $from
- * @param string $to
- * @return float|mixed
- */
- public static function getRate($from='CNY', $to='USD')
- {
- $cacheKey = "cache:rates:{$from}_{$to}";
- $data = Cache::get($cacheKey);
- $rate = isset($data['rate'])? floatval($data['rate']) : 0.00;
- $expired = isset($data['expired'])? intval($data['expired']) : 0;
- if($rate<=0 || $expired<time()){
- $result = curl_api_get(sprintf(self::$apiUrl, $to, $from));
- $result = $result? json_decode($result, true) : [];
- $data = isset($result['data'])? $result['data'] : [];
- $rate = isset($data['rate'])? floatval($data['rate']) : 0.00;
- if($rate > 0){
- $data['expired'] = time() + 300;
- Cache::set($cacheKey, $data, time() + 300);
- }
- }
- return $rate;
- }
- }
- ?>
|