appId = $config['app_id']; $this->appKey = $config['app_key']; $this->secret = $config['app_secret']; $this->accessTokenFile = storage_path('app/bytedance/bytedance_access_token.json'); $this->accessToken = $this->checkAccessToken(); return $this; } /** * @param string $code * @param string $anonymousCode * @return array|mixed * @throws \Exception */ public function login($code = '',$anonymousCode = '') { return $this->post(ByteDanceAPI::LOGIN, [ 'code' => $code, 'anonymous_code' => $anonymousCode, ]); } /** * 校验access token 是否过期 * @return mixed */ private function checkAccessToken() : string { try { $dir = storage_path('app/bytedance'); if (!is_dir($dir)) mkdir($dir, 0755); if (!is_file($this->accessTokenFile)) touch($this->accessTokenFile); $accessToken = file_get_contents($this->accessTokenFile); $accessToken = $accessToken ? json_decode($accessToken,true) : null; if (empty($accessToken) || $accessToken['expires_at'] < time()) { $accessToken = $this->getAccessToken(); }else{ $accessToken = $accessToken['access_token']; } return $accessToken; } catch (\Exception $e) { } } /** * 获取 access token * @throws \Exception */ private function getAccessToken() : string { $res = $this->post(ByteDanceAPI::ACCESS_TOKEN, [ 'grant_type' => 'client_credential' ]); if (!empty($res['err_no'])) { throw new \Exception('获取access token 错误'); } file_put_contents($this->accessTokenFile, json_encode([ 'access_token' => $res['access_token'], 'expires_at' => $res['expiresAt'] ])); return $res['access_token']; } /** * 接口请求 * * @param string $uri * @param array $data * @return array|mixed * @throws \Exception */ private function post($uri = '', $data = []) : array { try { $data = array_merge($data,[ 'appid' => $this->appId, 'secret' => $this->secret, ]); $client = new Client(); $res = $client->post($uri, [ 'verify' => false, 'headers' => ['Content-Type' => 'application/json'], 'body' => json_encode($data) ]); $stringBody = (string)$res->getBody(); $res = json_decode($stringBody, true); if(!empty($res['err_no'])){ throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_no']},错误信息:{$res['err_tips']}"); } return $res['data']; } catch (GuzzleException $e) { trace($e->getMessage(), 'error'); throw new \Exception($e->getMessage()); } } }