| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- <?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
- {
- use \Hyperf\Di\Aop\ProxyTrait;
- use \Hyperf\Di\Aop\PropertyHandlerTrait;
- function __construct()
- {
- $this->__handlePropertyHandler(__CLASS__);
- }
- /**
- * @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,
- );
- $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 [];
- }
- }
|