ConfigUsdtRate.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Repositories\ConfigRepoistory;
  4. use Carbon\Carbon;
  5. use GuzzleHttp\Client;
  6. use Illuminate\Console\Command;
  7. class ConfigUsdtRate extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'config:usdt_rate';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = '获取usdt汇率';
  21. private $reatUrl = [
  22. 'http://api.coincap.io/v2/rates/chinese-yuan-renminbi',
  23. 'https://v6.exchangerate-api.com/v6/1a45491bb39175ddc4203829/latest/CNY',
  24. 'https://api.exchangerate-api.com/v4/latest/CNY'
  25. ];
  26. /**
  27. * Create a new command instance.
  28. *
  29. * @return void
  30. */
  31. public function __construct()
  32. {
  33. parent::__construct();
  34. }
  35. public function handle()
  36. {
  37. $this->comment('开始获取usdt汇率');
  38. $confRepo = app(ConfigRepoistory::class);
  39. $config = $confRepo->pickByKeys(['usdt_rate', 'usdt_pick_switch'], 'sys');
  40. if ($config['usdt_pick_switch']['svalue'] != 1) {
  41. $this->comment('ust采集开关已关闭');
  42. return '';
  43. }
  44. $oldUsdtRate = $config['usdt_rate']['svalue'];
  45. foreach ($this->reatUrl as $key => $url) {
  46. try {
  47. $res = $this->curl($url);
  48. $aRes = json_decode($res,true);
  49. if ($key == 0) {
  50. if (empty($aRes['data']) || $aRes['data']['symbol'] != 'CNY') {
  51. continue;
  52. }
  53. $rateUsd = round($aRes['data']['rateUsd'], 2);
  54. break;
  55. }
  56. if ($key == 1) {
  57. if ( empty($aRes['result'])|| $aRes['result'] != 'success') {
  58. continue;
  59. }
  60. $rateUsd = round($aRes['conversion_rates']['USD'], 2);
  61. break;
  62. }
  63. if ($key == 2) {
  64. if (empty($aRes['rates'])) {
  65. continue;
  66. }
  67. $rateUsd = round($aRes['rates']['USD'], 2);
  68. break;
  69. }
  70. } catch (\Exception $e) {
  71. $this->comment('ustd汇率获取失败'. $key);
  72. continue;
  73. }
  74. }
  75. $usdtRate = (round(100 / $rateUsd, 2)) / 100;
  76. if ($oldUsdtRate != $usdtRate) {
  77. $confRepo->saveByKeys(['usdt_rate' => ($usdtRate + 0.3)], 'sys');
  78. $confRepo->updateConfigCache('sys');
  79. }
  80. }
  81. private function curl($url)
  82. {
  83. $client = new Client();
  84. $res = $client->request('GET', $url, [
  85. 'headers' => ['Content-type' => 'application/json']
  86. ]);
  87. $data = $res->getBody()->getContents();
  88. return $data;
  89. }
  90. }