| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace app\extra\dyLife;
- use support\think\Cache;
- use yzh52521\EasyHttp\Http;
- class BasicLife
- {
- /**
- * 网关
- * @var string
- */
- protected string $gateway = "https://open.douyin.com/";
- /**
- * 配置信息
- * @var array
- */
- protected array $config = [];
- /**
- * 默认header
- * @var string[]
- */
- protected array $header = [];
- /**
- * AccessToken前缀
- * @var string
- */
- protected string $prefix = "dy_[appid]_access_token";
- /**
- * 设置配置信息
- * @param array $config
- * @return $this
- */
- public function config(array $config = []): static
- {
- $this->config = $config;
- return $this;
- }
- /**
- * 释放授权
- * @return $this
- */
- public function token(): static
- {
- $this->header = [
- "access-token" => $this->getAccessToken()
- ];
- return $this;
- }
- public function getAccessToken()
- {
- try {
- $accessToken = Cache::get($this->getPrefix());
- if (!empty($accessToken)) return $accessToken;
- $result = (new Token)->config($this->config)->getAccessToken();
- if (empty($result)) return "获取Token失败";
- Cache::set($this->getPrefix(),$result['access_token'],$result['expires_in']);
- return $result['access_token'];
- } catch (\Throwable $throwable) {
- return "";
- }
- }
- /**
- * @return string
- */
- protected function getPrefix(): string
- {
- return str_replace("[appid]",$this->config['appid'],$this->prefix);
- }
- /**
- * @param string $url
- * @param array $data
- * @param string $field
- * @return array
- */
- public function curlPostApi(string $url = "", array $data = [], string $field = "data"): array
- {
- $result = Http::asJson()->withHeaders($this->header)->post($this->gateway.$url,$data)->array();
- if(!empty($result[$field]))
- {
- return $result[$field];
- }
- return [];
- }
- /**
- * @param string $url
- * @param array $data
- * @param string $field
- * @return array
- */
- public function curlGetApi(string $url = "", array $data = [], string $field = "data"): array
- {
- $result = Http::asJson()->withProxy("")->withHeaders($this->header)->get($this->gateway.$url,$data)->array();
- if(!empty($result[$field]))
- {
- return $result[$field];
- }
- return [];
- }
- }
|