ConfigUsdtRate.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace App\Task;
  3. use App\Repositories\ConfigRepoistory;
  4. use Hyperf\Crontab\Annotation\Crontab;
  5. use Hyperf\Di\Annotation\Inject;
  6. use Hyperf\Guzzle\ClientFactory;
  7. /**
  8. * @Crontab(name="UsdtRate", rule="00 /1 * * *", callback="execute", memo="usdt汇率")
  9. */
  10. class ConfigUsdtRate
  11. {
  12. /**
  13. * @Inject()
  14. * @var \Hyperf\Contract\StdoutLoggerInterface
  15. */
  16. private $logger;
  17. private $reatUrl = [
  18. 'http://api.coincap.io/v2/rates/chinese-yuan-renminbi',
  19. 'https://v6.exchangerate-api.com/v6/1a45491bb39175ddc4203829/latest/CNY',
  20. 'https://api.exchangerate-api.com/v4/latest/CNY'
  21. ];
  22. public function execute()
  23. {
  24. $confRepo = make(ConfigRepoistory::class);
  25. $config = $confRepo->pickByKeys(['usdt_conf', 'usdt_pick_switch'], 'sys');
  26. if ($config['usdt_pick_switch']['svalue'] != 1) {
  27. return '';
  28. }
  29. $oldUsdtRate = $config['usdt_conf']['svalue'];
  30. foreach ($this->reatUrl as $key => $url) {
  31. try {
  32. $res = $this->curl($url);
  33. if (empty($res)) {
  34. continue;
  35. }
  36. $aRes = json_decode($res, true);
  37. if ($key == 0) {
  38. if (empty($aRes['data']) || $aRes['data']['symbol'] != 'CNY') {
  39. continue;
  40. }
  41. $rateUsd = round($aRes['data']['rateUsd'], 2);
  42. break;
  43. }
  44. if ($key == 1) {
  45. if (empty($aRes['result']) || $aRes['result'] != 'success') {
  46. continue;
  47. }
  48. $rateUsd = round($aRes['conversion_rates']['USD'], 2);
  49. break;
  50. }
  51. if ($key == 2) {
  52. if (empty($aRes['rates'])) {
  53. continue;
  54. }
  55. $rateUsd = round($aRes['rates']['USD'], 2);
  56. break;
  57. }
  58. } catch (\Exception $exception) {
  59. logger($exception->getMessage());
  60. }
  61. }
  62. $usdtRate = (round(100 / $rateUsd, 2)) / 100;
  63. if ($oldUsdtRate != $usdtRate) {
  64. $confRepo->saveByKeys(['usdt_conf' => ($usdtRate + 0.3)], 'sys');
  65. $confRepo->updateConfigCache('sys');
  66. }
  67. }
  68. private function curl($url)
  69. {
  70. $options = array(
  71. 'timeout' => 20, // 超时,单位秒.
  72. 'verify' => false, // 是否校验SSL证书.
  73. 'http_errors' => false, // 如果跟随http异常头部是否中断.
  74. 'debug' => false, // 是否启用调试模式.
  75. 'allow_redirects' => true, // 不跟随301/302跳转.
  76. );
  77. $client = make(ClientFactory::class)->create($options);
  78. $params = [
  79. 'headers' => [
  80. 'Content-Type'=>'application/json'
  81. ],
  82. ];
  83. $result = $client->get($url, $params);
  84. $code = $result->getStatusCode();
  85. if ($code == 200) {
  86. return $result->getBody()->getContents();
  87. }
  88. return [];
  89. }
  90. }