BasicLife.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace app\extra\dyLife;
  3. use support\think\Cache;
  4. class BasicLife
  5. {
  6. /**
  7. * 网关
  8. * @var string
  9. */
  10. protected string $gateway = "https://open.douyin.com/";
  11. /**
  12. * 配置信息
  13. * @var array
  14. */
  15. protected array $config = [];
  16. /**
  17. * 默认header
  18. * @var string[]
  19. */
  20. protected array $header = [
  21. "content-type" => "application/json"
  22. ];
  23. /**
  24. * AccessToken前缀
  25. * @var string
  26. */
  27. protected string $prefix = "dy_[appid]_access_token";
  28. /**
  29. * 设置配置信息
  30. * @param array $config
  31. * @return $this
  32. */
  33. public function config(array $config = []): static
  34. {
  35. $this->config = $config;
  36. return $this;
  37. }
  38. /**
  39. * 释放授权
  40. * @return $this
  41. */
  42. public function token(): static
  43. {
  44. $this->header = [
  45. "access-token" => $this->getAccessToken()
  46. ];
  47. return $this;
  48. }
  49. public function getAccessToken()
  50. {
  51. try {
  52. $accessToken = Cache::get($this->getPrefix());
  53. if (!empty($accessToken)) return $accessToken;
  54. $result = (new Token)->config($this->config)->getAccessToken();
  55. if (empty($result)) return "获取Token失败";
  56. Cache::set($this->getPrefix(),$result['access_token'],$result['expires_in']);
  57. return $result['access_token'];
  58. } catch (\Throwable $throwable) {
  59. return "";
  60. }
  61. }
  62. /**
  63. * @return string
  64. */
  65. protected function getPrefix(): string
  66. {
  67. return str_replace("[appid]",$this->config['appid'],$this->prefix);
  68. }
  69. }