NodeClient.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace TronTool;
  3. use GuzzleHttp\Client;
  4. class NodeClient{
  5. protected $client;
  6. protected $headers = [];
  7. static function mainNet(){
  8. return new self('https://api.trongrid.io');
  9. }
  10. static function testNet(){
  11. return new self('https://api.shasta.trongrid.io');
  12. }
  13. function __construct($uri){
  14. $apiKey = '';
  15. if (function_exists('config')) {
  16. $apiKey = \config('app.tron_pro_api_key', '');
  17. }
  18. if (!$apiKey) {
  19. $apiKey = getenv('TRON_PRO_API_KEY') ?: '';
  20. }
  21. if ($apiKey) {
  22. $this->headers['TRON-PRO-API-KEY'] = $apiKey;
  23. }
  24. $opts = [
  25. 'base_uri' => $uri,
  26. 'verify' => false,
  27. 'headers' => $this->headers,
  28. ];
  29. $this->client = new Client($opts);
  30. }
  31. function post($api,$payload=[]){
  32. $opts = [
  33. 'json' => $payload,
  34. 'headers' => $this->headers,
  35. ];
  36. $rsp = $this->requestWithRetry('post',$api,$opts);
  37. return $this->handle($rsp);
  38. }
  39. function get($api,$query=[]){
  40. $opts = [
  41. 'query' => $query,
  42. 'headers' => $this->headers,
  43. ];
  44. $rsp = $this->requestWithRetry('get',$api,$opts);
  45. return $this->handle($rsp);
  46. }
  47. protected function requestWithRetry($method,$api,$opts=[],$maxRetries=1){
  48. $attempt = 0;
  49. start:
  50. try {
  51. return $this->client->{$method}($api,$opts);
  52. } catch (\Throwable $e) {
  53. $attempt++;
  54. if ($attempt <= $maxRetries && strpos($e->getMessage(), '429') !== false) {
  55. usleep(5500000);
  56. goto start;
  57. }
  58. throw $e;
  59. }
  60. }
  61. function handle($rsp){
  62. $content = $rsp->getBody();
  63. //echo $content . PHP_EOL;
  64. return json_decode($content);
  65. }
  66. function version(){
  67. return '1.0.0';
  68. }
  69. }