httpClient = new Client(); if (function_exists('config')) { $this->notifierUrl = config('eknotifier.url'); $this->applicationCode = config('eknotifier.app_code'); $this->applicationPassword = config('eknotifier.app_password'); } elseif (!$url || !$applicationCode || !$applicationPassword) { throw new \Exception('Url, Application Code, or Application Password is missing'); } else { $this->notifierUrl = $url; $this->applicationCode = $applicationCode; $this->applicationPassword = $applicationPassword; } } /** * Get the EKNotifier JWT Token. * * @return string|null * @throws \GuzzleHttp\Exception\GuzzleException * @throws \Exception */ public function getAuthToken(): ?string { if (!cache('eknotifier_token')) { $this->login(); } return cache('eknotifier_token'); } /** * Login to the EKNotifier Service and cache the key. * * @return bool * @throws \GuzzleHttp\Exception\GuzzleException * @throws \Exception */ public function login(): bool { if (cache('eknotifier_token')) { return true; } $response = $this->postAPI('application/login', [ 'code' => $this->applicationCode, 'password' => $this->applicationPassword ]); if ($response->getStatusCode() === 200) { $result = json_decode(trim($response->getBody()), true); cache(['eknotifier_token' => $result['access_token']], 1800); return true; } return false; } /** * Call EKNotifier POST API. * * @param string $path * @param array $request * @param string|null $token * @return ResponseInterface * @throws \GuzzleHttp\Exception\GuzzleException */ protected function postAPI(string $path, array $request, string $token = null): ResponseInterface { $url = $this->notifierUrl . '/api/v1/' . $path; $params = ['json' => $request]; if ($token) { $params['headers'] = ['Authorization' => 'Bearer ' . $token]; } try { return $this->httpClient->request('POST', $url, $params); } catch (\Exception $exception) { if ($exception instanceof \Exception) { Logger::trace('EKNOTIFIER ERROR' . $exception->getResponse()->getBody()->getContents()); return new Response( $exception->getResponse()->getStatusCode(), $exception->getResponse()->getHeaders(), $exception->getResponse()->getBody()->getContents(), $exception->getResponse()->getProtocolVersion(), $exception->getResponse()->getReasonPhrase() ); } Logger::trace('EKNOTIFIER ERROR' . $exception->getMessage()); return new Response(500, [], $exception->getMessage()); } } }