curl = $curl; $this->cache = $cache; } public function setCaller(Caller $caller): static { $this->caller = $caller; return $this; } protected function getTimestamp(): int { if (!$this->timestamp) { return $this->timestamp = round(microtime(true) * 1000); } return $this->timestamp; } protected function sign(): string { return md5( $this->caller->getAppKey() . $this->getTimestamp() . $this->caller->getAppSecret() ); } protected function getRequestData(): array { return [ 'sign' => $this->sign(), 'appKey' => $this->caller->getAppKey(), 'timestamp' => $this->getTimestamp(), ]; } protected function getRequestUrl(): string { return rtrim($this->caller->getHost(), "/") . '/api/auth/thirdPartyToken'; } protected function post(): array { $body = json_encode($this->getRequestData()); $this->curl->addHeader("Content-Type", "application/json"); $this->curl->post( $this->getRequestUrl(), $body); $body = json_decode($this->curl->getBody(), true); return $body; } /** * @return string * @throws LocalizedException */ protected function tokenCache(): string { $lifeTime = 24*3600-60; $token = $this->post(); if (isset($token['code']) && $token['code'] == 200) { $cacheData = json_encode([ 'token' => $token['data'], 'created_at' => time() ]); $this->cache->save($cacheData, self::DEEPBLUE_TOKEN_IDENTIFIER, [], $lifeTime); return $token['data']; } throw new LocalizedException(__('从/api/auth/thirdPartyToken获取token失败,原因:'.$token['msg'].', code:'.$token['code'])); } /** * @return string * @throws LocalizedException */ public function getToken(): string { $token = $this->cache->load(self::DEEPBLUE_TOKEN_IDENTIFIER); if (!$token) { return $this->tokenCache(); } $cacheData = json_decode($token, true); if ((time() - $cacheData['created_at']) > 60) { return $this->tokenCache(); } return $cacheData['token']; } }