| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- namespace App\Task;
- use App\Repositories\ConfigRepoistory;
- use Hyperf\Crontab\Annotation\Crontab;
- use Hyperf\Di\Annotation\Inject;
- use Hyperf\Guzzle\ClientFactory;
- /**
- * @Crontab(name="UsdtRate", rule="00 /1 * * *", callback="execute", memo="usdt汇率")
- */
- class ConfigUsdtRate
- {
- /**
- * @Inject()
- * @var \Hyperf\Contract\StdoutLoggerInterface
- */
- private $logger;
- private $reatUrl = [
- 'http://api.coincap.io/v2/rates/chinese-yuan-renminbi',
- 'https://v6.exchangerate-api.com/v6/1a45491bb39175ddc4203829/latest/CNY',
- 'https://api.exchangerate-api.com/v4/latest/CNY'
- ];
- public function execute()
- {
- $confRepo = make(ConfigRepoistory::class);
- $config = $confRepo->pickByKeys(['usdt_conf', 'usdt_pick_switch'], 'sys');
- if ($config['usdt_pick_switch']['svalue'] != 1) {
- return '';
- }
- $oldUsdtRate = $config['usdt_conf']['svalue'];
- foreach ($this->reatUrl as $key => $url) {
- try {
- $res = $this->curl($url);
- if (empty($res)) {
- continue;
- }
- $aRes = json_decode($res, true);
- if ($key == 0) {
- if (empty($aRes['data']) || $aRes['data']['symbol'] != 'CNY') {
- continue;
- }
- $rateUsd = round($aRes['data']['rateUsd'], 2);
- break;
- }
- if ($key == 1) {
- if (empty($aRes['result']) || $aRes['result'] != 'success') {
- continue;
- }
- $rateUsd = round($aRes['conversion_rates']['USD'], 2);
- break;
- }
- if ($key == 2) {
- if (empty($aRes['rates'])) {
- continue;
- }
- $rateUsd = round($aRes['rates']['USD'], 2);
- break;
- }
- } catch (\Exception $exception) {
- logger($exception->getMessage());
- }
- }
- $usdtRate = (round(100 / $rateUsd, 2)) / 100;
- if ($oldUsdtRate != $usdtRate) {
- $confRepo->saveByKeys(['usdt_conf' => ($usdtRate + 0.3)], 'sys');
- $confRepo->updateConfigCache('sys');
- }
- }
- private function curl($url)
- {
- $options = array(
- 'timeout' => 20, // 超时,单位秒.
- 'verify' => false, // 是否校验SSL证书.
- 'http_errors' => false, // 如果跟随http异常头部是否中断.
- 'debug' => false, // 是否启用调试模式.
- 'allow_redirects' => true, // 不跟随301/302跳转.
- );
- $client = make(ClientFactory::class)->create($options);
- $params = [
- 'headers' => [
- 'Content-Type'=>'application/json'
- ],
- ];
- $result = $client->get($url, $params);
- $code = $result->getStatusCode();
- if ($code == 200) {
- return $result->getBody()->getContents();
- }
- return [];
- }
- }
|