/** * Authorize the user object. If the initial authorization has not been * completed, the `auth_url` is returned. If authorization has already * happened and the `access_token` hasn't passed its expiration time, we * are already authorized. Otherwise, if the `access_token` has expired, * request a new token. This method also retrieves the user's API endpoints. * * @param null|string $redirectUrl The URL the user is redirected to after * navigating to the authorization URL. * * @return array */ public function authorize($redirectUrl = null) { $retval = ['success' => true, 'data' => []]; $config = $this->cache->loadAccountConfig($this->email) ?: []; $this->token = new ParameterBag($config); $scope = rawurlencode(implode(' ', $this->scope)); $response = null; if (!$this->token["access_token"]) { if (!$redirectUrl) { $retval = ['success' => false, 'data' => ['message' => 'Initial authorization required.', 'auth_url' => "https://www.amazon.com/ap/oa?client_id={$this->clientId}&scope={$scope}&response_type=code&redirect_uri=http://localhost"]]; return $retval; } $response = $this->requestAuthorization($redirectUrl); if (!$response["success"]) { return $response; } } else { if (time() - $this->token["last_authorized"] > $this->token["expires_in"]) { $response = $this->renewAuthorization(); if (!$response["success"]) { return $response; } } } if ($response && $response['data']) { $this->token->merge($response['data']); } if (!$this->token["metadata_url"] || !$this->token["content_url"]) { $response = $this->fetchEndpoint(); if (!$response['success']) { return $response; } $this->token['metadata_url'] = $response['data']['metadataUrl']; $this->token['content_url'] = $response['data']['contentUrl']; } $this->checkpoint = $this->token["checkpoint"]; $this->metadataUrl = $this->token["metadata_url"]; $this->contentUrl = $this->token["content_url"]; $this->save(); return $retval; }