BasicLife.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace app\extra\dyLife;
  3. use support\think\Cache;
  4. use yzh52521\EasyHttp\Http;
  5. class BasicLife
  6. {
  7. /**
  8. * 网关
  9. * @var string
  10. */
  11. protected string $gateway = "https://open.douyin.com/";
  12. /**
  13. * 配置信息
  14. * @var array
  15. */
  16. protected array $config = [];
  17. /**
  18. * 默认header
  19. * @var string[]
  20. */
  21. protected array $header = [];
  22. /**
  23. * AccessToken前缀
  24. * @var string
  25. */
  26. protected string $prefix = "dy_[appid]_access_token";
  27. /**
  28. * 设置配置信息
  29. * @param array $config
  30. * @return $this
  31. */
  32. public function config(array $config = []): static
  33. {
  34. $this->config = $config;
  35. return $this;
  36. }
  37. /**
  38. * 释放授权
  39. * @return $this
  40. */
  41. public function token(): static
  42. {
  43. $this->header = [
  44. "access-token" => $this->getAccessToken()
  45. ];
  46. return $this;
  47. }
  48. public function getAccessToken()
  49. {
  50. try {
  51. $accessToken = Cache::get($this->getPrefix());
  52. if (!empty($accessToken)) return $accessToken;
  53. $result = (new Token)->config($this->config)->getAccessToken();
  54. if (empty($result)) return "获取Token失败";
  55. Cache::set($this->getPrefix(),$result['access_token'],$result['expires_in']);
  56. return $result['access_token'];
  57. } catch (\Throwable $throwable) {
  58. return "";
  59. }
  60. }
  61. /**
  62. * @return string
  63. */
  64. protected function getPrefix(): string
  65. {
  66. return str_replace("[appid]",$this->config['appid'],$this->prefix);
  67. }
  68. /**
  69. * @param string $url
  70. * @param array $data
  71. * @param string $field
  72. * @return array
  73. */
  74. public function curlPostApi(string $url = "", array $data = [], string $field = "data"): array
  75. {
  76. $result = Http::asJson()->withHeaders($this->header)->post($this->gateway.$url,$data)->array();
  77. if(!empty($result[$field]))
  78. {
  79. return $result[$field];
  80. }
  81. return [];
  82. }
  83. /**
  84. * @param string $url
  85. * @param array $data
  86. * @param string $field
  87. * @return array
  88. */
  89. public function curlGetApi(string $url = "", array $data = [], string $field = "data"): array
  90. {
  91. $result = Http::asJson()->withProxy("")->withHeaders($this->header)->get($this->gateway.$url,$data)->array();
  92. if(!empty($result[$field]))
  93. {
  94. return $result[$field];
  95. }
  96. return [];
  97. }
  98. }