getAccessToken(); if (empty($accessToken)) { // Return null if we cannot obtain an access token return null; } try { // Making a POST request to the Rakuten API to generate the affiliate link $response = Http::throw() ->withHeaders([ 'Authorization' => sprintf('Bearer %s', $accessToken), ]) ->post('https://api.linksynergy.com/v1/links/deep_links', [ 'url' => $originalUrl, 'advertiser_id' => $this->partnerConfig['advertiser_id'], ]); } catch (Exception $ex) { // Logging the exception for debugging purposes report($ex); return null; } // Verifying the API response and extracting the affiliate link if (!$response->ok() || empty($response->json()['advertiser']['deep_link']['deep_link_url'])) { return null; } $url = $response->json()['advertiser']['deep_link']['deep_link_url']; // Storing the generated affiliate link in cache for 24 hours to improve performance Cache::put($cacheKey, $url, 60 * 60 * 24); return $url; } /** * Retrieves the access token required for API calls, with caching to optimize the process. * * @return string|null The access token or null if retrieval fails. */ private function getAccessToken(): ?string { $cacheKey = 'rakuten.access_token'; $token = Cache::get($cacheKey); // Return cached token if available if (!empty($token)) { return $token; } try { // Requesting a new access token from the Rakuten API $response = Http::throw() ->asForm() ->withHeaders([ 'Authorization' => sprintf('Bearer %s', config('services.rakuten.token_key')), ]) ->post('https://api.linksynergy.com/token', [ 'scope' => config('services.rakuten.sid'), ]); } catch (Exception $ex) { // Logging the exception for debugging purposes report($ex); return null; } // Verifying the API response and extracting the access token and its expiration time if (!$response->ok() || empty($response->json()['access_token']) || empty($response->json()['expires_in'])) { return null; } $accessToken = $response->json()['access_token']; $expire = $response->json()['expires_in']; // Caching the access token for the duration of its validity to reduce API calls Cache::put($cacheKey, $accessToken, $expire); return $accessToken; } }