Base.php 2.0 KB

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