Base.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace app\extra\douyin;
  3. use support\think\Cache;
  4. use yzh52521\EasyHttp\Http;
  5. class Base
  6. {
  7. /**
  8. * API地址
  9. * @var string
  10. */
  11. protected string $gateway = "https://open.douyin.com/";
  12. /**
  13. * 配置信息
  14. * @var array
  15. */
  16. protected array $config = [];
  17. /**
  18. * @var string
  19. */
  20. private string $access_token;
  21. /**
  22. * 默认header
  23. * @var string[]
  24. */
  25. protected array $header = [
  26. "content-type" => "application/json"
  27. ];
  28. /**
  29. * AccessToken前缀
  30. * @var string
  31. */
  32. protected string $tokenPrefix = "dy_[appid]_access_token";
  33. public function token(): static
  34. {
  35. $this->header = [
  36. "access-token" => $this->getAccessToken()
  37. ];
  38. return $this;
  39. }
  40. /**
  41. * 设置配置信息
  42. * @param array $config
  43. * @return $this
  44. */
  45. public function config(array $config = []): static
  46. {
  47. $this->config = $config;
  48. return $this;
  49. }
  50. public function getAccessToken()
  51. {
  52. // $resp = Http::asJson()->get("https://miniapi.jsshuita.com.cn/test/token")->array();
  53. // return $resp['data']['token'];
  54. $accessToken = Cache::get($this->getTokenPrefix());
  55. if (!empty($accessToken)) return $accessToken;
  56. $result = (new AccessToken)->config($this->config)->getAccessTokenLine();
  57. if (empty($result)) return "获取Token失败\n";
  58. Cache::set($this->getTokenPrefix(),$result['access_token'],$result['expires_in']);
  59. return $result['access_token'];
  60. }
  61. /**
  62. * 注册当前请求接口
  63. * @param string $url 接口地址
  64. * @return string
  65. */
  66. protected function registerApi(string &$url): string
  67. {
  68. if (empty($this->access_token)) $this->access_token = $this->getAccessToken();
  69. return $url = str_replace('ACCESS_TOKEN', urlencode($this->access_token), $url);
  70. }
  71. /**
  72. * @return string
  73. */
  74. protected function getTokenPrefix(): string
  75. {
  76. return str_replace("[appid]",$this->config['appid'],$this->tokenPrefix);
  77. }
  78. }